diff --git a/sdk/src/rtc/MessageHandler.js b/sdk/src/rtc/MessageHandler.js index 1b3ec2b6f14823688a74ec64ba32ad94102224fa..94e79edcbb3ab59a70b05b985df3a62bd8f7afd8 100644 --- a/sdk/src/rtc/MessageHandler.js +++ b/sdk/src/rtc/MessageHandler.js @@ -27,42 +27,44 @@ class MessageHandler { sendStartCmdControl(startParams) { const mediaConfig = startParams.media_config; - if (mediaConfig.encode_type !== 0) { - delete mediaConfig.remote_scheduling_elb_ip; - delete mediaConfig.remote_scheduling_elb_port; + if (typeof mediaConfig !== 'string') { + if (mediaConfig.encode_type !== 0) { + delete mediaConfig.remote_scheduling_elb_ip; + delete mediaConfig.remote_scheduling_elb_port; + } + startParams.media_config = this._objToString(mediaConfig, ':'); } - startParams.media_config = this._objToString(mediaConfig, ':'); const parametersMap = new Map(); parametersMap.set(KEY_COMMAND, PROTOCOL_CONFIG.CMD_TYPE.START); for (let key in startParams) { parametersMap.set(key, startParams[key]); } - this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); + return this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); } sendStopCmdControl() { - this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.STOP) + return this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.STOP) } sendPauseCmdControl() { - this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.PAUSE); + return this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.PAUSE); } sendResumeCmdControl() { - this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.RESUME); + return this._sendNormalCmdControl(PROTOCOL_CONFIG.CMD_TYPE.RESUME); } _sendNormalCmdControl(cmdType) { const parametersMap = new Map(); parametersMap.set(KEY_COMMAND, cmdType); - this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); + return this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); } sendHeartBeat() { const parametersMap = new Map(); parametersMap.set(KEY_COMMAND, PROTOCOL_CONFIG.CMD_TYPE.HEART_BEAT); - this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.HEART_BEAT, parametersMap); + return this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.HEART_BEAT, parametersMap); } sendMediaConfig(mediaConfig) { @@ -70,7 +72,7 @@ class MessageHandler { const parametersMap = new Map(); parametersMap.set(KEY_COMMAND, PROTOCOL_CONFIG.CMD_TYPE.SET_MEDIA_CONFIG); parametersMap.set(KEY_MEDIA_CONFIG, mediaConfigStr); - this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); + return this._sendCommandMsgData(PROTOCOL_CONFIG.MSG_TYPE.CMD_CONTROL, parametersMap); } sendTouchMsgData(touchData) { @@ -92,12 +94,12 @@ class MessageHandler { msgBody[14] = touchData.height & 0xFF; msgBody[15] = (touchData.width >> 8) & 0xFF; msgBody[16] = touchData.width & 0xFF; - this._sendMsgData(PROTOCOL_CONFIG.MSG_TYPE.TOUCH, msgBody, 17); + return this._sendMsgData(PROTOCOL_CONFIG.MSG_TYPE.TOUCH, msgBody, 17); } _sendCommandMsgData(msgType, parametersMap) { const msgBody = this._makeCommand(parametersMap); - this._sendMsgData(msgType, msgBody, msgBody.length); + return this._sendMsgData(msgType, msgBody, msgBody.length); } _sendMsgData(msgType, msgBody, bodyLen) { @@ -112,7 +114,7 @@ class MessageHandler { msgData[6] = ((bodyLen >> 8) & 0xFF); msgData[7] = ((bodyLen) & 0xFF); msgData.set(msgBody, 8); - this.sendMessage(msgData); + return this.sendMessage(msgData); } _generateChecksum(msgType) { diff --git a/sdk/src/rtc/RTCChannel.js b/sdk/src/rtc/RTCChannel.js index 806333826a9ebdb633f79f17c897e7abd603bf81..726cfa73c86f39e25d59c07f450f1af1ee90e5d8 100644 --- a/sdk/src/rtc/RTCChannel.js +++ b/sdk/src/rtc/RTCChannel.js @@ -49,7 +49,7 @@ class RTCChannel { sdkVersion: __APP_VERSION__, } this.options.autoRotate = options.auto_rotate && this.options.isMobile; - if(this.options.autoRotate){ + if (this.options.autoRotate) { this.autoRotation = null; } @@ -62,7 +62,7 @@ class RTCChannel { this._configEnv(this.options.env); this.options.role = 'anchor'; - this.options.userId = this._generateGUID(); + this.options.userId = this.options.userId || this._generateGUID(); this.resolution = { x: 720, @@ -134,11 +134,11 @@ class RTCChannel { inputId: this.keyboardInput && this.keyboardInput.inputId || '' }); this.touchHandler.start(); - if(this.touchHandler.displayBox.width && this.touchHandler.displayBox.height) { + if (this.touchHandler.displayBox.width && this.touchHandler.displayBox.height) { const ctrlEle = document.getElementById('controlBtn'); const containerEle = document.getElementById('container'); - const left = (containerEle.offsetWidth - this.touchHandler.displayBox.width)/2 + 20; - const top = (containerEle.offsetHeight - this.touchHandler.displayBox.height)/2 + 125; + const left = (containerEle.offsetWidth - this.touchHandler.displayBox.width) / 2 + 20; + const top = (containerEle.offsetHeight - this.touchHandler.displayBox.height) / 2 + 125; if (this.options.isMobile) { ctrlEle.style.top = `20%`; ctrlEle.style.left = `5%`; @@ -148,9 +148,9 @@ class RTCChannel { } } - if(this.options.autoRotate){ + if (this.options.autoRotate) { this.autoRotation = new AutoRotation(this.options.containerId, - DEFAULT_ORIENTATION, this.options.isMobile,rotateDegrees => { + DEFAULT_ORIENTATION, this.options.isMobile, rotateDegrees => { // 旋转后更新触控,并根据旋转角度判断使用云机键盘还是真机键盘 this.touchHandler.resize(); }); @@ -286,7 +286,8 @@ class RTCChannel { return this.client.sendCommandMsg(message); } - sendMessage2(message) {} + sendMessage2(message) { + } _generateGUID() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => { @@ -357,6 +358,7 @@ class RTCChannel { appId: this.options.appId, countryCode: 'CN', }); + console.log(`rtc engine version:${HRTC.VERSION}`); } _initClientEvent() { @@ -376,13 +378,17 @@ class RTCChannel { }); this.client.on('peer-join', (event) => { console.log(`peer-join`); + this.cloudOnline = true; }); this.client.on('peer-leave', (event) => { console.log(`peer-leave`); + this.cloudOnline = false; + this.isSendStartCmdControl = false; }); this.client.on('stream-added', (event) => { console.log(`stream-add`); this._subscribeStream(event.stream); + this._sendStartCmdControl(); }); this.client.on('stream-updated', (event) => { console.log('stream-updated'); @@ -407,11 +413,24 @@ class RTCChannel { }); this.client.on('cmd-channel-established', () => { console.log('cmd-channel-established'); - this.messageHandler.sendStartCmdControl(this.startParams); - // this._startHeartBeat(); + this.cmdChannelEstablished = true; + this._sendStartCmdControl(); }); } + _sendStartCmdControl() { + if (this.isSendStartCmdControl || !this.cmdChannelEstablished || !this.cloudOnline) { + // 已发送、未建立通道、云机不在线情况,不发送cmd start,直接返回 + console.log(`_sendStartCmdControl return isSendStartCmdControl:${this.isSendStartCmdControl}, cmdChannelEstablished:${this.cmdChannelEstablished}, cloudOnline:${this.cloudOnline}`); + return; + } + let ret = this.messageHandler.sendStartCmdControl(this.startParams); + console.log(`_sendStartCmdControl ret:${ret}`); + if (ret) { + this.isSendStartCmdControl = true; + } + } + _joinRoomPre() { this.client.enableCommandMsg(true); this.client.setNetworkBandwidth({maxBandwidth: 30 * 1024}); @@ -487,7 +506,7 @@ class RTCChannel { } _stopHeartBeat() { - if(this.heartBeatTimer){ + if (this.heartBeatTimer) { clearTimeout(this.heartBeatTimer); } } @@ -577,13 +596,13 @@ class RTCChannel { this.messageHandler.dealReceiveMsg( commandMsgInfo.msg, { - cmdControlCallback: this._dealCmdControlCallback, - heartBeatCallback: this._dealHeartBeatCallback, - orientationCallback: this._dealOrientationCallback, - keyboardInputCallback: this._dealKeyboardInputCallback, - cameraCallback: this._dealCameraCallback, - microphoneCallback: this._dealMicrophoneCallback, - phoneControlCallback: this._dealPhoneControlCallback + cmdControlCallback: this._dealCmdControlCallback.bind(this), + heartBeatCallback: this._dealHeartBeatCallback.bind(this), + orientationCallback: this._dealOrientationCallback.bind(this), + keyboardInputCallback: this._dealKeyboardInputCallback.bind(this), + cameraCallback: this._dealCameraCallback.bind(this), + microphoneCallback: this._dealMicrophoneCallback.bind(this), + phoneControlCallback: this._dealPhoneControlCallback.bind(this), } ) } diff --git a/sdk/src/rtc/sdk/hrtc.js b/sdk/src/rtc/sdk/hrtc.js index 9661ee58fcf873a667b618ba74c989b1f6d41e9a..a634d009a65269db4a5549b628fec57402ee48fb 100644 --- a/sdk/src/rtc/sdk/hrtc.js +++ b/sdk/src/rtc/sdk/hrtc.js @@ -1,4 +1,4 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).HRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t(e)}function r(e){var r=function(e,r){if("object"!==t(e)||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,r||"default");if("object"!==t(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"===t(r)?r:String(r)}function i(e,t,i){return(t=r(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function n(e,t,r,i,n){var o={};return Object.keys(i).forEach((function(e){o[e]=i[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce((function(r,i){return i(e,t,r)||r}),o),n&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(n):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}var o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function s(e){var t=e.default;if("function"==typeof t){var r=function(){return t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})})),r}var a=function(e){return e&&e.Math==Math&&e},c=a("object"==typeof globalThis&&globalThis)||a("object"==typeof window&&window)||a("object"==typeof self&&self)||a("object"==typeof o&&o)||function(){return this}()||Function("return this")(),u={},d=function(e){try{return!!e()}catch(t){return!0}},l=!d((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),h=!d((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),f=h,p=Function.prototype.call,m=f?p.bind(p):function(){return p.apply(p,arguments)},g={},_={}.propertyIsEnumerable,S=Object.getOwnPropertyDescriptor,v=S&&!_.call({1:2},1);g.f=v?function(e){var t=S(this,e);return!!t&&t.enumerable}:_;var y,I,T=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},R=h,E=Function.prototype,b=E.bind,C=E.call,A=R&&b.bind(C,C),w=R?function(e){return e&&A(e)}:function(e){return e&&function(){return C.apply(e,arguments)}},k=w,O=k({}.toString),P=k("".slice),M=function(e){return P(O(e),8,-1)},D=d,N=M,U=Object,x=w("".split),L=D((function(){return!U("z").propertyIsEnumerable(0)}))?function(e){return"String"==N(e)?x(e,""):U(e)}:U,B=TypeError,V=function(e){if(null==e)throw B("Can't call method on "+e);return e},Y=L,j=V,F=function(e){return Y(j(e))},H=function(e){return"function"==typeof e},K=H,z=function(e){return"object"==typeof e?null!==e:K(e)},W=c,G=H,J=function(e,t){return arguments.length<2?(r=W[e],G(r)?r:void 0):W[e]&&W[e][t];var r},q=w({}.isPrototypeOf),X=J("navigator","userAgent")||"",Q=c,$=X,Z=Q.process,ee=Q.Deno,te=Z&&Z.versions||ee&&ee.version,re=te&&te.v8;re&&(I=(y=re.split("."))[0]>0&&y[0]<4?1:+(y[0]+y[1])),!I&&$&&(!(y=$.match(/Edge\/(\d+)/))||y[1]>=74)&&(y=$.match(/Chrome\/(\d+)/))&&(I=+y[1]);var ie=I,ne=ie,oe=d,se=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ae=se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ce=J,ue=H,de=q,le=Object,he=ae?function(e){return"symbol"==typeof e}:function(e){var t=ce("Symbol");return ue(t)&&de(t.prototype,le(e))},fe=String,pe=function(e){try{return fe(e)}catch(t){return"Object"}},me=H,ge=pe,_e=TypeError,Se=function(e){if(me(e))return e;throw _e(ge(e)+" is not a function")},ve=Se,ye=function(e,t){var r=e[t];return null==r?void 0:ve(r)},Ie=m,Te=H,Re=z,Ee=TypeError,be={exports:{}},Ce=c,Ae=Object.defineProperty,we=function(e,t){try{Ae(Ce,e,{value:t,configurable:!0,writable:!0})}catch(r){Ce[e]=t}return t},ke=we,Oe="__core-js_shared__",Pe=c[Oe]||ke(Oe,{}),Me=Pe;(be.exports=function(e,t){return Me[e]||(Me[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.23.3",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.23.3/LICENSE",source:"https://github.com/zloirock/core-js"});var De=V,Ne=Object,Ue=function(e){return Ne(De(e))},xe=Ue,Le=w({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return Le(xe(e),t)},Ve=w,Ye=0,je=Math.random(),Fe=Ve(1..toString),He=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Fe(++Ye+je,36)},Ke=c,ze=be.exports,We=Be,Ge=He,Je=se,qe=ae,Xe=ze("wks"),Qe=Ke.Symbol,$e=Qe&&Qe.for,Ze=qe?Qe:Qe&&Qe.withoutSetter||Ge,et=function(e){if(!We(Xe,e)||!Je&&"string"!=typeof Xe[e]){var t="Symbol."+e;Je&&We(Qe,e)?Xe[e]=Qe[e]:Xe[e]=qe&&$e?$e(t):Ze(t)}return Xe[e]},tt=m,rt=z,it=he,nt=ye,ot=function(e,t){var r,i;if("string"===t&&Te(r=e.toString)&&!Re(i=Ie(r,e)))return i;if(Te(r=e.valueOf)&&!Re(i=Ie(r,e)))return i;if("string"!==t&&Te(r=e.toString)&&!Re(i=Ie(r,e)))return i;throw Ee("Can't convert object to primitive value")},st=TypeError,at=et("toPrimitive"),ct=function(e,t){if(!rt(e)||it(e))return e;var r,i=nt(e,at);if(i){if(void 0===t&&(t="default"),r=tt(i,e,t),!rt(r)||it(r))return r;throw st("Can't convert object to primitive value")}return void 0===t&&(t="number"),ot(e,t)},ut=ct,dt=he,lt=function(e){var t=ut(e,"string");return dt(t)?t:t+""},ht=z,ft=c.document,pt=ht(ft)&&ht(ft.createElement),mt=function(e){return pt?ft.createElement(e):{}},gt=mt,_t=!l&&!d((function(){return 7!=Object.defineProperty(gt("div"),"a",{get:function(){return 7}}).a})),St=l,vt=m,yt=g,It=T,Tt=F,Rt=lt,Et=Be,bt=_t,Ct=Object.getOwnPropertyDescriptor;u.f=St?Ct:function(e,t){if(e=Tt(e),t=Rt(t),bt)try{return Ct(e,t)}catch(r){}if(Et(e,t))return It(!vt(yt.f,e,t),e[t])};var At={},wt=l&&d((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),kt=z,Ot=String,Pt=TypeError,Mt=function(e){if(kt(e))return e;throw Pt(Ot(e)+" is not an object")},Dt=l,Nt=_t,Ut=wt,xt=Mt,Lt=lt,Bt=TypeError,Vt=Object.defineProperty,Yt=Object.getOwnPropertyDescriptor,jt="enumerable",Ft="configurable",Ht="writable";At.f=Dt?Ut?function(e,t,r){if(xt(e),t=Lt(t),xt(r),"function"==typeof e&&"prototype"===t&&"value"in r&&Ht in r&&!r[Ht]){var i=Yt(e,t);i&&i[Ht]&&(e[t]=r.value,r={configurable:Ft in r?r[Ft]:i[Ft],enumerable:jt in r?r[jt]:i[jt],writable:!1})}return Vt(e,t,r)}:Vt:function(e,t,r){if(xt(e),t=Lt(t),xt(r),Nt)try{return Vt(e,t,r)}catch(i){}if("get"in r||"set"in r)throw Bt("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var Kt=At,zt=T,Wt=l?function(e,t,r){return Kt.f(e,t,zt(1,r))}:function(e,t,r){return e[t]=r,e},Gt={exports:{}},Jt=l,qt=Be,Xt=Function.prototype,Qt=Jt&&Object.getOwnPropertyDescriptor,$t=qt(Xt,"name"),Zt={EXISTS:$t,PROPER:$t&&"something"===function(){}.name,CONFIGURABLE:$t&&(!Jt||Jt&&Qt(Xt,"name").configurable)},er=H,tr=Pe,rr=w(Function.toString);er(tr.inspectSource)||(tr.inspectSource=function(e){return rr(e)});var ir,nr,or,sr=tr.inspectSource,ar=H,cr=sr,ur=c.WeakMap,dr=ar(ur)&&/native code/.test(cr(ur)),lr=be.exports,hr=He,fr=lr("keys"),pr=function(e){return fr[e]||(fr[e]=hr(e))},mr={},gr=dr,_r=c,Sr=w,vr=z,yr=Wt,Ir=Be,Tr=Pe,Rr=pr,Er=mr,br="Object already initialized",Cr=_r.TypeError,Ar=_r.WeakMap;if(gr||Tr.state){var wr=Tr.state||(Tr.state=new Ar),kr=Sr(wr.get),Or=Sr(wr.has),Pr=Sr(wr.set);ir=function(e,t){if(Or(wr,e))throw new Cr(br);return t.facade=e,Pr(wr,e,t),t},nr=function(e){return kr(wr,e)||{}},or=function(e){return Or(wr,e)}}else{var Mr=Rr("state");Er[Mr]=!0,ir=function(e,t){if(Ir(e,Mr))throw new Cr(br);return t.facade=e,yr(e,Mr,t),t},nr=function(e){return Ir(e,Mr)?e[Mr]:{}},or=function(e){return Ir(e,Mr)}}var Dr={set:ir,get:nr,has:or,enforce:function(e){return or(e)?nr(e):ir(e,{})},getterFor:function(e){return function(t){var r;if(!vr(t)||(r=nr(t)).type!==e)throw Cr("Incompatible receiver, "+e+" required");return r}}},Nr=d,Ur=H,xr=Be,Lr=l,Br=Zt.CONFIGURABLE,Vr=sr,Yr=Dr.enforce,jr=Dr.get,Fr=Object.defineProperty,Hr=Lr&&!Nr((function(){return 8!==Fr((function(){}),"length",{value:8}).length})),Kr=String(String).split("String"),zr=Gt.exports=function(e,t,r){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!xr(e,"name")||Br&&e.name!==t)&&(Lr?Fr(e,"name",{value:t,configurable:!0}):e.name=t),Hr&&r&&xr(r,"arity")&&e.length!==r.arity&&Fr(e,"length",{value:r.arity});try{r&&xr(r,"constructor")&&r.constructor?Lr&&Fr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var i=Yr(e);return xr(i,"source")||(i.source=Kr.join("string"==typeof t?t:"")),e};Function.prototype.toString=zr((function(){return Ur(this)&&jr(this).source||Vr(this)}),"toString");var Wr=H,Gr=At,Jr=Gt.exports,qr=we,Xr=function(e,t,r,i){i||(i={});var n=i.enumerable,o=void 0!==i.name?i.name:t;if(Wr(r)&&Jr(r,o,i),i.global)n?e[t]=r:qr(t,r);else{try{i.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=r:Gr.f(e,t,{value:r,enumerable:!1,configurable:!i.nonConfigurable,writable:!i.nonWritable})}return e},Qr={},$r=Math.ceil,Zr=Math.floor,ei=Math.trunc||function(e){var t=+e;return(t>0?Zr:$r)(t)},ti=ei,ri=function(e){var t=+e;return t!=t||0===t?0:ti(t)},ii=ri,ni=Math.max,oi=Math.min,si=function(e,t){var r=ii(e);return r<0?ni(r+t,0):oi(r,t)},ai=ri,ci=Math.min,ui=function(e){return e>0?ci(ai(e),9007199254740991):0},di=ui,li=function(e){return di(e.length)},hi=F,fi=si,pi=li,mi=function(e){return function(t,r,i){var n,o=hi(t),s=pi(o),a=fi(i,s);if(e&&r!=r){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===r)return e||a||0;return!e&&-1}},gi={includes:mi(!0),indexOf:mi(!1)},_i=Be,Si=F,vi=gi.indexOf,yi=mr,Ii=w([].push),Ti=function(e,t){var r,i=Si(e),n=0,o=[];for(r in i)!_i(yi,r)&&_i(i,r)&&Ii(o,r);for(;t.length>n;)_i(i,r=t[n++])&&(~vi(o,r)||Ii(o,r));return o},Ri=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ei=Ti,bi=Ri.concat("length","prototype");Qr.f=Object.getOwnPropertyNames||function(e){return Ei(e,bi)};var Ci={};Ci.f=Object.getOwnPropertySymbols;var Ai=J,wi=Qr,ki=Ci,Oi=Mt,Pi=w([].concat),Mi=Ai("Reflect","ownKeys")||function(e){var t=wi.f(Oi(e)),r=ki.f;return r?Pi(t,r(e)):t},Di=Be,Ni=Mi,Ui=u,xi=At,Li=function(e,t,r){for(var i=Ni(t),n=xi.f,o=Ui.f,s=0;s=51&&/native code/.test(e))return!1;var r=new Ts((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};return(r.constructor={})[ks]=i,!(Os=r.then((function(){}))instanceof i)||!t&&As&&!Ps})),Ds={CONSTRUCTOR:Ms,REJECTION_EVENT:Ps,SUBCLASSING:Os},Ns={},Us=Se,xs=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i})),this.resolve=Us(t),this.reject=Us(r)};Ns.f=function(e){return new xs(e)};var Ls,Bs,Vs,Ys=en,js=tn,Fs=c,Hs=m,Ks=Xr,zs=un,Ws=fn,Gs=Sn,Js=Se,qs=H,Xs=z,Qs=In,$s=to,Zs=Xo.set,ea=ps,ta=function(e,t){var r=ms.console;r&&r.error&&(1==arguments.length?r.error(e):r.error(e,t))},ra=gs,ia=Ss,na=Dr,oa=vs,sa=Ns,aa="Promise",ca=Ds.CONSTRUCTOR,ua=Ds.REJECTION_EVENT,da=Ds.SUBCLASSING,la=na.getterFor(aa),ha=na.set,fa=oa&&oa.prototype,pa=oa,ma=fa,ga=Fs.TypeError,_a=Fs.document,Sa=Fs.process,va=sa.f,ya=va,Ia=!!(_a&&_a.createEvent&&Fs.dispatchEvent),Ta="unhandledrejection",Ra=function(e){var t;return!(!Xs(e)||!qs(t=e.then))&&t},Ea=function(e,t){var r,i,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,u=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&ka(t),t.rejection=1),!0===a?r=o:(d&&d.enter(),r=a(o),d&&(d.exit(),n=!0)),r===e.promise?u(ga("Promise-chain cycle")):(i=Ra(r))?Hs(i,r,c,u):c(r)):u(o)}catch(jN){d&&!n&&d.exit(),u(jN)}},ba=function(e,t){e.notified||(e.notified=!0,ea((function(){for(var r,i=e.reactions;r=i.get();)Ea(r,e);e.notified=!1,t&&!e.rejection&&Aa(e)})))},Ca=function(e,t,r){var i,n;Ia?((i=_a.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),Fs.dispatchEvent(i)):i={promise:t,reason:r},!ua&&(n=Fs["on"+e])?n(i):e===Ta&&ta("Unhandled promise rejection",r)},Aa=function(e){Hs(Zs,Fs,(function(){var t,r=e.facade,i=e.value;if(wa(e)&&(t=ra((function(){js?Sa.emit("unhandledRejection",i,r):Ca(Ta,r,i)})),e.rejection=js||wa(e)?2:1,t.error))throw t.value}))},wa=function(e){return 1!==e.rejection&&!e.parent},ka=function(e){Hs(Zs,Fs,(function(){var t=e.facade;js?Sa.emit("rejectionHandled",t):Ca("rejectionhandled",t,e.value)}))},Oa=function(e,t,r){return function(i){e(t,i,r)}},Pa=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,ba(e,!0))},Ma=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw ga("Promise can't be resolved itself");var i=Ra(t);i?ea((function(){var r={done:!1};try{Hs(i,t,Oa(Ma,r,e),Oa(Pa,r,e))}catch(jN){Pa(r,jN,e)}})):(e.value=t,e.state=1,ba(e,!1))}catch(jN){Pa({done:!1},jN,e)}}};if(ca&&(ma=(pa=function(e){Qs(this,ma),Js(e),Hs(Ls,this);var t=la(this);try{e(Oa(Ma,t),Oa(Pa,t))}catch(jN){Pa(t,jN)}}).prototype,(Ls=function(e){ha(this,{type:aa,done:!1,notified:!1,parent:!1,reactions:new ia,rejection:!1,state:0,value:void 0})}).prototype=Ks(ma,"then",(function(e,t){var r=la(this),i=va($s(this,pa));return r.parent=!0,i.ok=!qs(e)||e,i.fail=qs(t)&&t,i.domain=js?Sa.domain:void 0,0==r.state?r.reactions.add(i):ea((function(){Ea(i,r)})),i.promise})),Bs=function(){var e=new Ls,t=la(e);this.promise=e,this.resolve=Oa(Ma,t),this.reject=Oa(Pa,t)},sa.f=va=function(e){return e===pa||undefined===e?new Bs(e):ya(e)},qs(oa)&&fa!==Object.prototype)){Vs=fa.then,da||Ks(fa,"then",(function(e,t){var r=this;return new pa((function(e,t){Hs(Vs,r,e,t)})).then(e,t)}),{unsafe:!0});try{delete fa.constructor}catch(jN){}zs&&zs(fa,ma)}Ys({global:!0,constructor:!0,wrap:!0,forced:ca},{Promise:pa}),Ws(pa,aa,!1),Gs(aa);var Da={},Na=Da,Ua=et("iterator"),xa=Array.prototype,La=function(e){return void 0!==e&&(Na.Array===e||xa[Ua]===e)},Ba=kn,Va=ye,Ya=Da,ja=et("iterator"),Fa=function(e){if(null!=e)return Va(e,ja)||Va(e,"@@iterator")||Ya[Ba(e)]},Ha=m,Ka=Se,za=Mt,Wa=pe,Ga=Fa,Ja=TypeError,qa=function(e,t){var r=arguments.length<2?Ga(e):t;if(Ka(r))return za(Ha(r,e));throw Ja(Wa(e)+" is not iterable")},Xa=m,Qa=Mt,$a=ye,Za=lo,ec=m,tc=Mt,rc=pe,ic=La,nc=li,oc=q,sc=qa,ac=Fa,cc=function(e,t,r){var i,n;Qa(e);try{if(!(i=$a(e,"return"))){if("throw"===t)throw r;return r}i=Xa(i,e)}catch(jN){n=!0,i=jN}if("throw"===t)throw r;if(n)throw i;return Qa(i),r},uc=TypeError,dc=function(e,t){this.stopped=e,this.result=t},lc=dc.prototype,hc=function(e,t,r){var i,n,o,s,a,c,u,d=r&&r.that,l=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_ITERATOR),f=!(!r||!r.INTERRUPTED),p=Za(t,d),m=function(e){return i&&cc(i,"normal",e),new dc(!0,e)},g=function(e){return l?(tc(e),f?p(e[0],e[1],m):p(e[0],e[1])):f?p(e,m):p(e)};if(h)i=e;else{if(!(n=ac(e)))throw uc(rc(e)+" is not iterable");if(ic(n)){for(o=0,s=nc(e);s>o;o++)if((a=g(e[o]))&&oc(lc,a))return a;return new dc(!1)}i=sc(e,n)}for(c=i.next;!(u=ec(c,i)).done;){try{a=g(u.value)}catch(jN){cc(i,"throw",jN)}if("object"==typeof a&&a&&oc(lc,a))return a}return new dc(!1)},fc=et("iterator"),pc=!1;try{var mc=0,gc={next:function(){return{done:!!mc++}},return:function(){pc=!0}};gc[fc]=function(){return this},Array.from(gc,(function(){throw 2}))}catch(jN){}var _c=function(e,t){if(!t&&!pc)return!1;var r=!1;try{var i={};i[fc]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(jN){}return r},Sc=vs,vc=Ds.CONSTRUCTOR||!_c((function(e){Sc.all(e).then(void 0,(function(){}))})),yc=m,Ic=Se,Tc=Ns,Rc=gs,Ec=hc;en({target:"Promise",stat:!0,forced:vc},{all:function(e){var t=this,r=Tc.f(t),i=r.resolve,n=r.reject,o=Rc((function(){var r=Ic(t.resolve),o=[],s=0,a=1;Ec(e,(function(e){var c=s++,u=!1;a++,yc(r,t,e).then((function(e){u||(u=!0,o[c]=e,--a||i(o))}),n)})),--a||i(o)}));return o.error&&n(o.value),r.promise}});var bc=en,Cc=Ds.CONSTRUCTOR,Ac=vs,wc=J,kc=H,Oc=Xr,Pc=Ac&&Ac.prototype;if(bc({target:"Promise",proto:!0,forced:Cc,real:!0},{catch:function(e){return this.then(void 0,e)}}),kc(Ac)){var Mc=wc("Promise").prototype.catch;Pc.catch!==Mc&&Oc(Pc,"catch",Mc,{unsafe:!0})}var Dc=m,Nc=Se,Uc=Ns,xc=gs,Lc=hc;en({target:"Promise",stat:!0,forced:vc},{race:function(e){var t=this,r=Uc.f(t),i=r.reject,n=xc((function(){var n=Nc(t.resolve);Lc(e,(function(e){Dc(n,t,e).then(r.resolve,i)}))}));return n.error&&i(n.value),r.promise}});var Bc=m,Vc=Ns;en({target:"Promise",stat:!0,forced:Ds.CONSTRUCTOR},{reject:function(e){var t=Vc.f(this);return Bc(t.reject,void 0,e),t.promise}});var Yc=Mt,jc=z,Fc=Ns,Hc=function(e,t){if(Yc(e),jc(t)&&t.constructor===e)return t;var r=Fc.f(e);return(0,r.resolve)(t),r.promise},Kc=en,zc=Ds.CONSTRUCTOR,Wc=Hc;J("Promise"),Kc({target:"Promise",stat:!0,forced:zc},{resolve:function(e){return Wc(this,e)}});let Gc=function(e){return e[e.RTC_ERR_CODE_SUCCESS=0]="RTC_ERR_CODE_SUCCESS",e[e.RTC_ERR_CODE_RTC_SDK_ERROR=90000001]="RTC_ERR_CODE_RTC_SDK_ERROR",e[e.RTC_ERR_CODE_WAIT_RSP_TIMEOUT=90000004]="RTC_ERR_CODE_WAIT_RSP_TIMEOUT",e[e.RTC_ERR_CODE_INVALID_PARAMETER=90000005]="RTC_ERR_CODE_INVALID_PARAMETER",e[e.RTC_ERR_CODE_INVALID_OPERATION=90100001]="RTC_ERR_CODE_INVALID_OPERATION",e[e.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES=90100002]="RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_DEVICES=90100003]="RTC_ERR_CODE_NO_AVAILABLE_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES=90100004]="RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES=90100005]="RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES=90100006]="RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES",e[e.RTC_ERR_CODE_STATUS_ERROR=90100007]="RTC_ERR_CODE_STATUS_ERROR",e[e.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED=90100008]="RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED",e[e.RTC_ERR_CODE_WAIT_CONFIG_FAIL=90100009]="RTC_ERR_CODE_WAIT_CONFIG_FAIL",e[e.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL=90100010]="RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL",e[e.RTC_ERR_CODE_REGION_NOT_COVERED=90100011]="RTC_ERR_CODE_REGION_NOT_COVERED",e[e.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT=90100012]="RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT",e[e.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT=90100013]="RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT",e[e.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN=90100014]="RTC_ERR_CODE_WEBSOCKET_NOT_OPEN",e[e.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED=90100015]="RTC_ERR_CODE_WEBSOCKET_INTERRUPTED",e[e.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR=90100016]="RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR",e[e.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED=90100017]="RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED",e[e.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED=90100018]="RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED",e[e.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND=90100019]="RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND",e[e.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE=90100020]="RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE",e[e.RTC_ERR_CODE_PLAY_NOT_ALLOW=90100021]="RTC_ERR_CODE_PLAY_NOT_ALLOW",e[e.RTC_ERR_CODE_ROLE_NO_PERMISSION=90100022]="RTC_ERR_CODE_ROLE_NO_PERMISSION",e[e.RTC_ERR_CODE_ANSWER_SDP_INVALID=90100023]="RTC_ERR_CODE_ANSWER_SDP_INVALID",e[e.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED=90100024]="RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED",e[e.RTC_ERR_CODE_WEBRTC_UNSUPPORTED=90100025]="RTC_ERR_CODE_WEBRTC_UNSUPPORTED",e[e.RTC_ERR_CODE_MEDIA_NETWORK_ERROR=90100026]="RTC_ERR_CODE_MEDIA_NETWORK_ERROR",e[e.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM=90100027]="RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM",e[e.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM=90100028]="RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM",e[e.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED=90100029]="RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED",e[e.RTC_ERR_CODE_SIGNATURE_EXPIRED=90100030]="RTC_ERR_CODE_SIGNATURE_EXPIRED",e[e.RTC_ERR_CODE_SIGNATURE_INVALID=90100031]="RTC_ERR_CODE_SIGNATURE_INVALID",e[e.RTC_ERR_CODE_RTC_ACS=90100100]="RTC_ERR_CODE_RTC_ACS",e[e.RTC_ERR_CODE_RTC_CONTROL_ERROR=90100200]="RTC_ERR_CODE_RTC_CONTROL_ERROR",e[e.RTC_ERR_CODE_SFU_ERROR=90100600]="RTC_ERR_CODE_SFU_ERROR",e}({});const Jc={[Gc.RTC_ERR_CODE_SUCCESS]:"success",[Gc.RTC_ERR_CODE_RTC_SDK_ERROR]:"sdk internal error",[Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES]:"not support enumerate devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES]:"no available devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES]:"no available video input devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES]:"no available audio input devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES]:"no available audio output devices",[Gc.RTC_ERR_CODE_STATUS_ERROR]:"room status error",[Gc.RTC_ERR_CODE_INVALID_PARAMETER]:"invalid parameter",[Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED]:'websocket connection state is not "CONNECTED"',[Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN]:"websocket is not open",[Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL]:"wait server config fail",[Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT]:"message response timeout",[Gc.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL]:"publish response fail",[Gc.RTC_ERR_CODE_REGION_NOT_COVERED]:"current region is not covered, service unavailable",[Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT]:"websocket connect timeout",[Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT]:"websocket reconnect timeout",[Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED]:"websocket connection state is idle, interrupt operation",[Gc.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED]:"capture failed, permission denied",[Gc.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED]:"capture failed, Constraint parameter invalid",[Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND]:"capture failed, requested device not found",[Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE]:"capture failed, maybe device is occupied by other application",[Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW]:"the user didn't interact with the document first, please trigger by gesture",[Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION]:"the user role have no permission to operate",[Gc.RTC_ERR_CODE_ANSWER_SDP_INVALID]:"the answer sdp is invalid",[Gc.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED]:"the upstream media is not supported",[Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED]:"the browser does not support",[Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR]:"media connection establish failed, please switch network or try again later",[Gc.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM]:"relay room number over maxium number.",[Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED]:"room stream status paused",[Gc.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM]:"joiner already exist in relay rooms.",[Gc.RTC_ERR_CODE_SIGNATURE_INVALID]:"signature invalid",[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]:"signature expired"};class qc extends Error{constructor(e,t){const r=e;let i,n="";r>9e7&&r<90100100||r<100?(i=r,n=t||r in Gc&&Jc[r]):r>=6e5&&r<7e5?(i=Gc.RTC_ERR_CODE_SFU_ERROR,n="code: ".concat(r,", msg: ").concat(t)):r>=2e5&&r<3e5?(i=Gc.RTC_ERR_CODE_RTC_CONTROL_ERROR,n="code: ".concat(r,", msg: ").concat(t)):r>=1e5&&r<2e5?(i=Gc.RTC_ERR_CODE_RTC_ACS,n="code: ".concat(r,", msg: ").concat(t)):(n="unknow error",i=r),super(n),this.code=i,this.message=n}getCode(){return this.code}getMsg(){return this.message}toString(){return'["code": '.concat(this.code,', "message": "').concat(this.message,'"]')}}var Xc=kn,Qc=String,$c=function(e){if("Symbol"===Xc(e))throw TypeError("Cannot convert a Symbol value to a string");return Qc(e)},Zc=en,eu=l,tu=c,ru=w,iu=Be,nu=H,ou=q,su=$c,au=At.f,cu=Li,uu=tu.Symbol,du=uu&&uu.prototype;if(eu&&nu(uu)&&(!("description"in du)||void 0!==uu().description)){var lu={},hu=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:su(arguments[0]),t=ou(du,this)?new uu(e):void 0===e?uu():uu(e);return""===e&&(lu[t]=!0),t};cu(hu,uu),hu.prototype=du,du.constructor=hu;var fu="Symbol(test)"==String(uu("test")),pu=ru(du.toString),mu=ru(du.valueOf),gu=/^Symbol\((.*)\)[^)]+$/,_u=ru("".replace),Su=ru("".slice);au(du,"description",{configurable:!0,get:function(){var e=mu(this),t=pu(e);if(iu(lu,e))return"";var r=fu?Su(t,7,-1):_u(t,gu,"$1");return""===r?void 0:r}}),Zc({global:!0,constructor:!0,forced:!0},{Symbol:hu})}var vu={},yu=Ti,Iu=Ri,Tu=Object.keys||function(e){return yu(e,Iu)},Ru=l,Eu=wt,bu=At,Cu=Mt,Au=F,wu=Tu;vu.f=Ru&&!Eu?Object.defineProperties:function(e,t){Cu(e);for(var r,i=Au(t),n=wu(t),o=n.length,s=0;o>s;)bu.f(e,r=n[s++],i[r]);return e};var ku,Ou=Mt,Pu=vu,Mu=Ri,Du=mr,Nu=ho,Uu=mt,xu="prototype",Lu="script",Bu=pr("IE_PROTO"),Vu=function(){},Yu=function(e){return"<"+Lu+">"+e+""},ju=function(e){e.write(Yu("")),e.close();var t=e.parentWindow.Object;return e=null,t},Fu=function(){try{ku=new ActiveXObject("htmlfile")}catch(jN){}var e,t,r;Fu="undefined"!=typeof document?document.domain&&ku?ju(ku):(t=Uu("iframe"),r="java"+Lu+":",t.style.display="none",Nu.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write(Yu("document.F=Object")),e.close(),e.F):ju(ku);for(var i=Mu.length;i--;)delete Fu[xu][Mu[i]];return Fu()};Du[Bu]=!0;var Hu=Object.create||function(e,t){var r;return null!==e?(Vu[xu]=Ou(e),r=new Vu,Vu[xu]=null,r[Bu]=e):r=Fu(),void 0===t?r:Pu.f(r,t)},Ku=et,zu=Hu,Wu=At.f,Gu=Ku("unscopables"),Ju=Array.prototype;null==Ju[Gu]&&Wu(Ju,Gu,{configurable:!0,value:zu(null)});var qu,Xu,Qu,$u=function(e){Ju[Gu][e]=!0},Zu=!d((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),ed=Be,td=H,rd=Ue,id=Zu,nd=pr("IE_PROTO"),od=Object,sd=od.prototype,ad=id?od.getPrototypeOf:function(e){var t=rd(e);if(ed(t,nd))return t[nd];var r=t.constructor;return td(r)&&t instanceof r?r.prototype:t instanceof od?sd:null},cd=d,ud=H,dd=ad,ld=Xr,hd=et("iterator"),fd=!1;[].keys&&("next"in(Qu=[].keys())?(Xu=dd(dd(Qu)))!==Object.prototype&&(qu=Xu):fd=!0);var pd=null==qu||cd((function(){var e={};return qu[hd].call(e)!==e}));pd&&(qu={}),ud(qu[hd])||ld(qu,hd,(function(){return this}));var md={IteratorPrototype:qu,BUGGY_SAFARI_ITERATORS:fd},gd=md.IteratorPrototype,_d=Hu,Sd=T,vd=fn,yd=Da,Id=function(){return this},Td=en,Rd=m,Ed=H,bd=function(e,t,r,i){var n=t+" Iterator";return e.prototype=_d(gd,{next:Sd(+!i,r)}),vd(e,n,!1),yd[n]=Id,e},Cd=ad,Ad=un,wd=fn,kd=Wt,Od=Xr,Pd=Da,Md=Zt.PROPER,Dd=Zt.CONFIGURABLE,Nd=md.IteratorPrototype,Ud=md.BUGGY_SAFARI_ITERATORS,xd=et("iterator"),Ld="keys",Bd="values",Vd="entries",Yd=function(){return this},jd=F,Fd=$u,Hd=Da,Kd=Dr,zd=At.f,Wd=function(e,t,r,i,n,o,s){bd(r,t,i);var a,c,u,d=function(e){if(e===n&&m)return m;if(!Ud&&e in f)return f[e];switch(e){case Ld:case Bd:case Vd:return function(){return new r(this,e)}}return function(){return new r(this)}},l=t+" Iterator",h=!1,f=e.prototype,p=f[xd]||f["@@iterator"]||n&&f[n],m=!Ud&&p||d(n),g="Array"==t&&f.entries||p;if(g&&(a=Cd(g.call(new e)))!==Object.prototype&&a.next&&(Cd(a)!==Nd&&(Ad?Ad(a,Nd):Ed(a[xd])||Od(a,xd,Yd)),wd(a,l,!0)),Md&&n==Bd&&p&&p.name!==Bd&&(Dd?kd(f,"name",Bd):(h=!0,m=function(){return Rd(p,this)})),n)if(c={values:d(Bd),keys:o?m:d(Ld),entries:d(Vd)},s)for(u in c)(Ud||h||!(u in f))&&Od(f,u,c[u]);else Td({target:t,proto:!0,forced:Ud||h},c);return f[xd]!==m&&Od(f,xd,m,{name:n}),Pd[t]=m,c},Gd=l,Jd="Array Iterator",qd=Kd.set,Xd=Kd.getterFor(Jd),Qd=Wd(Array,"Array",(function(e,t){qd(this,{type:Jd,target:jd(e),index:0,kind:t})}),(function(){var e=Xd(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==r?{value:i,done:!1}:"values"==r?{value:t[i],done:!1}:{value:[i,t[i]],done:!1}}),"values"),$d=Hd.Arguments=Hd.Array;if(Fd("keys"),Fd("values"),Fd("entries"),Gd&&"values"!==$d.name)try{zd($d,"name",{value:"values"})}catch(jN){}var Zd=m,el=Se,tl=Mt,rl=function(){for(var e,t=tl(this),r=el(t.delete),i=!0,n=0,o=arguments.length;n1?arguments[1]:void 0);return!cl(r,(function(e,r,n){if(!i(r,e,t))return n()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var ul=J,dl=lo,ll=m,hl=Se,fl=Mt,pl=to,ml=nl,gl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{filter:function(e){var t=fl(this),r=ml(t),i=dl(e,arguments.length>1?arguments[1]:void 0),n=new(pl(t,ul("Map"))),o=hl(n.set);return gl(r,(function(e,r){i(r,e,t)&&ll(o,n,e,r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var _l=Mt,Sl=lo,vl=nl,yl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{find:function(e){var t=_l(this),r=vl(t),i=Sl(e,arguments.length>1?arguments[1]:void 0);return yl(r,(function(e,r,n){if(i(r,e,t))return n(r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var Il=Mt,Tl=lo,Rl=nl,El=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{findKey:function(e){var t=Il(this),r=Rl(t),i=Tl(e,arguments.length>1?arguments[1]:void 0);return El(r,(function(e,r,n){if(i(r,e,t))return n(e)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var bl=Mt,Cl=nl,Al=function(e,t){return e===t||e!=e&&t!=t},wl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{includes:function(e){return wl(Cl(bl(this)),(function(t,r,i){if(Al(r,e))return i()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var kl=Mt,Ol=nl,Pl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{keyOf:function(e){return Pl(Ol(kl(this)),(function(t,r,i){if(r===e)return i(t)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var Ml=J,Dl=lo,Nl=m,Ul=Se,xl=Mt,Ll=to,Bl=nl,Vl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{mapKeys:function(e){var t=xl(this),r=Bl(t),i=Dl(e,arguments.length>1?arguments[1]:void 0),n=new(Ll(t,Ml("Map"))),o=Ul(n.set);return Vl(r,(function(e,r){Nl(o,n,i(r,e,t),r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var Yl=J,jl=lo,Fl=m,Hl=Se,Kl=Mt,zl=to,Wl=nl,Gl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{mapValues:function(e){var t=Kl(this),r=Wl(t),i=jl(e,arguments.length>1?arguments[1]:void 0),n=new(zl(t,Yl("Map"))),o=Hl(n.set);return Gl(r,(function(e,r){Fl(o,n,e,i(r,e,t))}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var Jl=Se,ql=Mt,Xl=hc;en({target:"Map",proto:!0,real:!0,arity:1,forced:!0},{merge:function(e){for(var t=ql(this),r=Jl(t.set),i=arguments.length,n=0;n1?arguments[1]:void 0);return oh(r,(function(e,r,n){if(i(r,e,t))return n()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var sh=m,ah=Mt,ch=Se,uh=TypeError;en({target:"Map",proto:!0,real:!0,forced:!0},{update:function(e,t){var r=ah(this),i=ch(r.get),n=ch(r.has),o=ch(r.set),s=arguments.length;ch(t);var a=sh(n,r,e);if(!a&&s<3)throw uh("Updating absent value");var c=a?sh(i,r,e):ch(s>2?arguments[2]:void 0)(e,r);return sh(o,r,e,t(c,e,r)),r}});var dh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},lh=mt("span").classList,hh=lh&&lh.constructor&&lh.constructor.prototype,fh=hh===Object.prototype?void 0:hh,ph=c,mh=dh,gh=fh,_h=Qd,Sh=Wt,vh=et,yh=vh("iterator"),Ih=vh("toStringTag"),Th=_h.values,Rh=function(e,t){if(e){if(e[yh]!==Th)try{Sh(e,yh,Th)}catch(jN){e[yh]=Th}if(e[Ih]||Sh(e,Ih,t),mh[t])for(var r in _h)if(e[r]!==_h[r])try{Sh(e,r,_h[r])}catch(jN){e[r]=_h[r]}}};for(var Eh in mh)Rh(ph[Eh]&&ph[Eh].prototype,Eh);Rh(gh,"DOMTokenList");var bh=M,Ch=Array.isArray||function(e){return"Array"==bh(e)},Ah=Gn,wh=z,kh=et("species"),Oh=Array,Ph=function(e){var t;return Ch(e)&&(t=e.constructor,(Ah(t)&&(t===Oh||Ch(t.prototype))||wh(t)&&null===(t=t[kh]))&&(t=void 0)),void 0===t?Oh:t},Mh=lo,Dh=L,Nh=Ue,Uh=li,xh=function(e,t){return new(Ph(e))(0===t?0:t)},Lh=w([].push),Bh=function(e){var t=1==e,r=2==e,i=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,u,d,l){for(var h,f,p=Nh(c),m=Dh(p),g=Mh(u,d),_=Uh(m),S=0,v=l||xh,y=t?v(c,_):r||s?v(c,0):void 0;_>S;S++)if((a||S in m)&&(f=g(h=m[S],S,p),e))if(t)y[S]=f;else if(f)switch(e){case 3:return!0;case 5:return h;case 6:return S;case 2:Lh(y,h)}else switch(e){case 4:return!1;case 7:Lh(y,h)}return o?-1:i||n?n:y}},Vh={forEach:Bh(0),map:Bh(1),filter:Bh(2),some:Bh(3),every:Bh(4),find:Bh(5),findIndex:Bh(6),filterReject:Bh(7)},Yh=d,jh=function(e,t){var r=[][e];return!!r&&Yh((function(){r.call(null,t||function(){return 1},1)}))},Fh=Vh.forEach,Hh=jh("forEach")?[].forEach:function(e){return Fh(this,e,arguments.length>1?arguments[1]:void 0)},Kh=c,zh=dh,Wh=fh,Gh=Hh,Jh=Wt,qh=function(e){if(e&&e.forEach!==Gh)try{Jh(e,"forEach",Gh)}catch(jN){e.forEach=Gh}};for(var Xh in zh)zh[Xh]&&qh(Kh[Xh]&&Kh[Xh].prototype);qh(Wh);var Qh=gi.includes,$h=$u;en({target:"Array",proto:!0,forced:d((function(){return!Array(1).includes()}))},{includes:function(e){return Qh(this,e,arguments.length>1?arguments[1]:void 0)}}),$h("includes");var Zh=Mt,ef=function(){var e=Zh(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},tf=d,rf=c.RegExp,nf=tf((function(){var e=rf("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),of=nf||tf((function(){return!rf("a","y").sticky})),sf=nf||tf((function(){var e=rf("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),af={BROKEN_CARET:sf,MISSED_STICKY:of,UNSUPPORTED_Y:nf},cf=d,uf=c.RegExp,df=cf((function(){var e=uf(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),lf=d,hf=c.RegExp,ff=lf((function(){var e=hf("(?b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$c")})),pf=m,mf=w,gf=$c,_f=ef,Sf=af,vf=be.exports,yf=Hu,If=Dr.get,Tf=df,Rf=ff,Ef=vf("native-string-replace",String.prototype.replace),bf=RegExp.prototype.exec,Cf=bf,Af=mf("".charAt),wf=mf("".indexOf),kf=mf("".replace),Of=mf("".slice),Pf=function(){var e=/a/,t=/b*/g;return pf(bf,e,"a"),pf(bf,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Mf=Sf.BROKEN_CARET,Df=void 0!==/()??/.exec("")[1];(Pf||Df||Mf||Tf||Rf)&&(Cf=function(e){var t,r,i,n,o,s,a,c=this,u=If(c),d=gf(e),l=u.raw;if(l)return l.lastIndex=c.lastIndex,t=pf(Cf,l,d),c.lastIndex=l.lastIndex,t;var h=u.groups,f=Mf&&c.sticky,p=pf(_f,c),m=c.source,g=0,_=d;if(f&&(p=kf(p,"y",""),-1===wf(p,"g")&&(p+="g"),_=Of(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Af(d,c.lastIndex-1))&&(m="(?: "+m+")",_=" "+_,g++),r=new RegExp("^(?:"+m+")",p)),Df&&(r=new RegExp("^"+m+"$(?!\\s)",p)),Pf&&(i=c.lastIndex),n=pf(bf,f?r:c,_),f?n?(n.input=Of(n.input,g),n[0]=Of(n[0],g),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Pf&&n&&(c.lastIndex=c.global?n.index+n[0].length:i),Df&&n&&n.length>1&&pf(Ef,n[0],r,(function(){for(o=1;o=a?e?"":void 0:(i=Jf(o,s))<55296||i>56319||s+1===a||(n=Jf(o,s+1))<56320||n>57343?e?Gf(o,s):i:e?qf(o,s,s+2):n-56320+(i-55296<<10)+65536}},Qf={codeAt:Xf(!1),charAt:Xf(!0)}.charAt,$f=w,Zf=Ue,ep=Math.floor,tp=$f("".charAt),rp=$f("".replace),ip=$f("".slice),np=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,op=/\$([$&'`]|\d{1,2})/g,sp=function(e,t,r,i,n,o){var s=r+e.length,a=i.length,c=op;return void 0!==n&&(n=Zf(n),c=np),rp(o,c,(function(o,c){var u;switch(tp(c,0)){case"$":return"$";case"&":return e;case"`":return ip(t,0,r);case"'":return ip(t,s);case"<":u=n[ip(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var l=ep(d/10);return 0===l?o:l<=a?void 0===i[l-1]?tp(c,1):i[l-1]+tp(c,1):o}u=i[d-1]}return void 0===u?"":u}))},ap=m,cp=Mt,up=H,dp=M,lp=Nf,hp=TypeError,fp=so,pp=m,mp=w,gp=function(e,t,r,i){var n=Vf(e),o=!Bf((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Bf((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[jf]=function(){return r},r.flags="",r[n]=/./[n]),r.exec=function(){return t=!0,null},r[n](""),!t}));if(!o||!s||r){var a=Uf(/./[n]),c=t(n,""[e],(function(e,t,r,i,n){var s=Uf(e),c=t.exec;return c===Lf||c===Ff.exec?o&&!n?{done:!0,value:a(t,r,i)}:{done:!0,value:s(r,t,i)}:{done:!1}}));xf(String.prototype,e,c[0]),xf(Ff,n,c[1])}i&&Yf(Ff[n],"sham",!0)},_p=d,Sp=Mt,vp=H,yp=ri,Ip=ui,Tp=$c,Rp=V,Ep=function(e,t,r){return t+(r?Qf(e,t).length:1)},bp=ye,Cp=sp,Ap=function(e,t){var r=e.exec;if(up(r)){var i=ap(r,e,t);return null!==i&&cp(i),i}if("RegExp"===dp(e))return ap(lp,e,t);throw hp("RegExp#exec called on incompatible receiver")},wp=et("replace"),kp=Math.max,Op=Math.min,Pp=mp([].concat),Mp=mp([].push),Dp=mp("".indexOf),Np=mp("".slice),Up="$0"==="a".replace(/./,"$0"),xp=!!/./[wp]&&""===/./[wp]("a","$0"),Lp=!_p((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")}));gp("replace",(function(e,t,r){var i=xp?"$":"$0";return[function(e,r){var i=Rp(this),n=null==e?void 0:bp(e,wp);return n?pp(n,e,i,r):pp(t,Tp(i),e,r)},function(e,n){var o=Sp(this),s=Tp(e);if("string"==typeof n&&-1===Dp(n,i)&&-1===Dp(n,"$<")){var a=r(t,o,s,n);if(a.done)return a.value}var c=vp(n);c||(n=Tp(n));var u=o.global;if(u){var d=o.unicode;o.lastIndex=0}for(var l=[];;){var h=Ap(o,s);if(null===h)break;if(Mp(l,h),!u)break;""===Tp(h[0])&&(o.lastIndex=Ep(s,Ip(o.lastIndex),d))}for(var f,p="",m=0,g=0;g=m&&(p+=Np(s,m,S)+R,m=S+_.length)}return p+Np(s,m)}]}),!Lp||!Up||xp);var Bp=z,Vp=M,Yp=et("match"),jp=function(e){var t;return Bp(e)&&(void 0!==(t=e[Yp])?!!t:"RegExp"==Vp(e))},Fp=m,Hp=Be,Kp=q,zp=ef,Wp=RegExp.prototype,Gp=function(e){var t=e.flags;return void 0!==t||"flags"in Wp||Hp(e,"flags")||!Kp(Wp,e)?t:Fp(zp,e)},Jp=en,qp=m,Xp=w,Qp=V,$p=H,Zp=jp,em=$c,tm=ye,rm=Gp,im=sp,nm=et("replace"),om=TypeError,sm=Xp("".indexOf);Xp("".replace);var am=Xp("".slice),cm=Math.max,um=function(e,t,r){return r>e.length?-1:""===t?r:sm(e,t,r)};Jp({target:"String",proto:!0},{replaceAll:function(e,t){var r,i,n,o,s,a,c,u,d=Qp(this),l=0,h=0,f="";if(null!=e){if(Zp(e)&&(r=em(Qp(rm(e))),!~sm(r,"g")))throw om("`.replaceAll` does not allow non-global regexes");if(i=tm(e,nm))return qp(i,e,d,t)}for(n=em(d),o=em(e),(s=$p(t))||(t=em(t)),a=o.length,c=cm(1,a),l=um(n,o,0);-1!==l;)u=s?em(t(o,l,n)):im(o,n,l,[],void 0,t),f+=am(n,h,l)+u,h=l+a,l=um(n,o,l+c);return h@^][^\s!#%&*+<=>@^]*>/,zm=/a/g,Wm=/a/g,Gm=new xm(zm)!==zm,Jm=Cm.MISSED_STICKY,qm=Cm.UNSUPPORTED_Y,Xm=mm&&(!Gm||Jm||Dm||Nm||km((function(){return Wm[Um]=!1,xm(zm)!=zm||xm(Wm)==Wm||"/a/i"!=xm(zm,"i")})));if(Sm("RegExp",Xm)){for(var Qm=function(e,t){var r,i,n,o,s,a,c=Tm(Lm,this),u=Rm(e),d=void 0===t,l=[],h=e;if(!c&&u&&d&&e.constructor===Qm)return e;if((u||Tm(Lm,e))&&(e=e.source,d&&(t=bm(h))),e=void 0===e?"":Em(e),t=void 0===t?"":Em(t),h=e,Dm&&"dotAll"in zm&&(i=!!t&&Fm(t,"s")>-1)&&(t=jm(t,/s/g,"")),r=t,Jm&&"sticky"in zm&&(n=!!t&&Fm(t,"y")>-1)&&qm&&(t=jm(t,/y/g,"")),Nm&&(o=function(e){for(var t,r=e.length,i=0,n="",o=[],s={},a=!1,c=!1,u=0,d="";i<=r;i++){if("\\"===(t=Ym(e,i)))t+=Ym(e,++i);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:Vm(Km,Hm(e,i+1))&&(i+=2,c=!0),n+=t,u++;continue;case">"===t&&c:if(""===d||Om(s,d))throw new Bm("Invalid capture group name");s[d]=!0,o[o.length]=[d,u],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],l=o[1]),s=vm(xm(e,t),c?this:Lm,Qm),(i||n||l.length)&&(a=Pm(s),i&&(a.dotAll=!0,a.raw=Qm(function(e){for(var t,r=e.length,i=0,n="",o=!1;i<=r;i++)"\\"!==(t=Ym(e,i))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+Ym(e,++i);return n}(e),r)),n&&(a.sticky=!0),l.length&&(a.groups=l)),e!==h)try{ym(s,"source",""===h?"(?:)":h)}catch(jN){}return s},$m=Im(xm),Zm=0;$m.length>Zm;)Am(Qm,xm,$m[Zm++]);Lm.constructor=Qm,Qm.prototype=Lm,wm(gm,"RegExp",Qm,{constructor:!0})}Mm("RegExp");const eg=["none","error","warn","info","debug"];var tg="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},rg=[],ig=[],ng="undefined"!=typeof Uint8Array?Uint8Array:Array,og=!1;function sg(){og=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)rg[t]=e[t],ig[e.charCodeAt(t)]=t;ig["-".charCodeAt(0)]=62,ig["_".charCodeAt(0)]=63}function ag(e,t,r){for(var i,n,o=[],s=t;s>18&63]+rg[n>>12&63]+rg[n>>6&63]+rg[63&n]);return o.join("")}function cg(e){var t;og||sg();for(var r=e.length,i=r%3,n="",o=[],s=16383,a=0,c=r-i;ac?c:a+s));return 1===i?(t=e[r-1],n+=rg[t>>2],n+=rg[t<<4&63],n+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],n+=rg[t>>10],n+=rg[t>>4&63],n+=rg[t<<2&63],n+="="),o.push(n),o.join("")}function ug(e,t,r,i,n){var o,s,a=8*n-i-1,c=(1<>1,d=-7,l=r?n-1:0,h=r?-1:1,f=e[t+l];for(l+=h,o=f&(1<<-d)-1,f>>=-d,d+=a;d>0;o=256*o+e[t+l],l+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=i;d>0;s=256*s+e[t+l],l+=h,d-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,i),o-=u}return(f?-1:1)*s*Math.pow(2,o-i)}function dg(e,t,r,i,n,o){var s,a,c,u=8*o-n-1,d=(1<>1,h=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:o-1,p=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+l>=1?h/c:h*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=d?(a=0,s=d):s+l>=1?(a=(t*c-1)*Math.pow(2,n),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,n),s=0));n>=8;e[r+f]=255&a,f+=p,a/=256,n-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,u-=8);e[r+f-p]|=128*m}var lg={}.toString,hg=Array.isArray||function(e){return"[object Array]"==lg.call(e)};function fg(){return mg.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function pg(e,t){if(fg()=fg())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fg().toString(16)+" bytes");return 0|e}function Ig(e){return!(null==e||!e._isBuffer)}function Tg(e,t){if(Ig(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return qg(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Xg(e).length;default:if(i)return qg(e).length;t=(""+t).toLowerCase(),i=!0}}function Rg(e,t,r){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Bg(this,t,r);case"utf8":case"utf-8":return Ng(this,t,r);case"ascii":return xg(this,t,r);case"latin1":case"binary":return Lg(this,t,r);case"base64":return Dg(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Vg(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function Eg(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function bg(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=mg.from(t,i)),Ig(t))return 0===t.length?-1:Cg(e,t,r,i,n);if("number"==typeof t)return t&=255,mg.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Cg(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Cg(e,t,r,i,n){var o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){var d=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){for(var l=!0,h=0;hn&&(i=n):i=n;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var s=0;s>8,n=r%256,o.push(n),o.push(i);return o}(t,e.length-r),e,r,i)}function Dg(e,t,r){return 0===t&&r===e.length?cg(e):cg(e.slice(t,r))}function Ng(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n239?4:u>223?3:u>191?2:1;if(n+l<=r)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(o=e[n+1]))&&(c=(31&u)<<6|63&o)>127&&(d=c);break;case 3:o=e[n+1],s=e[n+2],128==(192&o)&&128==(192&s)&&(c=(15&u)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:o=e[n+1],s=e[n+2],a=e[n+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d),n+=l}return function(e){var t=e.length;if(t<=Ug)return String.fromCharCode.apply(String,e);var r="",i=0;for(;i0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},mg.prototype.compare=function(e,t,r,i,n){if(!Ig(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&t>=r)return 0;if(i>=n)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(i>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),c=this.slice(i,n),u=e.slice(t,r),d=0;dn)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Ag(this,e,t,r);case"utf8":case"utf-8":return wg(this,e,t,r);case"ascii":return kg(this,e,t,r);case"latin1":case"binary":return Og(this,e,t,r);case"base64":return Pg(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Mg(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},mg.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ug=4096;function xg(e,t,r){var i="";r=Math.min(e.length,r);for(var n=t;ni)&&(r=i);for(var n="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function jg(e,t,r,i,n,o){if(!Ig(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw new RangeError("Index out of range")}function Fg(e,t,r,i){t<0&&(t=65535+t+1);for(var n=0,o=Math.min(e.length-r,2);n>>8*(i?n:1-n)}function Hg(e,t,r,i){t<0&&(t=4294967295+t+1);for(var n=0,o=Math.min(e.length-r,4);n>>8*(i?n:3-n)&255}function Kg(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function zg(e,t,r,i,n){return n||Kg(e,0,r,4),dg(e,t,r,i,23,4),r+4}function Wg(e,t,r,i,n){return n||Kg(e,0,r,8),dg(e,t,r,i,52,8),r+8}mg.prototype.slice=function(e,t){var r,i=this.length;if((e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t0&&(n*=256);)i+=this[e+--t]*n;return i},mg.prototype.readUInt8=function(e,t){return t||Yg(e,1,this.length),this[e]},mg.prototype.readUInt16LE=function(e,t){return t||Yg(e,2,this.length),this[e]|this[e+1]<<8},mg.prototype.readUInt16BE=function(e,t){return t||Yg(e,2,this.length),this[e]<<8|this[e+1]},mg.prototype.readUInt32LE=function(e,t){return t||Yg(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},mg.prototype.readUInt32BE=function(e,t){return t||Yg(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},mg.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Yg(e,t,this.length);for(var i=this[e],n=1,o=0;++o=(n*=128)&&(i-=Math.pow(2,8*t)),i},mg.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Yg(e,t,this.length);for(var i=t,n=1,o=this[e+--i];i>0&&(n*=256);)o+=this[e+--i]*n;return o>=(n*=128)&&(o-=Math.pow(2,8*t)),o},mg.prototype.readInt8=function(e,t){return t||Yg(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},mg.prototype.readInt16LE=function(e,t){t||Yg(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},mg.prototype.readInt16BE=function(e,t){t||Yg(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},mg.prototype.readInt32LE=function(e,t){return t||Yg(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},mg.prototype.readInt32BE=function(e,t){return t||Yg(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},mg.prototype.readFloatLE=function(e,t){return t||Yg(e,4,this.length),ug(this,e,!0,23,4)},mg.prototype.readFloatBE=function(e,t){return t||Yg(e,4,this.length),ug(this,e,!1,23,4)},mg.prototype.readDoubleLE=function(e,t){return t||Yg(e,8,this.length),ug(this,e,!0,52,8)},mg.prototype.readDoubleBE=function(e,t){return t||Yg(e,8,this.length),ug(this,e,!1,52,8)},mg.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||jg(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+n]=e/o&255;return t+r},mg.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,1,255,0),mg.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},mg.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,65535,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Fg(this,e,t,!0),t+2},mg.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,65535,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Fg(this,e,t,!1),t+2},mg.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,4294967295,0),mg.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Hg(this,e,t,!0),t+4},mg.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,4294967295,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Hg(this,e,t,!1),t+4},mg.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);jg(this,e,t,r,n-1,-n)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+r},mg.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);jg(this,e,t,r,n-1,-n)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},mg.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,1,127,-128),mg.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},mg.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,32767,-32768),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Fg(this,e,t,!0),t+2},mg.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,32767,-32768),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Fg(this,e,t,!1),t+2},mg.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,2147483647,-2147483648),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Hg(this,e,t,!0),t+4},mg.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Hg(this,e,t,!1),t+4},mg.prototype.writeFloatLE=function(e,t,r){return zg(this,e,t,!0,r)},mg.prototype.writeFloatBE=function(e,t,r){return zg(this,e,t,!1,r)},mg.prototype.writeDoubleLE=function(e,t,r){return Wg(this,e,t,!0,r)},mg.prototype.writeDoubleBE=function(e,t,r){return Wg(this,e,t,!1,r)},mg.prototype.copy=function(e,t,r,i){if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--n)e[n+t]=this[n+r];else if(o<1e3||!mg.TYPED_ARRAY_SUPPORT)for(n=0;n>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Xg(e){return function(e){var t,r,i,n,o,s;og||sg();var a=e.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[a-2]?2:"="===e[a-1]?1:0,s=new ng(3*a/4-o),i=o>0?a-4:a;var c=0;for(t=0,r=0;t>16&255,s[c++]=n>>8&255,s[c++]=255&n;return 2===o?(n=ig[e.charCodeAt(t)]<<2|ig[e.charCodeAt(t+1)]>>4,s[c++]=255&n):1===o&&(n=ig[e.charCodeAt(t)]<<10|ig[e.charCodeAt(t+1)]<<4|ig[e.charCodeAt(t+2)]>>2,s[c++]=n>>8&255,s[c++]=255&n),s}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Gg,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Qg(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function $g(e){return null!=e&&(!!e._isBuffer||Zg(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Zg(e.slice(0,0))}(e))}function Zg(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function e_(){throw new Error("setTimeout has not been defined")}function t_(){throw new Error("clearTimeout has not been defined")}var r_=e_,i_=t_;function n_(e){if(r_===setTimeout)return setTimeout(e,0);if((r_===e_||!r_)&&setTimeout)return r_=setTimeout,setTimeout(e,0);try{return r_(e,0)}catch(Dw){try{return r_.call(null,e,0)}catch(Dw){return r_.call(this,e,0)}}}"function"==typeof tg.setTimeout&&(r_=setTimeout),"function"==typeof tg.clearTimeout&&(i_=clearTimeout);var o_,s_=[],a_=!1,c_=-1;function u_(){a_&&o_&&(a_=!1,o_.length?s_=o_.concat(s_):c_=-1,s_.length&&d_())}function d_(){if(!a_){var e=n_(u_);a_=!0;for(var t=s_.length;t;){for(o_=s_,s_=[];++c_>2,a=(3&t)<<4|r>>4,c=1>6:64,u=2>4,r=(15&s)<<4|(a=o.indexOf(e.charAt(u++)))>>2,i=(3&a)<<6|(c=o.indexOf(e.charAt(u++))),h[d++]=t,64!==a&&(h[d++]=r),64!==c&&(h[d++]=i);return h}},{"./support":30,"./utils":32}],2:[function(e,t,r){var i=e("./external"),n=e("./stream/DataWorker"),o=e("./stream/Crc32Probe"),s=e("./stream/DataLengthProbe");function a(e,t,r,i,n){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=i,this.compressedContent=n}a.prototype={getContentWorker:function(){var e=new n(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new s("data_length")),t=this;return e.on("end",(function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),e},getCompressedWorker:function(){return new n(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,r){return e.pipe(new o).pipe(new s("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new s("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){var i=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(e){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},r.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){var i=e("./utils"),n=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,r,i){var o=n,s=i+r;e^=-1;for(var a=i;a>>8^o[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,r,i){var o=n,s=i+r;e^=-1;for(var a=i;a>>8^o[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(e,t,r){var i=null;i="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:i}},{lie:37}],7:[function(e,t,r){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=e("pako"),o=e("./utils"),s=e("./stream/GenericWorker"),a=i?"uint8array":"array";function c(e,t){s.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}r.magic="\b\0",o.inherits(c,s),c.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(o.transformTo(a,e.data),!1)},c.prototype.flush=function(){s.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},r.compressWorker=function(e){return new c("Deflate",e)},r.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,r){function i(e,t){var r,i="";for(r=0;r>>=8;return i}function n(e,t,r,n,s,d){var l,h,f=e.file,p=e.compression,m=d!==a.utf8encode,g=o.transformTo("string",d(f.name)),_=o.transformTo("string",a.utf8encode(f.name)),S=f.comment,v=o.transformTo("string",d(S)),y=o.transformTo("string",a.utf8encode(S)),I=_.length!==f.name.length,T=y.length!==S.length,R="",E="",b="",C=f.dir,A=f.date,w={crc32:0,compressedSize:0,uncompressedSize:0};t&&!r||(w.crc32=e.crc32,w.compressedSize=e.compressedSize,w.uncompressedSize=e.uncompressedSize);var k=0;t&&(k|=8),m||!I&&!T||(k|=2048);var O=0,P=0;C&&(O|=16),"UNIX"===s?(P=798,O|=function(e,t){var r=e;return e||(r=t?16893:33204),(65535&r)<<16}(f.unixPermissions,C)):(P=20,O|=function(e){return 63&(e||0)}(f.dosPermissions)),l=A.getUTCHours(),l<<=6,l|=A.getUTCMinutes(),l<<=5,l|=A.getUTCSeconds()/2,h=A.getUTCFullYear()-1980,h<<=4,h|=A.getUTCMonth()+1,h<<=5,h|=A.getUTCDate(),I&&(E=i(1,1)+i(c(g),4)+_,R+="up"+i(E.length,2)+E),T&&(b=i(1,1)+i(c(v),4)+y,R+="uc"+i(b.length,2)+b);var M="";return M+="\n\0",M+=i(k,2),M+=p.magic,M+=i(l,2),M+=i(h,2),M+=i(w.crc32,4),M+=i(w.compressedSize,4),M+=i(w.uncompressedSize,4),M+=i(g.length,2),M+=i(R.length,2),{fileRecord:u.LOCAL_FILE_HEADER+M+g+R,dirRecord:u.CENTRAL_FILE_HEADER+i(P,2)+M+i(v.length,2)+"\0\0\0\0"+i(O,4)+i(n,4)+g+R+v}}var o=e("../utils"),s=e("../stream/GenericWorker"),a=e("../utf8"),c=e("../crc32"),u=e("../signature");function d(e,t,r,i){s.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=i,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(d,s),d.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,s.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-i-1))/r:100}}))},d.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,r=n(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:function(e){return u.DATA_DESCRIPTOR+i(e.crc32,4)+i(e.compressedSize,4)+i(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)r=(r<<8)+this.byteAt(t);return this.index+=e,r},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(e){},lastIndexOfSignature:function(e){},readAndCheckSignature:function(e){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=n},{"../utils":32}],19:[function(e,t,r){var i=e("./Uint8ArrayReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,r){var i=e("./DataReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},n.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},n.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./DataReader":18}],21:[function(e,t,r){var i=e("./ArrayReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,r){var i=e("../utils"),n=e("../support"),o=e("./ArrayReader"),s=e("./StringReader"),a=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");t.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||n.uint8array?"nodebuffer"===t?new a(e):n.uint8array?new c(i.transformTo("uint8array",e)):new o(i.transformTo("array",e)):new s(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,r){r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,r){var i=e("./GenericWorker"),n=e("../utils");function o(e){i.call(this,"ConvertWorker to "+e),this.destType=e}n.inherits(o,i),o.prototype.processChunk=function(e){this.push({data:n.transformTo(this.destType,e.data),meta:e.meta})},t.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,r){var i=e("./GenericWorker"),n=e("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(o,i),o.prototype.processChunk=function(e){this.streamInfo.crc32=n(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,r){var i=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(o,n),o.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}n.prototype.processChunk.call(this,e)},t.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,r){var i=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then((function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()}),(function(e){t.error(e)}))}i.inherits(o,n),o.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,r){function i(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var r=0;r "+e:e}},t.exports=i},{}],29:[function(e,t,r){var i=e("../utils"),n=e("./ConvertWorker"),o=e("./GenericWorker"),s=e("../base64"),a=e("../support"),c=e("../external"),u=null;if(a.nodestream)try{u=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function d(e,t){return new c.Promise((function(r,n){var o=[],a=e._internalType,c=e._outputType,u=e._mimeType;e.on("data",(function(e,r){o.push(e),t&&t(r)})).on("error",(function(e){o=[],n(e)})).on("end",(function(){try{var e=function(e,t,r){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),r);case"base64":return s.encode(t);default:return i.transformTo(e,t)}}(c,function(e,t){var r,i=0,n=null,o=0;for(r=0;r>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t}(e)},r.utf8decode=function(e){return n.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,r,n,o,s=e.length,c=new Array(2*s);for(t=r=0;t>10&1023,c[r++]=56320|1023&n)}return c.length!==r&&(c.subarray?c=c.subarray(0,r):c.length=r),i.applyFromCharCode(c)}(e=i.transformTo(n.uint8array?"uint8array":"array",e))},i.inherits(u,s),u.prototype.processChunk=function(e){var t=i.transformTo(n.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var o=t;(t=new Uint8Array(o.length+this.leftOver.length)).set(this.leftOver,0),t.set(o,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var s=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0||0===r?t:r+a[e[r]]>t?r:t}(t),c=t;s!==t.length&&(n.uint8array?(c=t.subarray(0,s),this.leftOver=t.subarray(s,t.length)):(c=t.slice(0,s),this.leftOver=t.slice(s,t.length))),this.push({data:r.utf8decode(c),meta:e.meta})},u.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:r.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},r.Utf8DecodeWorker=u,i.inherits(d,s),d.prototype.processChunk=function(e){this.push({data:r.utf8encode(e.data),meta:e.meta})},r.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,r){var i=e("./support"),n=e("./base64"),o=e("./nodejsUtils"),s=e("./external");function a(e){return e}function c(e,t){for(var r=0;r>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(e){if(this.extraFields[1]){var t=i(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(e){var t,r,i,n=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t},r.buf2binstring=function(e){return c(e,e.length)},r.binstring2buf=function(e){for(var t=new i.Buf8(e.length),r=0,n=t.length;r>10&1023,u[i++]=56320|1023&n)}return c(u,i)},r.utf8border=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0||0===r?t:r+s[e[r]]>t?r:t}},{"./common":41}],43:[function(e,t,r){t.exports=function(e,t,r,i){for(var n=65535&e|0,o=e>>>16&65535|0,s=0;0!==r;){for(r-=s=2e3>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t,r,n){var o=i,s=n+r;e^=-1;for(var a=n;a>>8^o[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,r){var i,n=e("../utils/common"),o=e("./trees"),s=e("./adler32"),a=e("./crc32"),c=e("./messages"),u=0,d=4,l=0,h=-2,f=-1,p=4,m=2,g=8,_=9,S=286,v=30,y=19,I=2*S+1,T=15,R=3,E=258,b=E+R+1,C=42,A=113,w=1,k=2,O=3,P=4;function M(e,t){return e.msg=c[t],t}function D(e){return(e<<1)-(4e.avail_out&&(r=e.avail_out),0!==r&&(n.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function x(e,t){o._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,U(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function B(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function V(e,t){var r,i,n=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-b?e.strstart-(e.w_size-b):0,u=e.window,d=e.w_mask,l=e.prev,h=e.strstart+E,f=u[o+s-1],p=u[o+s];e.prev_length>=e.good_match&&(n>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(r=t)+s]===p&&u[r+s-1]===f&&u[r]===u[o]&&u[++r]===u[o+1]){o+=2,r++;do{}while(u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&oc&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Y(e){var t,r,i,o,c,u,d,l,h,f,p=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=p+(p-b)){for(n.arraySet(e.window,e.window,p,p,0),e.match_start-=p,e.strstart-=p,e.block_start-=p,t=r=e.hash_size;i=e.head[--t],e.head[t]=p<=i?i-p:0,--r;);for(t=r=p;i=e.prev[--t],e.prev[t]=p<=i?i-p:0,--r;);o+=p}if(0===e.strm.avail_in)break;if(u=e.strm,d=e.window,l=e.strstart+e.lookahead,f=void 0,(h=o)<(f=u.avail_in)&&(f=h),r=0===f?0:(u.avail_in-=f,n.arraySet(d,u.input,u.next_in,f,l),1===u.state.wrap?u.adler=s(u.adler,d,f,l):2===u.state.wrap&&(u.adler=a(u.adler,d,f,l)),u.next_in+=f,u.total_in+=f,f),e.lookahead+=r,e.lookahead+e.insert>=R)for(c=e.strstart-e.insert,e.ins_h=e.window[c],e.ins_h=(e.ins_h<=R&&(e.ins_h=(e.ins_h<=R)if(i=o._tr_tally(e,e.strstart-e.match_start,e.match_length-R),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=R){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=R&&(e.ins_h=(e.ins_h<=R&&e.match_length<=e.prev_length){for(n=e.strstart+e.lookahead-R,i=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-R),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Y(e),0===e.lookahead&&t===u)return w;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,x(e,!1),0===e.strm.avail_out))return w;if(e.strstart-e.block_start>=e.w_size-b&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):(e.strstart>e.block_start&&(x(e,!1),e.strm.avail_out),w)})),new H(4,4,8,4,j),new H(4,5,16,8,j),new H(4,6,32,32,j),new H(4,4,16,16,F),new H(8,16,32,32,F),new H(8,16,128,128,F),new H(8,32,128,256,F),new H(32,128,258,1024,F),new H(32,258,258,4096,F)],r.deflateInit=function(e,t){return G(e,t,g,15,8,0)},r.deflateInit2=G,r.deflateReset=W,r.deflateResetKeep=z,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?h:(e.state.gzhead=t,l):h},r.deflate=function(e,t){var r,n,s,c;if(!e||!e.state||5>8&255),L(n,n.gzhead.time>>16&255),L(n,n.gzhead.time>>24&255),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(L(n,255&n.gzhead.extra.length),L(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=a(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(L(n,0),L(n,0),L(n,0),L(n,0),L(n,0),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,3),n.status=A);else{var f=g+(n.w_bits-8<<4)<<8;f|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(f|=32),f+=31-f%31,n.status=A,B(n,f),0!==n.strstart&&(B(n,e.adler>>>16),B(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(s=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending!==n.pending_buf_size));)L(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindexs&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindexs&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&U(e),n.pending+2<=n.pending_buf_size&&(L(n,255&e.adler),L(n,e.adler>>8&255),e.adler=0,n.status=A)):n.status=A),0!==n.pending){if(U(e),0===e.avail_out)return n.last_flush=-1,l}else if(0===e.avail_in&&D(t)<=D(r)&&t!==d)return M(e,-5);if(666===n.status&&0!==e.avail_in)return M(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==u&&666!==n.status){var p=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(Y(e),0===e.lookahead)){if(t===u)return w;break}if(e.match_length=0,r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):e.last_lit&&(x(e,!1),0===e.strm.avail_out)?w:k}(n,t):3===n.strategy?function(e,t){for(var r,i,n,s,a=e.window;;){if(e.lookahead<=E){if(Y(e),e.lookahead<=E&&t===u)return w;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=R&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=R?(r=o._tr_tally(e,1,e.match_length-R),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):e.last_lit&&(x(e,!1),0===e.strm.avail_out)?w:k}(n,t):i[n.level].func(n,t);if(p!==O&&p!==P||(n.status=666),p===w||p===O)return 0===e.avail_out&&(n.last_flush=-1),l;if(p===k&&(1===t?o._tr_align(n):5!==t&&(o._tr_stored_block(n,0,0,!1),3===t&&(N(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),U(e),0===e.avail_out))return n.last_flush=-1,l}return t!==d?l:n.wrap<=0?1:(2===n.wrap?(L(n,255&e.adler),L(n,e.adler>>8&255),L(n,e.adler>>16&255),L(n,e.adler>>24&255),L(n,255&e.total_in),L(n,e.total_in>>8&255),L(n,e.total_in>>16&255),L(n,e.total_in>>24&255)):(B(n,e.adler>>>16),B(n,65535&e.adler)),U(e),0=r.w_size&&(0===a&&(N(r.head),r.strstart=0,r.block_start=0,r.insert=0),f=new n.Buf8(r.w_size),n.arraySet(f,t,p-r.w_size,r.w_size,0),t=f,p=r.w_size),c=e.avail_in,u=e.next_in,d=e.input,e.avail_in=p,e.next_in=0,e.input=t,Y(r);r.lookahead>=R;){for(i=r.strstart,o=r.lookahead-(R-1);r.ins_h=(r.ins_h<>>=y=v>>>24,p-=y,0==(y=v>>>16&255))C[o++]=65535&v;else{if(!(16&y)){if(0==(64&y)){v=m[(65535&v)+(f&(1<>>=y,p-=y),p<15&&(f+=b[i++]<>>=y=v>>>24,p-=y,!(16&(y=v>>>16&255))){if(0==(64&y)){v=g[(65535&v)+(f&(1<>>=y,p-=y,(y=o-s)>3,f&=(1<<(p-=I<<3))-1,e.next_in=i,e.next_out=o,e.avail_in=i>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new i.Buf32(f),t.distcode=t.distdyn=new i.Buf32(p),t.sane=1,t.back=-1,d):l}function S(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):l}function v(e,t){var r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=s.wsize?(i.arraySet(s.window,t,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(o=s.wsize-s.wnext)&&(o=n),i.arraySet(s.window,t,r-n,o,s.wnext),(n-=o)?(i.arraySet(s.window,t,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=o(r.check,Y,2,0),I=y=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&y)<<8)+(y>>8))%31){e.msg="incorrect header check",r.mode=30;break}if(8!=(15&y)){e.msg="unknown compression method",r.mode=30;break}if(I-=4,U=8+(15&(y>>>=4)),0===r.wbits)r.wbits=U;else if(U>r.wbits){e.msg="invalid window size",r.mode=30;break}r.dmax=1<>8&1),512&r.flags&&(Y[0]=255&y,Y[1]=y>>>8&255,r.check=o(r.check,Y,2,0)),I=y=0,r.mode=3;case 3:for(;I<32;){if(0===S)break e;S--,y+=f[g++]<>>8&255,Y[2]=y>>>16&255,Y[3]=y>>>24&255,r.check=o(r.check,Y,4,0)),I=y=0,r.mode=4;case 4:for(;I<16;){if(0===S)break e;S--,y+=f[g++]<>8),512&r.flags&&(Y[0]=255&y,Y[1]=y>>>8&255,r.check=o(r.check,Y,2,0)),I=y=0,r.mode=5;case 5:if(1024&r.flags){for(;I<16;){if(0===S)break e;S--,y+=f[g++]<>>8&255,r.check=o(r.check,Y,2,0)),I=y=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(S<(C=r.length)&&(C=S),C&&(r.head&&(U=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),i.arraySet(r.head.extra,f,g,C,U)),512&r.flags&&(r.check=o(r.check,f,C,g)),S-=C,g+=C,r.length-=C),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===S)break e;for(C=0;U=f[g+C++],r.head&&U&&r.length<65536&&(r.head.name+=String.fromCharCode(U)),U&&C>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=12;break;case 10:for(;I<32;){if(0===S)break e;S--,y+=f[g++]<>>=7&I,I-=7&I,r.mode=27;break}for(;I<3;){if(0===S)break e;S--,y+=f[g++]<>>=1)){case 0:r.mode=14;break;case 1:if(E(r),r.mode=20,6!==t)break;y>>>=2,I-=2;break e;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=30}y>>>=2,I-=2;break;case 14:for(y>>>=7&I,I-=7&I;I<32;){if(0===S)break e;S--,y+=f[g++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&y,I=y=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(C=r.length){if(S>>=5,I-=5,r.ndist=1+(31&y),y>>>=5,I-=5,r.ncode=4+(15&y),y>>>=4,I-=4,286>>=3,I-=3}for(;r.have<19;)r.lens[j[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,L={bits:r.lenbits},x=a(0,r.lens,0,19,r.lencode,0,r.work,L),r.lenbits=L.bits,x){e.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=k,I-=k,r.lens[r.have++]=P;else{if(16===P){for(B=k+2;I>>=k,I-=k,0===r.have){e.msg="invalid bit length repeat",r.mode=30;break}U=r.lens[r.have-1],C=3+(3&y),y>>>=2,I-=2}else if(17===P){for(B=k+3;I>>=k)),y>>>=3,I-=3}else{for(B=k+7;I>>=k)),y>>>=7,I-=7}if(r.have+C>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=30;break}for(;C--;)r.lens[r.have++]=U}}if(30===r.mode)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,L={bits:r.lenbits},x=a(c,r.lens,0,r.nlen,r.lencode,0,r.work,L),r.lenbits=L.bits,x){e.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,L={bits:r.distbits},x=a(u,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,L),r.distbits=L.bits,x){e.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(6<=S&&258<=v){e.next_out=_,e.avail_out=v,e.next_in=g,e.avail_in=S,r.hold=y,r.bits=I,s(e,R),_=e.next_out,p=e.output,v=e.avail_out,g=e.next_in,f=e.input,S=e.avail_in,y=r.hold,I=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;O=(V=r.lencode[y&(1<>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>M)])>>>16&255,P=65535&V,!(M+(k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=M,I-=M,r.back+=M}if(y>>>=k,I-=k,r.back+=k,r.length=P,0===O){r.mode=26;break}if(32&O){r.back=-1,r.mode=12;break}if(64&O){e.msg="invalid literal/length code",r.mode=30;break}r.extra=15&O,r.mode=22;case 22:if(r.extra){for(B=r.extra;I>>=r.extra,I-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;O=(V=r.distcode[y&(1<>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>M)])>>>16&255,P=65535&V,!(M+(k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=M,I-=M,r.back+=M}if(y>>>=k,I-=k,r.back+=k,64&O){e.msg="invalid distance code",r.mode=30;break}r.offset=P,r.extra=15&O,r.mode=24;case 24:if(r.extra){for(B=r.extra;I>>=r.extra,I-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===v)break e;if(C=R-v,r.offset>C){if((C=r.offset-C)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=30;break}A=C>r.wnext?(C-=r.wnext,r.wsize-C):r.wnext-C,C>r.length&&(C=r.length),w=r.window}else w=p,A=_-r.offset,C=r.length;for(vS?(y=L[B+l[E]],D[N+l[E]]):(y=96,0),f=1<>k)+(p-=f)]=v<<24|y<<16|I|0,0!==p;);for(f=1<>=1;if(0!==f?(M&=f-1,M+=f):M=0,E++,0==--U[R]){if(R===C)break;R=t[r+l[E]]}if(A>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function B(e,t,r){e.bi_valid>m-r?(e.bi_buf|=t<>m-e.bi_valid,e.bi_valid+=r-m):(e.bi_buf|=t<>>=1,r<<=1,0<--t;);return r>>>1}function j(e,t,r){var i,n,o=new Array(p+1),s=0;for(i=1;i<=p;i++)o[i]=s=s+r[i-1]<<1;for(n=0;n<=t;n++){var a=e[2*n+1];0!==a&&(e[2*n]=Y(o[a]++,a))}}function F(e){var t;for(t=0;t>1;1<=r;r--)z(e,o,r);for(n=c;r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],z(e,o,1),i=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=i,o[2*n]=o[2*r]+o[2*i],e.depth[n]=(e.depth[r]>=e.depth[i]?e.depth[r]:e.depth[i])+1,o[2*r+1]=o[2*i+1]=n,e.heap[1]=n++,z(e,o,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,i,n,o,s,a,c=t.dyn_tree,u=t.max_code,d=t.stat_desc.static_tree,l=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,_=0;for(o=0;o<=p;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r>=7;i>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return n;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return o;for(t=32;t>>3,(a=e.static_len+3+7>>>3)<=s&&(s=a)):s=a=r+5,r+4<=s&&-1!==t?Q(e,t,r,i):4===e.strategy||a===s?(B(e,2+(i?1:0),3),W(e,b,C)):(B(e,4+(i?1:0),3),function(e,t,r,i){var n;for(B(e,t-257,5),B(e,r-1,5),B(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(w[r]+u+1)]++,e.dyn_dtree[2*x(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){B(e,2,3),V(e,_,b),function(e){16===e.bi_valid?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,r){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,r){(function(e){!function(e,t){if(!e.setImmediate){var r,i,n,o,s=1,a={},c=!1,u=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,r="[object process]"==={}.toString.call(e.process)?function(e){!function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r>1,d=23===t?E_(2,-24)-E_(2,-77):0,l=e<0||0===e&&1/e<0?1:0,h=0;for((e=R_(e))!=e||e===1/0?(n=e!=e?1:0,i=c):(i=b_(C_(e)/A_),e*(o=E_(2,-i))<1&&(i--,o*=2),(e+=i+u>=1?d/o:d*E_(2,1-u))*o>=2&&(i++,o/=2),i+u>=c?(n=0,i=c):i+u>=1?(n=(e*o-1)*E_(2,t),i+=u):(n=e*E_(2,u-1)*E_(2,t),i=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(i=i<0;)s[h++]=255&i,i/=256,a-=8;return s[--h]|=128*l,s},unpack:function(e,t){var r,i=e.length,n=8*i-t-1,o=(1<>1,a=n-7,c=i-1,u=e[c--],d=127&u;for(u>>=7;a>0;)d=256*d+e[c--],a-=8;for(r=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)r=256*r+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return r?NaN:u?-1/0:1/0;r+=E_(2,t),d-=s}return(u?-1:1)*r*E_(2,d-t)}},k_=Ue,O_=si,P_=li,M_=function(e){for(var t=k_(this),r=P_(t),i=arguments.length,n=O_(i>1?arguments[1]:void 0,r),o=i>2?arguments[2]:void 0,s=void 0===o?r:O_(o,r);s>n;)t[n++]=e;return t},D_=lt,N_=At,U_=T,x_=si,L_=li,B_=function(e,t,r){var i=D_(t);i in e?N_.f(e,i,U_(0,r)):e[i]=r},V_=Array,Y_=Math.max,j_=function(e,t,r){for(var i=L_(e),n=x_(t,i),o=x_(void 0===r?i:r,i),s=V_(Y_(o-n,0)),a=0;n>8&255]},OS=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},PS=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},MS=function(e){return CS(e,23,4)},DS=function(e){return CS(e,52,8)},NS=function(e,t){nS(e[pS],t,{get:function(){return dS(this)[t]}})},US=function(e,t,r,i){var n=Z_(r),o=dS(e);if(n+t>o.byteLength)throw RS(mS);var s=dS(o.buffer).bytes,a=n+o.byteOffset,c=sS(s,a,a+t);return i?c:bS(c)},xS=function(e,t,r,i,n,o){var s=Z_(r),a=dS(e);if(s+t>a.byteLength)throw RS(mS);for(var c=dS(a.buffer).bytes,u=s+a.byteOffset,d=i(+n),l=0;lYS;)(BS=VS[YS++])in _S||G_(_S,BS,gS[BS]);SS.constructor=_S}rS&&tS(yS)!==IS&&rS(yS,IS);var jS=new vS(new _S(2)),FS=H_(yS.setInt8);jS.setInt8(0,2147483648),jS.setInt8(1,2147483649),!jS.getInt8(0)&&jS.getInt8(1)||J_(yS,{setInt8:function(e,t){FS(this,e,t<<24>>24)},setUint8:function(e,t){FS(this,e,t<<24>>24)}},{unsafe:!0})}else _S=function(e){X_(this,SS);var t=Z_(e);lS(this,{bytes:ES(TS(t),0),byteLength:t}),K_||(this.byteLength=t)},SS=_S[pS],vS=function(e,t,r){X_(this,yS),X_(e,SS);var i=dS(e).byteLength,n=Q_(t);if(n<0||n>i)throw RS("Wrong offset");if(n+(r=void 0===r?i-n:$_(r))>i)throw RS("Wrong length");lS(this,{buffer:e,byteLength:r,byteOffset:n}),K_||(this.buffer=e,this.byteLength=r,this.byteOffset=n)},yS=vS[pS],K_&&(NS(_S,"byteLength"),NS(vS,"buffer"),NS(vS,"byteLength"),NS(vS,"byteOffset")),J_(yS,{getInt8:function(e){return US(this,1,e)[0]<<24>>24},getUint8:function(e){return US(this,1,e)[0]},getInt16:function(e){var t=US(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=US(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return PS(US(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return PS(US(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return AS(US(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return AS(US(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){xS(this,1,e,wS,t)},setUint8:function(e,t){xS(this,1,e,wS,t)},setInt16:function(e,t){xS(this,2,e,kS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){xS(this,2,e,kS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){xS(this,4,e,OS,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){xS(this,4,e,OS,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){xS(this,4,e,MS,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){xS(this,8,e,DS,t,arguments.length>2?arguments[2]:void 0)}});aS(_S,hS),aS(vS,fS);var HS={ArrayBuffer:_S,DataView:vS},KS=en,zS=w,WS=d,GS=Mt,JS=si,qS=ui,XS=to,QS=HS.ArrayBuffer,$S=HS.DataView,ZS=$S.prototype,ev=zS(QS.prototype.slice),tv=zS(ZS.getUint8),rv=zS(ZS.setUint8);KS({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:WS((function(){return!new QS(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(ev&&void 0===t)return ev(GS(this),e);for(var r=GS(this).byteLength,i=JS(e,r),n=JS(void 0===t?r:t,r),o=new(XS(this,QS))(qS(n-i)),s=new $S(this),a=new $S(o),c=0;i1?arguments[1]:void 0,l=void 0!==d,h=dy(c);if(h&&!ly(h))for(s=(o=uy(c,h)).next,c=[];!(n=oy(s,o)).done;)c.push(n.value);for(l&&u>2&&(d=ny(d,arguments[2])),r=cy(c),i=new(hy(a))(r),t=0;r>t;t++)i[t]=l?d(c[t],t):c[t];return i},Ly=Vh.forEach,By=Sn,Vy=At,Yy=u,jy=fm,Fy=Dr.get,Hy=Dr.set,Ky=Dr.enforce,zy=Vy.f,Wy=Yy.f,Gy=Math.round,Jy=py.RangeError,qy=vy.ArrayBuffer,Xy=qy.prototype,Qy=vy.DataView,$y=Sy.NATIVE_ARRAY_BUFFER_VIEWS,Zy=Sy.TYPED_ARRAY_TAG,eI=Sy.TypedArray,tI=Sy.TypedArrayPrototype,rI=Sy.aTypedArrayConstructor,iI=Sy.isTypedArray,nI="BYTES_PER_ELEMENT",oI="Wrong length",sI=function(e,t){rI(e);for(var r=0,i=t.length,n=new e(i);i>r;)n[r]=t[r++];return n},aI=function(e,t){zy(e,t,{get:function(){return Fy(this)[t]}})},cI=function(e){var t;return Dy(Xy,e)||"ArrayBuffer"==(t=ky(e))||"SharedArrayBuffer"==t},uI=function(e,t){return iI(e)&&!Py(t)&&t in e&&Ry(+t)&&t>=0},dI=function(e,t){return t=Ay(t),uI(e,t)?Iy(2,e[t]):Wy(e,t)},lI=function(e,t,r){return t=Ay(t),!(uI(e,t)&&Oy(r)&&wy(r,"value"))||wy(r,"get")||wy(r,"set")||r.configurable||wy(r,"writable")&&!r.writable||wy(r,"enumerable")&&!r.enumerable?zy(e,t,r):(e[t]=r.value,e)};gy?($y||(Yy.f=dI,Vy.f=lI,aI(tI,"buffer"),aI(tI,"byteOffset"),aI(tI,"byteLength"),aI(tI,"length")),fy({target:"Object",stat:!0,forced:!$y},{getOwnPropertyDescriptor:dI,defineProperty:lI}),sv.exports=function(e,t,r){var i=e.match(/\d+$/)[0]/8,n=e+(r?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=py[n],c=a,u=c&&c.prototype,d={},l=function(e,t){zy(e,t,{get:function(){return function(e,t){var r=Fy(e);return r.view[o](t*i+r.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=Fy(e);r&&(n=(n=Gy(n))<0?0:n>255?255:255&n),o.view[s](t*i+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};$y?_y&&(c=t((function(e,t,r,n){return yy(e,u),jy(Oy(t)?cI(t)?void 0!==n?new a(t,Cy(r,i),n):void 0!==r?new a(t,Cy(r,i)):new a(t):iI(t)?sI(c,t):my(xy,c,t):new a(by(t)),e,c)})),Ny&&Ny(c,eI),Ly(Uy(a),(function(e){e in c||Ty(c,e,a[e])})),c.prototype=u):(c=t((function(e,t,r,n){yy(e,u);var o,s,a,d=0,h=0;if(Oy(t)){if(!cI(t))return iI(t)?sI(c,t):my(xy,c,t);o=t,h=Cy(r,i);var f=t.byteLength;if(void 0===n){if(f%i)throw Jy(oI);if((s=f-h)<0)throw Jy(oI)}else if((s=Ey(n)*i)+h>f)throw Jy(oI);a=s/i}else a=by(t),o=new qy(s=a*i);for(Hy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Qy(o)});d1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),SI((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var TI=c,RI=m,EI=Fv,bI=li,CI=iy,AI=Ue,wI=d,kI=TI.RangeError,OI=TI.Int8Array,PI=OI&&OI.prototype,MI=PI&&PI.set,DI=EI.aTypedArray,NI=EI.exportTypedArrayMethod,UI=!wI((function(){var e=new Uint8ClampedArray(2);return RI(MI,e,{length:1,0:3},1),3!==e[1]})),xI=UI&&EI.NATIVE_ARRAY_BUFFER_VIEWS&&wI((function(){var e=new OI(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));NI("set",(function(e){DI(this);var t=CI(arguments.length>1?arguments[1]:void 0,1),r=AI(e);if(UI)return RI(MI,this,r,t);var i=this.length,n=bI(r),o=0;if(n+t>i)throw kI("Wrong length");for(;o0;)e[i]=e[--i];i!==o++&&(e[i]=r)}return e},jI=function(e,t,r,i){for(var n=t.length,o=r.length,s=0,a=0;s0&&1/r<0?1:-1:t>r}}(e))}),!aT||sT);var cT,uT={exports:{}},dT={exports:{}},lT=s(Object.freeze({__proto__:null,default:{}}));function hT(){return cT||(cT=1,function(e,t){var r;e.exports=(r=r||function(e,t){var r;if("undefined"!=typeof window&&window.crypto&&(r=window.crypto),"undefined"!=typeof self&&self.crypto&&(r=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(r=globalThis.crypto),!r&&"undefined"!=typeof window&&window.msCrypto&&(r=window.msCrypto),!r&&void 0!==o&&o.crypto&&(r=o.crypto),!r)try{r=lT}catch(g){}var i=function(){if(r){if("function"==typeof r.getRandomValues)try{return r.getRandomValues(new Uint32Array(1))[0]}catch(g){}if("function"==typeof r.randomBytes)try{return r.randomBytes(4).readInt32LE()}catch(g){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),s={},a=s.lib={},c=a.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},u=a.WordArray=c.extend({init:function(e,r){e=this.words=e||[],this.sigBytes=r!=t?r:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[i+o>>>2]|=s<<24-(i+o)%4*8}else for(var a=0;a>>2]=r[a>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r>>2]>>>24-n%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new u.init(r,t/2)}},h=d.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new u.init(r,t)}},f=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(Dw){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,i=this._data,n=i.words,o=i.sigBytes,s=this.blockSize,a=o/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,d=e.min(4*c,o);if(c){for(var l=0;l>>2]|=e[n]<<24-n%4*8;t.call(this,i,r)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray)}(_T)),_T.exports}var vT,yT={exports:{}};function IT(){return vT||(vT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib.WordArray,i=e.enc;function n(e){return e<<8&4278255360|e>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>16-n%4*8&65535;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var r=e.length,i=[],n=0;n>>1]|=e.charCodeAt(n)<<16-n%2*16;return t.create(i,2*r)}},i.Utf16LE={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],o=0;o>>2]>>>16-o%4*8&65535);i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var r=e.length,i=[],o=0;o>>1]|=n(e.charCodeAt(o)<<16-o%2*16);return t.create(i,2*r)}}}(),r.enc.Utf16)}(yT)),yT.exports}var TT,RT={exports:{}};function ET(){return TT||(TT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib.WordArray;function i(e,r,i){for(var n=[],o=0,s=0;s>>6-s%4*2;n[o>>>2]|=a<<24-o%4*8,o++}return t.create(n,o)}e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,i=this._map;e.clamp();for(var n=[],o=0;o>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;n.length%4;)n.push(c);return n.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var o=0;o>>6-s%4*2;n[o>>>2]|=a<<24-o%4*8,o++}return t.create(n,o)}e.enc.Base64url={stringify:function(e,t=!0){var r=e.words,i=e.sigBytes,n=t?this._safe_map:this._map;e.clamp();for(var o=[],s=0;s>>2]>>>24-s%4*8&255)<<16|(r[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|r[s+2>>>2]>>>24-(s+2)%4*8&255,c=0;c<4&&s+.75*c>>6*(3-c)&63));var u=n.charAt(64);if(u)for(;o.length%4;)o.push(u);return o.join("")},parse:function(e,t=!0){var r=e.length,n=t?this._safe_map:this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var s=0;s>>24)|4278255360&(n<<24|n>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],f=e[t+2],p=e[t+3],m=e[t+4],g=e[t+5],_=e[t+6],S=e[t+7],v=e[t+8],y=e[t+9],I=e[t+10],T=e[t+11],R=e[t+12],E=e[t+13],b=e[t+14],C=e[t+15],A=o[0],w=o[1],k=o[2],O=o[3];A=u(A,w,k,O,s,7,a[0]),O=u(O,A,w,k,c,12,a[1]),k=u(k,O,A,w,f,17,a[2]),w=u(w,k,O,A,p,22,a[3]),A=u(A,w,k,O,m,7,a[4]),O=u(O,A,w,k,g,12,a[5]),k=u(k,O,A,w,_,17,a[6]),w=u(w,k,O,A,S,22,a[7]),A=u(A,w,k,O,v,7,a[8]),O=u(O,A,w,k,y,12,a[9]),k=u(k,O,A,w,I,17,a[10]),w=u(w,k,O,A,T,22,a[11]),A=u(A,w,k,O,R,7,a[12]),O=u(O,A,w,k,E,12,a[13]),k=u(k,O,A,w,b,17,a[14]),A=d(A,w=u(w,k,O,A,C,22,a[15]),k,O,c,5,a[16]),O=d(O,A,w,k,_,9,a[17]),k=d(k,O,A,w,T,14,a[18]),w=d(w,k,O,A,s,20,a[19]),A=d(A,w,k,O,g,5,a[20]),O=d(O,A,w,k,I,9,a[21]),k=d(k,O,A,w,C,14,a[22]),w=d(w,k,O,A,m,20,a[23]),A=d(A,w,k,O,y,5,a[24]),O=d(O,A,w,k,b,9,a[25]),k=d(k,O,A,w,p,14,a[26]),w=d(w,k,O,A,v,20,a[27]),A=d(A,w,k,O,E,5,a[28]),O=d(O,A,w,k,f,9,a[29]),k=d(k,O,A,w,S,14,a[30]),A=l(A,w=d(w,k,O,A,R,20,a[31]),k,O,g,4,a[32]),O=l(O,A,w,k,v,11,a[33]),k=l(k,O,A,w,T,16,a[34]),w=l(w,k,O,A,b,23,a[35]),A=l(A,w,k,O,c,4,a[36]),O=l(O,A,w,k,m,11,a[37]),k=l(k,O,A,w,S,16,a[38]),w=l(w,k,O,A,I,23,a[39]),A=l(A,w,k,O,E,4,a[40]),O=l(O,A,w,k,s,11,a[41]),k=l(k,O,A,w,p,16,a[42]),w=l(w,k,O,A,_,23,a[43]),A=l(A,w,k,O,y,4,a[44]),O=l(O,A,w,k,R,11,a[45]),k=l(k,O,A,w,C,16,a[46]),A=h(A,w=l(w,k,O,A,f,23,a[47]),k,O,s,6,a[48]),O=h(O,A,w,k,S,10,a[49]),k=h(k,O,A,w,b,15,a[50]),w=h(w,k,O,A,g,21,a[51]),A=h(A,w,k,O,R,6,a[52]),O=h(O,A,w,k,p,10,a[53]),k=h(k,O,A,w,I,15,a[54]),w=h(w,k,O,A,c,21,a[55]),A=h(A,w,k,O,v,6,a[56]),O=h(O,A,w,k,C,10,a[57]),k=h(k,O,A,w,_,15,a[58]),w=h(w,k,O,A,E,21,a[59]),A=h(A,w,k,O,m,6,a[60]),O=h(O,A,w,k,T,10,a[61]),k=h(k,O,A,w,f,15,a[62]),w=h(w,k,O,A,y,21,a[63]),o[0]=o[0]+A|0,o[1]=o[1]+w|0,o[2]=o[2]+k|0,o[3]=o[3]+O|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;r[n>>>5]|=128<<24-n%32;var o=e.floor(i/4294967296),s=i;r[15+(n+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(n+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,i,n,o,s){var a=e+(t&r|~t&i)+n+s;return(a<>>32-o)+t}function d(e,t,r,i,n,o,s){var a=e+(t&i|r&~i)+n+s;return(a<>>32-o)+t}function l(e,t,r,i,n,o,s){var a=e+(t^r^i)+n+s;return(a<>>32-o)+t}function h(e,t,r,i,n,o,s){var a=e+(r^(t|~i))+n+s;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),r.MD5)}(kT)),kT.exports}var PT,MT={exports:{}};function DT(){return PT||(PT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib,i=t.WordArray,n=t.Hasher,o=e.algo,s=[],a=o.SHA1=n.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],a=r[3],c=r[4],u=0;u<80;u++){if(u<16)s[u]=0|e[t+u];else{var d=s[u-3]^s[u-8]^s[u-14]^s[u-16];s[u]=d<<1|d>>>31}var l=(i<<5|i>>>27)+c+s[u];l+=u<20?1518500249+(n&o|~n&a):u<40?1859775393+(n^o^a):u<60?(n&o|n&a|o&a)-1894007588:(n^o^a)-899497514,c=a,a=o,o=n<<30|n>>>2,n=i,i=l}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(i+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=n._createHelper(a),e.HmacSHA1=n._createHmacHelper(a)}(),r.SHA1)}(MT)),MT.exports}var NT,UT={exports:{}};function xT(){return NT||(NT=1,function(e,t){var r;e.exports=(r=hT(),function(e){var t=r,i=t.lib,n=i.WordArray,o=i.Hasher,s=t.algo,a=[],c=[];!function(){function t(t){for(var r=e.sqrt(t),i=2;i<=r;i++)if(!(t%i))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var i=2,n=0;n<64;)t(i)&&(n<8&&(a[n]=r(e.pow(i,.5))),c[n]=r(e.pow(i,1/3)),n++),i++}();var u=[],d=s.SHA256=o.extend({_doReset:function(){this._hash=new n.init(a.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],s=r[3],a=r[4],d=r[5],l=r[6],h=r[7],f=0;f<64;f++){if(f<16)u[f]=0|e[t+f];else{var p=u[f-15],m=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,g=u[f-2],_=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;u[f]=m+u[f-7]+_+u[f-16]}var S=i&n^i&o^n&o,v=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),y=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&l)+c[f]+u[f];h=l,l=d,d=a,a=s+y|0,s=o,o=n,n=i,i=y+(v+S)|0}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0,r[5]=r[5]+d|0,r[6]=r[6]+l|0,r[7]=r[7]+h|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;return r[n>>>5]|=128<<24-n%32,r[14+(n+64>>>9<<4)]=e.floor(i/4294967296),r[15+(n+64>>>9<<4)]=i,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(d),t.HmacSHA256=o._createHmacHelper(d)}(Math),r.SHA256)}(UT)),UT.exports}var LT,BT={exports:{}};var VT,YT={exports:{}};function jT(){return VT||(VT=1,function(e,t){var r;e.exports=(r=hT(),mT(),function(){var e=r,t=e.lib.Hasher,i=e.x64,n=i.Word,o=i.WordArray,s=e.algo;function a(){return n.create.apply(n,arguments)}var c=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],u=[];!function(){for(var e=0;e<80;e++)u[e]=a()}();var d=s.SHA512=t.extend({_doReset:function(){this._hash=new o.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],s=r[3],a=r[4],d=r[5],l=r[6],h=r[7],f=i.high,p=i.low,m=n.high,g=n.low,_=o.high,S=o.low,v=s.high,y=s.low,I=a.high,T=a.low,R=d.high,E=d.low,b=l.high,C=l.low,A=h.high,w=h.low,k=f,O=p,P=m,M=g,D=_,N=S,U=v,x=y,L=I,B=T,V=R,Y=E,j=b,F=C,H=A,K=w,z=0;z<80;z++){var W,G,J=u[z];if(z<16)G=J.high=0|e[t+2*z],W=J.low=0|e[t+2*z+1];else{var q=u[z-15],X=q.high,Q=q.low,$=(X>>>1|Q<<31)^(X>>>8|Q<<24)^X>>>7,Z=(Q>>>1|X<<31)^(Q>>>8|X<<24)^(Q>>>7|X<<25),ee=u[z-2],te=ee.high,re=ee.low,ie=(te>>>19|re<<13)^(te<<3|re>>>29)^te>>>6,ne=(re>>>19|te<<13)^(re<<3|te>>>29)^(re>>>6|te<<26),oe=u[z-7],se=oe.high,ae=oe.low,ce=u[z-16],ue=ce.high,de=ce.low;G=(G=(G=$+se+((W=Z+ae)>>>0>>0?1:0))+ie+((W+=ne)>>>0>>0?1:0))+ue+((W+=de)>>>0>>0?1:0),J.high=G,J.low=W}var le,he=L&V^~L&j,fe=B&Y^~B&F,pe=k&P^k&D^P&D,me=O&M^O&N^M&N,ge=(k>>>28|O<<4)^(k<<30|O>>>2)^(k<<25|O>>>7),_e=(O>>>28|k<<4)^(O<<30|k>>>2)^(O<<25|k>>>7),Se=(L>>>14|B<<18)^(L>>>18|B<<14)^(L<<23|B>>>9),ve=(B>>>14|L<<18)^(B>>>18|L<<14)^(B<<23|L>>>9),ye=c[z],Ie=ye.high,Te=ye.low,Re=H+Se+((le=K+ve)>>>0>>0?1:0),Ee=_e+me;H=j,K=F,j=V,F=Y,V=L,Y=B,L=U+(Re=(Re=(Re=Re+he+((le+=fe)>>>0>>0?1:0))+Ie+((le+=Te)>>>0>>0?1:0))+G+((le+=W)>>>0>>0?1:0))+((B=x+le|0)>>>0>>0?1:0)|0,U=D,x=N,D=P,N=M,P=k,M=O,k=Re+(ge+pe+(Ee>>>0<_e>>>0?1:0))+((O=le+Ee|0)>>>0>>0?1:0)|0}p=i.low=p+O,i.high=f+k+(p>>>0>>0?1:0),g=n.low=g+M,n.high=m+P+(g>>>0>>0?1:0),S=o.low=S+N,o.high=_+D+(S>>>0>>0?1:0),y=s.low=y+x,s.high=v+U+(y>>>0>>0?1:0),T=a.low=T+B,a.high=I+L+(T>>>0>>0?1:0),E=d.low=E+Y,d.high=R+V+(E>>>0>>0?1:0),C=l.low=C+F,l.high=b+j+(C>>>0>>0?1:0),w=h.low=w+K,h.high=A+H+(w>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[30+(i+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(i+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=t.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32});e.SHA512=t._createHelper(d),e.HmacSHA512=t._createHmacHelper(d)}(),r.SHA512)}(YT)),YT.exports}var FT,HT={exports:{}};var KT,zT={exports:{}};function WT(){return KT||(KT=1,function(e,t){var r;e.exports=(r=hT(),mT(),function(e){var t=r,i=t.lib,n=i.WordArray,o=i.Hasher,s=t.x64.Word,a=t.algo,c=[],u=[],d=[];!function(){for(var e=1,t=0,r=0;r<24;r++){c[e+5*t]=(r+1)*(r+2)/2%64;var i=(2*e+3*t)%5;e=t%5,t=i}for(e=0;e<5;e++)for(t=0;t<5;t++)u[e+5*t]=t+(2*e+3*t)%5*5;for(var n=1,o=0;o<24;o++){for(var a=0,l=0,h=0;h<7;h++){if(1&n){var f=(1<>>24)|4278255360&(o<<24|o>>>8),s=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),(w=r[n]).high^=s,w.low^=o}for(var a=0;a<24;a++){for(var h=0;h<5;h++){for(var f=0,p=0,m=0;m<5;m++)f^=(w=r[h+5*m]).high,p^=w.low;var g=l[h];g.high=f,g.low=p}for(h=0;h<5;h++){var _=l[(h+4)%5],S=l[(h+1)%5],v=S.high,y=S.low;for(f=_.high^(v<<1|y>>>31),p=_.low^(y<<1|v>>>31),m=0;m<5;m++)(w=r[h+5*m]).high^=f,w.low^=p}for(var I=1;I<25;I++){var T=(w=r[I]).high,R=w.low,E=c[I];E<32?(f=T<>>32-E,p=R<>>32-E):(f=R<>>64-E,p=T<>>64-E);var b=l[u[I]];b.high=f,b.low=p}var C=l[0],A=r[0];for(C.high=A.high,C.low=A.low,h=0;h<5;h++)for(m=0;m<5;m++){var w=r[I=h+5*m],k=l[I],O=l[(h+1)%5+5*m],P=l[(h+2)%5+5*m];w.high=k.high^~O.high&P.high,w.low=k.low^~O.low&P.low}w=r[0];var M=d[a];w.high^=M.high,w.low^=M.low}},_doFinalize:function(){var t=this._data,r=t.words;this._nDataBytes;var i=8*t.sigBytes,o=32*this.blockSize;r[i>>>5]|=1<<24-i%32,r[(e.ceil((i+1)/o)*o>>>5)-1]|=128,t.sigBytes=4*r.length,this._process();for(var s=this._state,a=this.cfg.outputLength/8,c=a/8,u=[],d=0;d>>24)|4278255360&(h<<24|h>>>8),f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),u.push(f),u.push(h)}return new n.init(u,a)},clone:function(){for(var e=o.clone.call(this),t=e._state=this._state.slice(0),r=0;r<25;r++)t[r]=t[r].clone();return e}});t.SHA3=o._createHelper(h),t.HmacSHA3=o._createHmacHelper(h)}(Math),r.SHA3)}(zT)),zT.exports}var GT,JT={exports:{}};var qT,XT={exports:{}};function QT(){return qT||(qT=1,function(e,t){var r;e.exports=(r=hT(),void function(){var e=r,t=e.lib.Base,i=e.enc.Utf8;e.algo.HMAC=t.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=i.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var o=this._oKey=t.clone(),s=this._iKey=t.clone(),a=o.words,c=s.words,u=0;u>>2];e.sigBytes-=t}};i.BlockCipher=d.extend({cfg:d.cfg.extend({mode:f,padding:p}),reset:function(){var e;d.reset.call(this);var t=this.cfg,r=t.iv,i=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=i.createEncryptor:(e=i.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,r&&r.words):(this._mode=e.call(i,this,r&&r.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var m=i.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),g=(t.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;return(r?o.create([1398893684,1701076831]).concat(r).concat(t):t).toString(c)},parse:function(e){var t,r=c.parse(e),i=r.words;return 1398893684==i[0]&&1701076831==i[1]&&(t=o.create(i.slice(2,4)),i.splice(0,4),r.sigBytes-=16),m.create({ciphertext:r,salt:t})}},_=i.SerializableCipher=n.extend({cfg:n.extend({format:g}),encrypt:function(e,t,r,i){i=this.cfg.extend(i);var n=e.createEncryptor(r,i),o=n.finalize(t),s=n.cfg;return m.create({ciphertext:o,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:i.format})},decrypt:function(e,t,r,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),e.createDecryptor(r,i).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),S=(t.kdf={}).OpenSSL={execute:function(e,t,r,i){i||(i=o.random(8));var n=u.create({keySize:t+r}).compute(e,i),s=o.create(n.words.slice(t),4*r);return n.sigBytes=4*t,m.create({key:n,iv:s,salt:i})}},v=i.PasswordBasedCipher=_.extend({cfg:_.cfg.extend({kdf:S}),encrypt:function(e,t,r,i){var n=(i=this.cfg.extend(i)).kdf.execute(r,e.keySize,e.ivSize);i.iv=n.iv;var o=_.encrypt.call(this,e,t,n.key,i);return o.mixIn(n),o},decrypt:function(e,t,r,i){i=this.cfg.extend(i),t=this._parse(t,i.format);var n=i.kdf.execute(r,e.keySize,e.ivSize,t.salt);return i.iv=n.iv,_.decrypt.call(this,e,t,n.key,i)}})}()))}(nR)),nR.exports}var sR,aR={exports:{}};function cR(){return sR||(sR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(e,t,r,i){var n,o=this._iv;o?(n=o.slice(0),this._iv=void 0):n=this._prevBlock,i.encryptBlock(n,0);for(var s=0;s0&&y[0]<4?1:+(y[0]+y[1])),!I&&$&&(!(y=$.match(/Edge\/(\d+)/))||y[1]>=74)&&(y=$.match(/Chrome\/(\d+)/))&&(I=+y[1]);var ie=I,ne=ie,oe=d,se=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ae=se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ce=J,ue=H,de=q,le=Object,he=ae?function(e){return"symbol"==typeof e}:function(e){var t=ce("Symbol");return ue(t)&&de(t.prototype,le(e))},fe=String,pe=function(e){try{return fe(e)}catch(t){return"Object"}},me=H,ge=pe,_e=TypeError,Se=function(e){if(me(e))return e;throw _e(ge(e)+" is not a function")},ve=Se,ye=function(e,t){var r=e[t];return null==r?void 0:ve(r)},Ie=m,Te=H,Re=z,Ee=TypeError,be={exports:{}},Ce=c,Ae=Object.defineProperty,we=function(e,t){try{Ae(Ce,e,{value:t,configurable:!0,writable:!0})}catch(r){Ce[e]=t}return t},ke=we,Oe="__core-js_shared__",Pe=c[Oe]||ke(Oe,{}),Me=Pe;(be.exports=function(e,t){return Me[e]||(Me[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.23.3",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.23.3/LICENSE",source:"https://github.com/zloirock/core-js"});var De=V,Ne=Object,Ue=function(e){return Ne(De(e))},xe=Ue,Le=w({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return Le(xe(e),t)},Ve=w,Ye=0,je=Math.random(),Fe=Ve(1..toString),He=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Fe(++Ye+je,36)},Ke=c,ze=be.exports,We=Be,Ge=He,Je=se,qe=ae,Xe=ze("wks"),Qe=Ke.Symbol,$e=Qe&&Qe.for,Ze=qe?Qe:Qe&&Qe.withoutSetter||Ge,et=function(e){if(!We(Xe,e)||!Je&&"string"!=typeof Xe[e]){var t="Symbol."+e;Je&&We(Qe,e)?Xe[e]=Qe[e]:Xe[e]=qe&&$e?$e(t):Ze(t)}return Xe[e]},tt=m,rt=z,it=he,nt=ye,ot=function(e,t){var r,i;if("string"===t&&Te(r=e.toString)&&!Re(i=Ie(r,e)))return i;if(Te(r=e.valueOf)&&!Re(i=Ie(r,e)))return i;if("string"!==t&&Te(r=e.toString)&&!Re(i=Ie(r,e)))return i;throw Ee("Can't convert object to primitive value")},st=TypeError,at=et("toPrimitive"),ct=function(e,t){if(!rt(e)||it(e))return e;var r,i=nt(e,at);if(i){if(void 0===t&&(t="default"),r=tt(i,e,t),!rt(r)||it(r))return r;throw st("Can't convert object to primitive value")}return void 0===t&&(t="number"),ot(e,t)},ut=ct,dt=he,lt=function(e){var t=ut(e,"string");return dt(t)?t:t+""},ht=z,ft=c.document,pt=ht(ft)&&ht(ft.createElement),mt=function(e){return pt?ft.createElement(e):{}},gt=mt,_t=!l&&!d((function(){return 7!=Object.defineProperty(gt("div"),"a",{get:function(){return 7}}).a})),St=l,vt=m,yt=g,It=T,Tt=F,Rt=lt,Et=Be,bt=_t,Ct=Object.getOwnPropertyDescriptor;u.f=St?Ct:function(e,t){if(e=Tt(e),t=Rt(t),bt)try{return Ct(e,t)}catch(r){}if(Et(e,t))return It(!vt(yt.f,e,t),e[t])};var At={},wt=l&&d((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),kt=z,Ot=String,Pt=TypeError,Mt=function(e){if(kt(e))return e;throw Pt(Ot(e)+" is not an object")},Dt=l,Nt=_t,Ut=wt,xt=Mt,Lt=lt,Bt=TypeError,Vt=Object.defineProperty,Yt=Object.getOwnPropertyDescriptor,jt="enumerable",Ft="configurable",Ht="writable";At.f=Dt?Ut?function(e,t,r){if(xt(e),t=Lt(t),xt(r),"function"==typeof e&&"prototype"===t&&"value"in r&&Ht in r&&!r[Ht]){var i=Yt(e,t);i&&i[Ht]&&(e[t]=r.value,r={configurable:Ft in r?r[Ft]:i[Ft],enumerable:jt in r?r[jt]:i[jt],writable:!1})}return Vt(e,t,r)}:Vt:function(e,t,r){if(xt(e),t=Lt(t),xt(r),Nt)try{return Vt(e,t,r)}catch(i){}if("get"in r||"set"in r)throw Bt("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var Kt=At,zt=T,Wt=l?function(e,t,r){return Kt.f(e,t,zt(1,r))}:function(e,t,r){return e[t]=r,e},Gt={exports:{}},Jt=l,qt=Be,Xt=Function.prototype,Qt=Jt&&Object.getOwnPropertyDescriptor,$t=qt(Xt,"name"),Zt={EXISTS:$t,PROPER:$t&&"something"===function(){}.name,CONFIGURABLE:$t&&(!Jt||Jt&&Qt(Xt,"name").configurable)},er=H,tr=Pe,rr=w(Function.toString);er(tr.inspectSource)||(tr.inspectSource=function(e){return rr(e)});var ir,nr,or,sr=tr.inspectSource,ar=H,cr=sr,ur=c.WeakMap,dr=ar(ur)&&/native code/.test(cr(ur)),lr=be.exports,hr=He,fr=lr("keys"),pr=function(e){return fr[e]||(fr[e]=hr(e))},mr={},gr=dr,_r=c,Sr=w,vr=z,yr=Wt,Ir=Be,Tr=Pe,Rr=pr,Er=mr,br="Object already initialized",Cr=_r.TypeError,Ar=_r.WeakMap;if(gr||Tr.state){var wr=Tr.state||(Tr.state=new Ar),kr=Sr(wr.get),Or=Sr(wr.has),Pr=Sr(wr.set);ir=function(e,t){if(Or(wr,e))throw new Cr(br);return t.facade=e,Pr(wr,e,t),t},nr=function(e){return kr(wr,e)||{}},or=function(e){return Or(wr,e)}}else{var Mr=Rr("state");Er[Mr]=!0,ir=function(e,t){if(Ir(e,Mr))throw new Cr(br);return t.facade=e,yr(e,Mr,t),t},nr=function(e){return Ir(e,Mr)?e[Mr]:{}},or=function(e){return Ir(e,Mr)}}var Dr={set:ir,get:nr,has:or,enforce:function(e){return or(e)?nr(e):ir(e,{})},getterFor:function(e){return function(t){var r;if(!vr(t)||(r=nr(t)).type!==e)throw Cr("Incompatible receiver, "+e+" required");return r}}},Nr=d,Ur=H,xr=Be,Lr=l,Br=Zt.CONFIGURABLE,Vr=sr,Yr=Dr.enforce,jr=Dr.get,Fr=Object.defineProperty,Hr=Lr&&!Nr((function(){return 8!==Fr((function(){}),"length",{value:8}).length})),Kr=String(String).split("String"),zr=Gt.exports=function(e,t,r){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!xr(e,"name")||Br&&e.name!==t)&&(Lr?Fr(e,"name",{value:t,configurable:!0}):e.name=t),Hr&&r&&xr(r,"arity")&&e.length!==r.arity&&Fr(e,"length",{value:r.arity});try{r&&xr(r,"constructor")&&r.constructor?Lr&&Fr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var i=Yr(e);return xr(i,"source")||(i.source=Kr.join("string"==typeof t?t:"")),e};Function.prototype.toString=zr((function(){return Ur(this)&&jr(this).source||Vr(this)}),"toString");var Wr=H,Gr=At,Jr=Gt.exports,qr=we,Xr=function(e,t,r,i){i||(i={});var n=i.enumerable,o=void 0!==i.name?i.name:t;if(Wr(r)&&Jr(r,o,i),i.global)n?e[t]=r:qr(t,r);else{try{i.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=r:Gr.f(e,t,{value:r,enumerable:!1,configurable:!i.nonConfigurable,writable:!i.nonWritable})}return e},Qr={},$r=Math.ceil,Zr=Math.floor,ei=Math.trunc||function(e){var t=+e;return(t>0?Zr:$r)(t)},ti=ei,ri=function(e){var t=+e;return t!=t||0===t?0:ti(t)},ii=ri,ni=Math.max,oi=Math.min,si=function(e,t){var r=ii(e);return r<0?ni(r+t,0):oi(r,t)},ai=ri,ci=Math.min,ui=function(e){return e>0?ci(ai(e),9007199254740991):0},di=ui,li=function(e){return di(e.length)},hi=F,fi=si,pi=li,mi=function(e){return function(t,r,i){var n,o=hi(t),s=pi(o),a=fi(i,s);if(e&&r!=r){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===r)return e||a||0;return!e&&-1}},gi={includes:mi(!0),indexOf:mi(!1)},_i=Be,Si=F,vi=gi.indexOf,yi=mr,Ii=w([].push),Ti=function(e,t){var r,i=Si(e),n=0,o=[];for(r in i)!_i(yi,r)&&_i(i,r)&&Ii(o,r);for(;t.length>n;)_i(i,r=t[n++])&&(~vi(o,r)||Ii(o,r));return o},Ri=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ei=Ti,bi=Ri.concat("length","prototype");Qr.f=Object.getOwnPropertyNames||function(e){return Ei(e,bi)};var Ci={};Ci.f=Object.getOwnPropertySymbols;var Ai=J,wi=Qr,ki=Ci,Oi=Mt,Pi=w([].concat),Mi=Ai("Reflect","ownKeys")||function(e){var t=wi.f(Oi(e)),r=ki.f;return r?Pi(t,r(e)):t},Di=Be,Ni=Mi,Ui=u,xi=At,Li=function(e,t,r){for(var i=Ni(t),n=xi.f,o=Ui.f,s=0;s=51&&/native code/.test(e))return!1;var r=new Ts((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};return(r.constructor={})[ks]=i,!(Os=r.then((function(){}))instanceof i)||!t&&As&&!Ps})),Ds={CONSTRUCTOR:Ms,REJECTION_EVENT:Ps,SUBCLASSING:Os},Ns={},Us=Se,xs=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=i})),this.resolve=Us(t),this.reject=Us(r)};Ns.f=function(e){return new xs(e)};var Ls,Bs,Vs,Ys=en,js=tn,Fs=c,Hs=m,Ks=Xr,zs=un,Ws=fn,Gs=Sn,Js=Se,qs=H,Xs=z,Qs=In,$s=to,Zs=Xo.set,ea=ps,ta=function(e,t){var r=ms.console;r&&r.error&&(1==arguments.length?r.error(e):r.error(e,t))},ra=gs,ia=Ss,na=Dr,oa=vs,sa=Ns,aa="Promise",ca=Ds.CONSTRUCTOR,ua=Ds.REJECTION_EVENT,da=Ds.SUBCLASSING,la=na.getterFor(aa),ha=na.set,fa=oa&&oa.prototype,pa=oa,ma=fa,ga=Fs.TypeError,_a=Fs.document,Sa=Fs.process,va=sa.f,ya=va,Ia=!!(_a&&_a.createEvent&&Fs.dispatchEvent),Ta="unhandledrejection",Ra=function(e){var t;return!(!Xs(e)||!qs(t=e.then))&&t},Ea=function(e,t){var r,i,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,u=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&ka(t),t.rejection=1),!0===a?r=o:(d&&d.enter(),r=a(o),d&&(d.exit(),n=!0)),r===e.promise?u(ga("Promise-chain cycle")):(i=Ra(r))?Hs(i,r,c,u):c(r)):u(o)}catch(jN){d&&!n&&d.exit(),u(jN)}},ba=function(e,t){e.notified||(e.notified=!0,ea((function(){for(var r,i=e.reactions;r=i.get();)Ea(r,e);e.notified=!1,t&&!e.rejection&&Aa(e)})))},Ca=function(e,t,r){var i,n;Ia?((i=_a.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),Fs.dispatchEvent(i)):i={promise:t,reason:r},!ua&&(n=Fs["on"+e])?n(i):e===Ta&&ta("Unhandled promise rejection",r)},Aa=function(e){Hs(Zs,Fs,(function(){var t,r=e.facade,i=e.value;if(wa(e)&&(t=ra((function(){js?Sa.emit("unhandledRejection",i,r):Ca(Ta,r,i)})),e.rejection=js||wa(e)?2:1,t.error))throw t.value}))},wa=function(e){return 1!==e.rejection&&!e.parent},ka=function(e){Hs(Zs,Fs,(function(){var t=e.facade;js?Sa.emit("rejectionHandled",t):Ca("rejectionhandled",t,e.value)}))},Oa=function(e,t,r){return function(i){e(t,i,r)}},Pa=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,ba(e,!0))},Ma=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw ga("Promise can't be resolved itself");var i=Ra(t);i?ea((function(){var r={done:!1};try{Hs(i,t,Oa(Ma,r,e),Oa(Pa,r,e))}catch(jN){Pa(r,jN,e)}})):(e.value=t,e.state=1,ba(e,!1))}catch(jN){Pa({done:!1},jN,e)}}};if(ca&&(ma=(pa=function(e){Qs(this,ma),Js(e),Hs(Ls,this);var t=la(this);try{e(Oa(Ma,t),Oa(Pa,t))}catch(jN){Pa(t,jN)}}).prototype,(Ls=function(e){ha(this,{type:aa,done:!1,notified:!1,parent:!1,reactions:new ia,rejection:!1,state:0,value:void 0})}).prototype=Ks(ma,"then",(function(e,t){var r=la(this),i=va($s(this,pa));return r.parent=!0,i.ok=!qs(e)||e,i.fail=qs(t)&&t,i.domain=js?Sa.domain:void 0,0==r.state?r.reactions.add(i):ea((function(){Ea(i,r)})),i.promise})),Bs=function(){var e=new Ls,t=la(e);this.promise=e,this.resolve=Oa(Ma,t),this.reject=Oa(Pa,t)},sa.f=va=function(e){return e===pa||undefined===e?new Bs(e):ya(e)},qs(oa)&&fa!==Object.prototype)){Vs=fa.then,da||Ks(fa,"then",(function(e,t){var r=this;return new pa((function(e,t){Hs(Vs,r,e,t)})).then(e,t)}),{unsafe:!0});try{delete fa.constructor}catch(jN){}zs&&zs(fa,ma)}Ys({global:!0,constructor:!0,wrap:!0,forced:ca},{Promise:pa}),Ws(pa,aa,!1),Gs(aa);var Da={},Na=Da,Ua=et("iterator"),xa=Array.prototype,La=function(e){return void 0!==e&&(Na.Array===e||xa[Ua]===e)},Ba=kn,Va=ye,Ya=Da,ja=et("iterator"),Fa=function(e){if(null!=e)return Va(e,ja)||Va(e,"@@iterator")||Ya[Ba(e)]},Ha=m,Ka=Se,za=Mt,Wa=pe,Ga=Fa,Ja=TypeError,qa=function(e,t){var r=arguments.length<2?Ga(e):t;if(Ka(r))return za(Ha(r,e));throw Ja(Wa(e)+" is not iterable")},Xa=m,Qa=Mt,$a=ye,Za=lo,ec=m,tc=Mt,rc=pe,ic=La,nc=li,oc=q,sc=qa,ac=Fa,cc=function(e,t,r){var i,n;Qa(e);try{if(!(i=$a(e,"return"))){if("throw"===t)throw r;return r}i=Xa(i,e)}catch(jN){n=!0,i=jN}if("throw"===t)throw r;if(n)throw i;return Qa(i),r},uc=TypeError,dc=function(e,t){this.stopped=e,this.result=t},lc=dc.prototype,hc=function(e,t,r){var i,n,o,s,a,c,u,d=r&&r.that,l=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_ITERATOR),f=!(!r||!r.INTERRUPTED),p=Za(t,d),m=function(e){return i&&cc(i,"normal",e),new dc(!0,e)},g=function(e){return l?(tc(e),f?p(e[0],e[1],m):p(e[0],e[1])):f?p(e,m):p(e)};if(h)i=e;else{if(!(n=ac(e)))throw uc(rc(e)+" is not iterable");if(ic(n)){for(o=0,s=nc(e);s>o;o++)if((a=g(e[o]))&&oc(lc,a))return a;return new dc(!1)}i=sc(e,n)}for(c=i.next;!(u=ec(c,i)).done;){try{a=g(u.value)}catch(jN){cc(i,"throw",jN)}if("object"==typeof a&&a&&oc(lc,a))return a}return new dc(!1)},fc=et("iterator"),pc=!1;try{var mc=0,gc={next:function(){return{done:!!mc++}},return:function(){pc=!0}};gc[fc]=function(){return this},Array.from(gc,(function(){throw 2}))}catch(jN){}var _c=function(e,t){if(!t&&!pc)return!1;var r=!1;try{var i={};i[fc]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(jN){}return r},Sc=vs,vc=Ds.CONSTRUCTOR||!_c((function(e){Sc.all(e).then(void 0,(function(){}))})),yc=m,Ic=Se,Tc=Ns,Rc=gs,Ec=hc;en({target:"Promise",stat:!0,forced:vc},{all:function(e){var t=this,r=Tc.f(t),i=r.resolve,n=r.reject,o=Rc((function(){var r=Ic(t.resolve),o=[],s=0,a=1;Ec(e,(function(e){var c=s++,u=!1;a++,yc(r,t,e).then((function(e){u||(u=!0,o[c]=e,--a||i(o))}),n)})),--a||i(o)}));return o.error&&n(o.value),r.promise}});var bc=en,Cc=Ds.CONSTRUCTOR,Ac=vs,wc=J,kc=H,Oc=Xr,Pc=Ac&&Ac.prototype;if(bc({target:"Promise",proto:!0,forced:Cc,real:!0},{catch:function(e){return this.then(void 0,e)}}),kc(Ac)){var Mc=wc("Promise").prototype.catch;Pc.catch!==Mc&&Oc(Pc,"catch",Mc,{unsafe:!0})}var Dc=m,Nc=Se,Uc=Ns,xc=gs,Lc=hc;en({target:"Promise",stat:!0,forced:vc},{race:function(e){var t=this,r=Uc.f(t),i=r.reject,n=xc((function(){var n=Nc(t.resolve);Lc(e,(function(e){Dc(n,t,e).then(r.resolve,i)}))}));return n.error&&i(n.value),r.promise}});var Bc=m,Vc=Ns;en({target:"Promise",stat:!0,forced:Ds.CONSTRUCTOR},{reject:function(e){var t=Vc.f(this);return Bc(t.reject,void 0,e),t.promise}});var Yc=Mt,jc=z,Fc=Ns,Hc=function(e,t){if(Yc(e),jc(t)&&t.constructor===e)return t;var r=Fc.f(e);return(0,r.resolve)(t),r.promise},Kc=en,zc=Ds.CONSTRUCTOR,Wc=Hc;J("Promise"),Kc({target:"Promise",stat:!0,forced:zc},{resolve:function(e){return Wc(this,e)}});let Gc=function(e){return e[e.RTC_ERR_CODE_SUCCESS=0]="RTC_ERR_CODE_SUCCESS",e[e.RTC_ERR_CODE_RTC_SDK_ERROR=90000001]="RTC_ERR_CODE_RTC_SDK_ERROR",e[e.RTC_ERR_CODE_WAIT_RSP_TIMEOUT=90000004]="RTC_ERR_CODE_WAIT_RSP_TIMEOUT",e[e.RTC_ERR_CODE_INVALID_PARAMETER=90000005]="RTC_ERR_CODE_INVALID_PARAMETER",e[e.RTC_ERR_CODE_INVALID_OPERATION=90100001]="RTC_ERR_CODE_INVALID_OPERATION",e[e.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES=90100002]="RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_DEVICES=90100003]="RTC_ERR_CODE_NO_AVAILABLE_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES=90100004]="RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES=90100005]="RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES",e[e.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES=90100006]="RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES",e[e.RTC_ERR_CODE_STATUS_ERROR=90100007]="RTC_ERR_CODE_STATUS_ERROR",e[e.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED=90100008]="RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED",e[e.RTC_ERR_CODE_WAIT_CONFIG_FAIL=90100009]="RTC_ERR_CODE_WAIT_CONFIG_FAIL",e[e.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL=90100010]="RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL",e[e.RTC_ERR_CODE_REGION_NOT_COVERED=90100011]="RTC_ERR_CODE_REGION_NOT_COVERED",e[e.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT=90100012]="RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT",e[e.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT=90100013]="RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT",e[e.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN=90100014]="RTC_ERR_CODE_WEBSOCKET_NOT_OPEN",e[e.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED=90100015]="RTC_ERR_CODE_WEBSOCKET_INTERRUPTED",e[e.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR=90100016]="RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR",e[e.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED=90100017]="RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED",e[e.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED=90100018]="RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED",e[e.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND=90100019]="RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND",e[e.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE=90100020]="RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE",e[e.RTC_ERR_CODE_PLAY_NOT_ALLOW=90100021]="RTC_ERR_CODE_PLAY_NOT_ALLOW",e[e.RTC_ERR_CODE_ROLE_NO_PERMISSION=90100022]="RTC_ERR_CODE_ROLE_NO_PERMISSION",e[e.RTC_ERR_CODE_ANSWER_SDP_INVALID=90100023]="RTC_ERR_CODE_ANSWER_SDP_INVALID",e[e.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED=90100024]="RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED",e[e.RTC_ERR_CODE_WEBRTC_UNSUPPORTED=90100025]="RTC_ERR_CODE_WEBRTC_UNSUPPORTED",e[e.RTC_ERR_CODE_MEDIA_NETWORK_ERROR=90100026]="RTC_ERR_CODE_MEDIA_NETWORK_ERROR",e[e.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM=90100027]="RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM",e[e.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM=90100028]="RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM",e[e.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED=90100029]="RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED",e[e.RTC_ERR_CODE_SIGNATURE_EXPIRED=90100030]="RTC_ERR_CODE_SIGNATURE_EXPIRED",e[e.RTC_ERR_CODE_SIGNATURE_INVALID=90100031]="RTC_ERR_CODE_SIGNATURE_INVALID",e[e.RTC_ERR_CODE_RTC_ACS=90100100]="RTC_ERR_CODE_RTC_ACS",e[e.RTC_ERR_CODE_RTC_CONTROL_ERROR=90100200]="RTC_ERR_CODE_RTC_CONTROL_ERROR",e[e.RTC_ERR_CODE_SFU_ERROR=90100600]="RTC_ERR_CODE_SFU_ERROR",e}({});const Jc={[Gc.RTC_ERR_CODE_SUCCESS]:"success",[Gc.RTC_ERR_CODE_RTC_SDK_ERROR]:"sdk internal error",[Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES]:"not support enumerate devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES]:"no available devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES]:"no available video input devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES]:"no available audio input devices",[Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES]:"no available audio output devices",[Gc.RTC_ERR_CODE_STATUS_ERROR]:"room status error",[Gc.RTC_ERR_CODE_INVALID_PARAMETER]:"invalid parameter",[Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED]:'websocket connection state is not "CONNECTED"',[Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN]:"websocket is not open",[Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL]:"wait server config fail",[Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT]:"message response timeout",[Gc.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL]:"publish response fail",[Gc.RTC_ERR_CODE_REGION_NOT_COVERED]:"current region is not covered, service unavailable",[Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT]:"websocket connect timeout",[Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT]:"websocket reconnect timeout",[Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED]:"websocket connection state is idle, interrupt operation",[Gc.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED]:"capture failed, permission denied",[Gc.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED]:"capture failed, Constraint parameter invalid",[Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND]:"capture failed, requested device not found",[Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE]:"capture failed, maybe device is occupied by other application",[Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW]:"the user didn't interact with the document first, please trigger by gesture",[Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION]:"the user role have no permission to operate",[Gc.RTC_ERR_CODE_ANSWER_SDP_INVALID]:"the answer sdp is invalid",[Gc.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED]:"the upstream media is not supported",[Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED]:"the browser does not support",[Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR]:"media connection establish failed, please switch network or try again later",[Gc.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM]:"relay room number over maxium number.",[Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED]:"room stream status paused",[Gc.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM]:"joiner already exist in relay rooms.",[Gc.RTC_ERR_CODE_SIGNATURE_INVALID]:"signature invalid",[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]:"signature expired"};class qc extends Error{constructor(e,t){const r=e;let i,n="";r>9e7&&r<90100100||r<100?(i=r,n=t||r in Gc&&Jc[r]):r>=6e5&&r<7e5?(i=Gc.RTC_ERR_CODE_SFU_ERROR,n="code: ".concat(r,", msg: ").concat(t)):r>=2e5&&r<3e5?(i=Gc.RTC_ERR_CODE_RTC_CONTROL_ERROR,n="code: ".concat(r,", msg: ").concat(t)):r>=1e5&&r<2e5?(i=Gc.RTC_ERR_CODE_RTC_ACS,n="code: ".concat(r,", msg: ").concat(t)):(n="unknow error",i=r),super(n),this.code=i,this.message=n}getCode(){return this.code}getMsg(){return this.message}toString(){return'["code": '.concat(this.code,', "message": "').concat(this.message,'"]')}}var Xc=kn,Qc=String,$c=function(e){if("Symbol"===Xc(e))throw TypeError("Cannot convert a Symbol value to a string");return Qc(e)},Zc=en,eu=l,tu=c,ru=w,iu=Be,nu=H,ou=q,su=$c,au=At.f,cu=Li,uu=tu.Symbol,du=uu&&uu.prototype;if(eu&&nu(uu)&&(!("description"in du)||void 0!==uu().description)){var lu={},hu=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:su(arguments[0]),t=ou(du,this)?new uu(e):void 0===e?uu():uu(e);return""===e&&(lu[t]=!0),t};cu(hu,uu),hu.prototype=du,du.constructor=hu;var fu="Symbol(test)"==String(uu("test")),pu=ru(du.toString),mu=ru(du.valueOf),gu=/^Symbol\((.*)\)[^)]+$/,_u=ru("".replace),Su=ru("".slice);au(du,"description",{configurable:!0,get:function(){var e=mu(this),t=pu(e);if(iu(lu,e))return"";var r=fu?Su(t,7,-1):_u(t,gu,"$1");return""===r?void 0:r}}),Zc({global:!0,constructor:!0,forced:!0},{Symbol:hu})}var vu={},yu=Ti,Iu=Ri,Tu=Object.keys||function(e){return yu(e,Iu)},Ru=l,Eu=wt,bu=At,Cu=Mt,Au=F,wu=Tu;vu.f=Ru&&!Eu?Object.defineProperties:function(e,t){Cu(e);for(var r,i=Au(t),n=wu(t),o=n.length,s=0;o>s;)bu.f(e,r=n[s++],i[r]);return e};var ku,Ou=Mt,Pu=vu,Mu=Ri,Du=mr,Nu=ho,Uu=mt,xu="prototype",Lu="script",Bu=pr("IE_PROTO"),Vu=function(){},Yu=function(e){return"<"+Lu+">"+e+""},ju=function(e){e.write(Yu("")),e.close();var t=e.parentWindow.Object;return e=null,t},Fu=function(){try{ku=new ActiveXObject("htmlfile")}catch(jN){}var e,t,r;Fu="undefined"!=typeof document?document.domain&&ku?ju(ku):(t=Uu("iframe"),r="java"+Lu+":",t.style.display="none",Nu.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write(Yu("document.F=Object")),e.close(),e.F):ju(ku);for(var i=Mu.length;i--;)delete Fu[xu][Mu[i]];return Fu()};Du[Bu]=!0;var Hu=Object.create||function(e,t){var r;return null!==e?(Vu[xu]=Ou(e),r=new Vu,Vu[xu]=null,r[Bu]=e):r=Fu(),void 0===t?r:Pu.f(r,t)},Ku=et,zu=Hu,Wu=At.f,Gu=Ku("unscopables"),Ju=Array.prototype;null==Ju[Gu]&&Wu(Ju,Gu,{configurable:!0,value:zu(null)});var qu,Xu,Qu,$u=function(e){Ju[Gu][e]=!0},Zu=!d((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),ed=Be,td=H,rd=Ue,id=Zu,nd=pr("IE_PROTO"),od=Object,sd=od.prototype,ad=id?od.getPrototypeOf:function(e){var t=rd(e);if(ed(t,nd))return t[nd];var r=t.constructor;return td(r)&&t instanceof r?r.prototype:t instanceof od?sd:null},cd=d,ud=H,dd=ad,ld=Xr,hd=et("iterator"),fd=!1;[].keys&&("next"in(Qu=[].keys())?(Xu=dd(dd(Qu)))!==Object.prototype&&(qu=Xu):fd=!0);var pd=null==qu||cd((function(){var e={};return qu[hd].call(e)!==e}));pd&&(qu={}),ud(qu[hd])||ld(qu,hd,(function(){return this}));var md={IteratorPrototype:qu,BUGGY_SAFARI_ITERATORS:fd},gd=md.IteratorPrototype,_d=Hu,Sd=T,vd=fn,yd=Da,Id=function(){return this},Td=en,Rd=m,Ed=H,bd=function(e,t,r,i){var n=t+" Iterator";return e.prototype=_d(gd,{next:Sd(+!i,r)}),vd(e,n,!1),yd[n]=Id,e},Cd=ad,Ad=un,wd=fn,kd=Wt,Od=Xr,Pd=Da,Md=Zt.PROPER,Dd=Zt.CONFIGURABLE,Nd=md.IteratorPrototype,Ud=md.BUGGY_SAFARI_ITERATORS,xd=et("iterator"),Ld="keys",Bd="values",Vd="entries",Yd=function(){return this},jd=F,Fd=$u,Hd=Da,Kd=Dr,zd=At.f,Wd=function(e,t,r,i,n,o,s){bd(r,t,i);var a,c,u,d=function(e){if(e===n&&m)return m;if(!Ud&&e in f)return f[e];switch(e){case Ld:case Bd:case Vd:return function(){return new r(this,e)}}return function(){return new r(this)}},l=t+" Iterator",h=!1,f=e.prototype,p=f[xd]||f["@@iterator"]||n&&f[n],m=!Ud&&p||d(n),g="Array"==t&&f.entries||p;if(g&&(a=Cd(g.call(new e)))!==Object.prototype&&a.next&&(Cd(a)!==Nd&&(Ad?Ad(a,Nd):Ed(a[xd])||Od(a,xd,Yd)),wd(a,l,!0)),Md&&n==Bd&&p&&p.name!==Bd&&(Dd?kd(f,"name",Bd):(h=!0,m=function(){return Rd(p,this)})),n)if(c={values:d(Bd),keys:o?m:d(Ld),entries:d(Vd)},s)for(u in c)(Ud||h||!(u in f))&&Od(f,u,c[u]);else Td({target:t,proto:!0,forced:Ud||h},c);return f[xd]!==m&&Od(f,xd,m,{name:n}),Pd[t]=m,c},Gd=l,Jd="Array Iterator",qd=Kd.set,Xd=Kd.getterFor(Jd),Qd=Wd(Array,"Array",(function(e,t){qd(this,{type:Jd,target:jd(e),index:0,kind:t})}),(function(){var e=Xd(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==r?{value:i,done:!1}:"values"==r?{value:t[i],done:!1}:{value:[i,t[i]],done:!1}}),"values"),$d=Hd.Arguments=Hd.Array;if(Fd("keys"),Fd("values"),Fd("entries"),Gd&&"values"!==$d.name)try{zd($d,"name",{value:"values"})}catch(jN){}var Zd=m,el=Se,tl=Mt,rl=function(){for(var e,t=tl(this),r=el(t.delete),i=!0,n=0,o=arguments.length;n1?arguments[1]:void 0);return!cl(r,(function(e,r,n){if(!i(r,e,t))return n()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var ul=J,dl=lo,ll=m,hl=Se,fl=Mt,pl=to,ml=nl,gl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{filter:function(e){var t=fl(this),r=ml(t),i=dl(e,arguments.length>1?arguments[1]:void 0),n=new(pl(t,ul("Map"))),o=hl(n.set);return gl(r,(function(e,r){i(r,e,t)&&ll(o,n,e,r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var _l=Mt,Sl=lo,vl=nl,yl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{find:function(e){var t=_l(this),r=vl(t),i=Sl(e,arguments.length>1?arguments[1]:void 0);return yl(r,(function(e,r,n){if(i(r,e,t))return n(r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var Il=Mt,Tl=lo,Rl=nl,El=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{findKey:function(e){var t=Il(this),r=Rl(t),i=Tl(e,arguments.length>1?arguments[1]:void 0);return El(r,(function(e,r,n){if(i(r,e,t))return n(e)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var bl=Mt,Cl=nl,Al=function(e,t){return e===t||e!=e&&t!=t},wl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{includes:function(e){return wl(Cl(bl(this)),(function(t,r,i){if(Al(r,e))return i()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var kl=Mt,Ol=nl,Pl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{keyOf:function(e){return Pl(Ol(kl(this)),(function(t,r,i){if(r===e)return i(t)}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var Ml=J,Dl=lo,Nl=m,Ul=Se,xl=Mt,Ll=to,Bl=nl,Vl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{mapKeys:function(e){var t=xl(this),r=Bl(t),i=Dl(e,arguments.length>1?arguments[1]:void 0),n=new(Ll(t,Ml("Map"))),o=Ul(n.set);return Vl(r,(function(e,r){Nl(o,n,i(r,e,t),r)}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var Yl=J,jl=lo,Fl=m,Hl=Se,Kl=Mt,zl=to,Wl=nl,Gl=hc;en({target:"Map",proto:!0,real:!0,forced:!0},{mapValues:function(e){var t=Kl(this),r=Wl(t),i=jl(e,arguments.length>1?arguments[1]:void 0),n=new(zl(t,Yl("Map"))),o=Hl(n.set);return Gl(r,(function(e,r){Fl(o,n,e,i(r,e,t))}),{AS_ENTRIES:!0,IS_ITERATOR:!0}),n}});var Jl=Se,ql=Mt,Xl=hc;en({target:"Map",proto:!0,real:!0,arity:1,forced:!0},{merge:function(e){for(var t=ql(this),r=Jl(t.set),i=arguments.length,n=0;n1?arguments[1]:void 0);return oh(r,(function(e,r,n){if(i(r,e,t))return n()}),{AS_ENTRIES:!0,IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var sh=m,ah=Mt,ch=Se,uh=TypeError;en({target:"Map",proto:!0,real:!0,forced:!0},{update:function(e,t){var r=ah(this),i=ch(r.get),n=ch(r.has),o=ch(r.set),s=arguments.length;ch(t);var a=sh(n,r,e);if(!a&&s<3)throw uh("Updating absent value");var c=a?sh(i,r,e):ch(s>2?arguments[2]:void 0)(e,r);return sh(o,r,e,t(c,e,r)),r}});var dh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},lh=mt("span").classList,hh=lh&&lh.constructor&&lh.constructor.prototype,fh=hh===Object.prototype?void 0:hh,ph=c,mh=dh,gh=fh,_h=Qd,Sh=Wt,vh=et,yh=vh("iterator"),Ih=vh("toStringTag"),Th=_h.values,Rh=function(e,t){if(e){if(e[yh]!==Th)try{Sh(e,yh,Th)}catch(jN){e[yh]=Th}if(e[Ih]||Sh(e,Ih,t),mh[t])for(var r in _h)if(e[r]!==_h[r])try{Sh(e,r,_h[r])}catch(jN){e[r]=_h[r]}}};for(var Eh in mh)Rh(ph[Eh]&&ph[Eh].prototype,Eh);Rh(gh,"DOMTokenList");var bh=M,Ch=Array.isArray||function(e){return"Array"==bh(e)},Ah=Gn,wh=z,kh=et("species"),Oh=Array,Ph=function(e){var t;return Ch(e)&&(t=e.constructor,(Ah(t)&&(t===Oh||Ch(t.prototype))||wh(t)&&null===(t=t[kh]))&&(t=void 0)),void 0===t?Oh:t},Mh=lo,Dh=L,Nh=Ue,Uh=li,xh=function(e,t){return new(Ph(e))(0===t?0:t)},Lh=w([].push),Bh=function(e){var t=1==e,r=2==e,i=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,u,d,l){for(var h,f,p=Nh(c),m=Dh(p),g=Mh(u,d),_=Uh(m),S=0,v=l||xh,y=t?v(c,_):r||s?v(c,0):void 0;_>S;S++)if((a||S in m)&&(f=g(h=m[S],S,p),e))if(t)y[S]=f;else if(f)switch(e){case 3:return!0;case 5:return h;case 6:return S;case 2:Lh(y,h)}else switch(e){case 4:return!1;case 7:Lh(y,h)}return o?-1:i||n?n:y}},Vh={forEach:Bh(0),map:Bh(1),filter:Bh(2),some:Bh(3),every:Bh(4),find:Bh(5),findIndex:Bh(6),filterReject:Bh(7)},Yh=d,jh=function(e,t){var r=[][e];return!!r&&Yh((function(){r.call(null,t||function(){return 1},1)}))},Fh=Vh.forEach,Hh=jh("forEach")?[].forEach:function(e){return Fh(this,e,arguments.length>1?arguments[1]:void 0)},Kh=c,zh=dh,Wh=fh,Gh=Hh,Jh=Wt,qh=function(e){if(e&&e.forEach!==Gh)try{Jh(e,"forEach",Gh)}catch(jN){e.forEach=Gh}};for(var Xh in zh)zh[Xh]&&qh(Kh[Xh]&&Kh[Xh].prototype);qh(Wh);var Qh=gi.includes,$h=$u;en({target:"Array",proto:!0,forced:d((function(){return!Array(1).includes()}))},{includes:function(e){return Qh(this,e,arguments.length>1?arguments[1]:void 0)}}),$h("includes");var Zh=Mt,ef=function(){var e=Zh(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},tf=d,rf=c.RegExp,nf=tf((function(){var e=rf("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),of=nf||tf((function(){return!rf("a","y").sticky})),sf=nf||tf((function(){var e=rf("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),af={BROKEN_CARET:sf,MISSED_STICKY:of,UNSUPPORTED_Y:nf},cf=d,uf=c.RegExp,df=cf((function(){var e=uf(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),lf=d,hf=c.RegExp,ff=lf((function(){var e=hf("(?b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$c")})),pf=m,mf=w,gf=$c,_f=ef,Sf=af,vf=be.exports,yf=Hu,If=Dr.get,Tf=df,Rf=ff,Ef=vf("native-string-replace",String.prototype.replace),bf=RegExp.prototype.exec,Cf=bf,Af=mf("".charAt),wf=mf("".indexOf),kf=mf("".replace),Of=mf("".slice),Pf=function(){var e=/a/,t=/b*/g;return pf(bf,e,"a"),pf(bf,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Mf=Sf.BROKEN_CARET,Df=void 0!==/()??/.exec("")[1];(Pf||Df||Mf||Tf||Rf)&&(Cf=function(e){var t,r,i,n,o,s,a,c=this,u=If(c),d=gf(e),l=u.raw;if(l)return l.lastIndex=c.lastIndex,t=pf(Cf,l,d),c.lastIndex=l.lastIndex,t;var h=u.groups,f=Mf&&c.sticky,p=pf(_f,c),m=c.source,g=0,_=d;if(f&&(p=kf(p,"y",""),-1===wf(p,"g")&&(p+="g"),_=Of(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Af(d,c.lastIndex-1))&&(m="(?: "+m+")",_=" "+_,g++),r=new RegExp("^(?:"+m+")",p)),Df&&(r=new RegExp("^"+m+"$(?!\\s)",p)),Pf&&(i=c.lastIndex),n=pf(bf,f?r:c,_),f?n?(n.input=Of(n.input,g),n[0]=Of(n[0],g),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Pf&&n&&(c.lastIndex=c.global?n.index+n[0].length:i),Df&&n&&n.length>1&&pf(Ef,n[0],r,(function(){for(o=1;o=a?e?"":void 0:(i=Jf(o,s))<55296||i>56319||s+1===a||(n=Jf(o,s+1))<56320||n>57343?e?Gf(o,s):i:e?qf(o,s,s+2):n-56320+(i-55296<<10)+65536}},Qf={codeAt:Xf(!1),charAt:Xf(!0)}.charAt,$f=w,Zf=Ue,ep=Math.floor,tp=$f("".charAt),rp=$f("".replace),ip=$f("".slice),np=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,op=/\$([$&'`]|\d{1,2})/g,sp=function(e,t,r,i,n,o){var s=r+e.length,a=i.length,c=op;return void 0!==n&&(n=Zf(n),c=np),rp(o,c,(function(o,c){var u;switch(tp(c,0)){case"$":return"$";case"&":return e;case"`":return ip(t,0,r);case"'":return ip(t,s);case"<":u=n[ip(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var l=ep(d/10);return 0===l?o:l<=a?void 0===i[l-1]?tp(c,1):i[l-1]+tp(c,1):o}u=i[d-1]}return void 0===u?"":u}))},ap=m,cp=Mt,up=H,dp=M,lp=Nf,hp=TypeError,fp=so,pp=m,mp=w,gp=function(e,t,r,i){var n=Vf(e),o=!Bf((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Bf((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[jf]=function(){return r},r.flags="",r[n]=/./[n]),r.exec=function(){return t=!0,null},r[n](""),!t}));if(!o||!s||r){var a=Uf(/./[n]),c=t(n,""[e],(function(e,t,r,i,n){var s=Uf(e),c=t.exec;return c===Lf||c===Ff.exec?o&&!n?{done:!0,value:a(t,r,i)}:{done:!0,value:s(r,t,i)}:{done:!1}}));xf(String.prototype,e,c[0]),xf(Ff,n,c[1])}i&&Yf(Ff[n],"sham",!0)},_p=d,Sp=Mt,vp=H,yp=ri,Ip=ui,Tp=$c,Rp=V,Ep=function(e,t,r){return t+(r?Qf(e,t).length:1)},bp=ye,Cp=sp,Ap=function(e,t){var r=e.exec;if(up(r)){var i=ap(r,e,t);return null!==i&&cp(i),i}if("RegExp"===dp(e))return ap(lp,e,t);throw hp("RegExp#exec called on incompatible receiver")},wp=et("replace"),kp=Math.max,Op=Math.min,Pp=mp([].concat),Mp=mp([].push),Dp=mp("".indexOf),Np=mp("".slice),Up="$0"==="a".replace(/./,"$0"),xp=!!/./[wp]&&""===/./[wp]("a","$0"),Lp=!_p((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")}));gp("replace",(function(e,t,r){var i=xp?"$":"$0";return[function(e,r){var i=Rp(this),n=null==e?void 0:bp(e,wp);return n?pp(n,e,i,r):pp(t,Tp(i),e,r)},function(e,n){var o=Sp(this),s=Tp(e);if("string"==typeof n&&-1===Dp(n,i)&&-1===Dp(n,"$<")){var a=r(t,o,s,n);if(a.done)return a.value}var c=vp(n);c||(n=Tp(n));var u=o.global;if(u){var d=o.unicode;o.lastIndex=0}for(var l=[];;){var h=Ap(o,s);if(null===h)break;if(Mp(l,h),!u)break;""===Tp(h[0])&&(o.lastIndex=Ep(s,Ip(o.lastIndex),d))}for(var f,p="",m=0,g=0;g=m&&(p+=Np(s,m,S)+R,m=S+_.length)}return p+Np(s,m)}]}),!Lp||!Up||xp);var Bp=z,Vp=M,Yp=et("match"),jp=function(e){var t;return Bp(e)&&(void 0!==(t=e[Yp])?!!t:"RegExp"==Vp(e))},Fp=m,Hp=Be,Kp=q,zp=ef,Wp=RegExp.prototype,Gp=function(e){var t=e.flags;return void 0!==t||"flags"in Wp||Hp(e,"flags")||!Kp(Wp,e)?t:Fp(zp,e)},Jp=en,qp=m,Xp=w,Qp=V,$p=H,Zp=jp,em=$c,tm=ye,rm=Gp,im=sp,nm=et("replace"),om=TypeError,sm=Xp("".indexOf);Xp("".replace);var am=Xp("".slice),cm=Math.max,um=function(e,t,r){return r>e.length?-1:""===t?r:sm(e,t,r)};Jp({target:"String",proto:!0},{replaceAll:function(e,t){var r,i,n,o,s,a,c,u,d=Qp(this),l=0,h=0,f="";if(null!=e){if(Zp(e)&&(r=em(Qp(rm(e))),!~sm(r,"g")))throw om("`.replaceAll` does not allow non-global regexes");if(i=tm(e,nm))return qp(i,e,d,t)}for(n=em(d),o=em(e),(s=$p(t))||(t=em(t)),a=o.length,c=cm(1,a),l=um(n,o,0);-1!==l;)u=s?em(t(o,l,n)):im(o,n,l,[],void 0,t),f+=am(n,h,l)+u,h=l+a,l=um(n,o,l+c);return h@^][^\s!#%&*+<=>@^]*>/,zm=/a/g,Wm=/a/g,Gm=new xm(zm)!==zm,Jm=Cm.MISSED_STICKY,qm=Cm.UNSUPPORTED_Y,Xm=mm&&(!Gm||Jm||Dm||Nm||km((function(){return Wm[Um]=!1,xm(zm)!=zm||xm(Wm)==Wm||"/a/i"!=xm(zm,"i")})));if(Sm("RegExp",Xm)){for(var Qm=function(e,t){var r,i,n,o,s,a,c=Tm(Lm,this),u=Rm(e),d=void 0===t,l=[],h=e;if(!c&&u&&d&&e.constructor===Qm)return e;if((u||Tm(Lm,e))&&(e=e.source,d&&(t=bm(h))),e=void 0===e?"":Em(e),t=void 0===t?"":Em(t),h=e,Dm&&"dotAll"in zm&&(i=!!t&&Fm(t,"s")>-1)&&(t=jm(t,/s/g,"")),r=t,Jm&&"sticky"in zm&&(n=!!t&&Fm(t,"y")>-1)&&qm&&(t=jm(t,/y/g,"")),Nm&&(o=function(e){for(var t,r=e.length,i=0,n="",o=[],s={},a=!1,c=!1,u=0,d="";i<=r;i++){if("\\"===(t=Ym(e,i)))t+=Ym(e,++i);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:Vm(Km,Hm(e,i+1))&&(i+=2,c=!0),n+=t,u++;continue;case">"===t&&c:if(""===d||Om(s,d))throw new Bm("Invalid capture group name");s[d]=!0,o[o.length]=[d,u],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],l=o[1]),s=vm(xm(e,t),c?this:Lm,Qm),(i||n||l.length)&&(a=Pm(s),i&&(a.dotAll=!0,a.raw=Qm(function(e){for(var t,r=e.length,i=0,n="",o=!1;i<=r;i++)"\\"!==(t=Ym(e,i))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+Ym(e,++i);return n}(e),r)),n&&(a.sticky=!0),l.length&&(a.groups=l)),e!==h)try{ym(s,"source",""===h?"(?:)":h)}catch(jN){}return s},$m=Im(xm),Zm=0;$m.length>Zm;)Am(Qm,xm,$m[Zm++]);Lm.constructor=Qm,Qm.prototype=Lm,wm(gm,"RegExp",Qm,{constructor:!0})}Mm("RegExp");const eg=["none","error","warn","info","debug"];var tg="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},rg=[],ig=[],ng="undefined"!=typeof Uint8Array?Uint8Array:Array,og=!1;function sg(){og=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)rg[t]=e[t],ig[e.charCodeAt(t)]=t;ig["-".charCodeAt(0)]=62,ig["_".charCodeAt(0)]=63}function ag(e,t,r){for(var i,n,o=[],s=t;s>18&63]+rg[n>>12&63]+rg[n>>6&63]+rg[63&n]);return o.join("")}function cg(e){var t;og||sg();for(var r=e.length,i=r%3,n="",o=[],s=16383,a=0,c=r-i;ac?c:a+s));return 1===i?(t=e[r-1],n+=rg[t>>2],n+=rg[t<<4&63],n+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],n+=rg[t>>10],n+=rg[t>>4&63],n+=rg[t<<2&63],n+="="),o.push(n),o.join("")}function ug(e,t,r,i,n){var o,s,a=8*n-i-1,c=(1<>1,d=-7,l=r?n-1:0,h=r?-1:1,f=e[t+l];for(l+=h,o=f&(1<<-d)-1,f>>=-d,d+=a;d>0;o=256*o+e[t+l],l+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=i;d>0;s=256*s+e[t+l],l+=h,d-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,i),o-=u}return(f?-1:1)*s*Math.pow(2,o-i)}function dg(e,t,r,i,n,o){var s,a,c,u=8*o-n-1,d=(1<>1,h=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:o-1,p=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+l>=1?h/c:h*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=d?(a=0,s=d):s+l>=1?(a=(t*c-1)*Math.pow(2,n),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,n),s=0));n>=8;e[r+f]=255&a,f+=p,a/=256,n-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,u-=8);e[r+f-p]|=128*m}var lg={}.toString,hg=Array.isArray||function(e){return"[object Array]"==lg.call(e)};function fg(){return mg.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function pg(e,t){if(fg()=fg())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fg().toString(16)+" bytes");return 0|e}function Ig(e){return!(null==e||!e._isBuffer)}function Tg(e,t){if(Ig(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return qg(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Xg(e).length;default:if(i)return qg(e).length;t=(""+t).toLowerCase(),i=!0}}function Rg(e,t,r){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Bg(this,t,r);case"utf8":case"utf-8":return Ng(this,t,r);case"ascii":return xg(this,t,r);case"latin1":case"binary":return Lg(this,t,r);case"base64":return Dg(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Vg(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function Eg(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function bg(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=mg.from(t,i)),Ig(t))return 0===t.length?-1:Cg(e,t,r,i,n);if("number"==typeof t)return t&=255,mg.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Cg(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Cg(e,t,r,i,n){var o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){var d=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){for(var l=!0,h=0;hn&&(i=n):i=n;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var s=0;s>8,n=r%256,o.push(n),o.push(i);return o}(t,e.length-r),e,r,i)}function Dg(e,t,r){return 0===t&&r===e.length?cg(e):cg(e.slice(t,r))}function Ng(e,t,r){r=Math.min(e.length,r);for(var i=[],n=t;n239?4:u>223?3:u>191?2:1;if(n+l<=r)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(o=e[n+1]))&&(c=(31&u)<<6|63&o)>127&&(d=c);break;case 3:o=e[n+1],s=e[n+2],128==(192&o)&&128==(192&s)&&(c=(15&u)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:o=e[n+1],s=e[n+2],a=e[n+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d),n+=l}return function(e){var t=e.length;if(t<=Ug)return String.fromCharCode.apply(String,e);var r="",i=0;for(;i0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},mg.prototype.compare=function(e,t,r,i,n){if(!Ig(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&t>=r)return 0;if(i>=n)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(i>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),c=this.slice(i,n),u=e.slice(t,r),d=0;dn)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Ag(this,e,t,r);case"utf8":case"utf-8":return wg(this,e,t,r);case"ascii":return kg(this,e,t,r);case"latin1":case"binary":return Og(this,e,t,r);case"base64":return Pg(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Mg(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},mg.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ug=4096;function xg(e,t,r){var i="";r=Math.min(e.length,r);for(var n=t;ni)&&(r=i);for(var n="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function jg(e,t,r,i,n,o){if(!Ig(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw new RangeError("Index out of range")}function Fg(e,t,r,i){t<0&&(t=65535+t+1);for(var n=0,o=Math.min(e.length-r,2);n>>8*(i?n:1-n)}function Hg(e,t,r,i){t<0&&(t=4294967295+t+1);for(var n=0,o=Math.min(e.length-r,4);n>>8*(i?n:3-n)&255}function Kg(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function zg(e,t,r,i,n){return n||Kg(e,0,r,4),dg(e,t,r,i,23,4),r+4}function Wg(e,t,r,i,n){return n||Kg(e,0,r,8),dg(e,t,r,i,52,8),r+8}mg.prototype.slice=function(e,t){var r,i=this.length;if((e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t0&&(n*=256);)i+=this[e+--t]*n;return i},mg.prototype.readUInt8=function(e,t){return t||Yg(e,1,this.length),this[e]},mg.prototype.readUInt16LE=function(e,t){return t||Yg(e,2,this.length),this[e]|this[e+1]<<8},mg.prototype.readUInt16BE=function(e,t){return t||Yg(e,2,this.length),this[e]<<8|this[e+1]},mg.prototype.readUInt32LE=function(e,t){return t||Yg(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},mg.prototype.readUInt32BE=function(e,t){return t||Yg(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},mg.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Yg(e,t,this.length);for(var i=this[e],n=1,o=0;++o=(n*=128)&&(i-=Math.pow(2,8*t)),i},mg.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Yg(e,t,this.length);for(var i=t,n=1,o=this[e+--i];i>0&&(n*=256);)o+=this[e+--i]*n;return o>=(n*=128)&&(o-=Math.pow(2,8*t)),o},mg.prototype.readInt8=function(e,t){return t||Yg(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},mg.prototype.readInt16LE=function(e,t){t||Yg(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},mg.prototype.readInt16BE=function(e,t){t||Yg(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},mg.prototype.readInt32LE=function(e,t){return t||Yg(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},mg.prototype.readInt32BE=function(e,t){return t||Yg(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},mg.prototype.readFloatLE=function(e,t){return t||Yg(e,4,this.length),ug(this,e,!0,23,4)},mg.prototype.readFloatBE=function(e,t){return t||Yg(e,4,this.length),ug(this,e,!1,23,4)},mg.prototype.readDoubleLE=function(e,t){return t||Yg(e,8,this.length),ug(this,e,!0,52,8)},mg.prototype.readDoubleBE=function(e,t){return t||Yg(e,8,this.length),ug(this,e,!1,52,8)},mg.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||jg(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+n]=e/o&255;return t+r},mg.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,1,255,0),mg.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},mg.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,65535,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Fg(this,e,t,!0),t+2},mg.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,65535,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Fg(this,e,t,!1),t+2},mg.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,4294967295,0),mg.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Hg(this,e,t,!0),t+4},mg.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,4294967295,0),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Hg(this,e,t,!1),t+4},mg.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);jg(this,e,t,r,n-1,-n)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+r},mg.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);jg(this,e,t,r,n-1,-n)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},mg.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,1,127,-128),mg.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},mg.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,32767,-32768),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Fg(this,e,t,!0),t+2},mg.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,2,32767,-32768),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Fg(this,e,t,!1),t+2},mg.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,2147483647,-2147483648),mg.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Hg(this,e,t,!0),t+4},mg.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||jg(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),mg.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Hg(this,e,t,!1),t+4},mg.prototype.writeFloatLE=function(e,t,r){return zg(this,e,t,!0,r)},mg.prototype.writeFloatBE=function(e,t,r){return zg(this,e,t,!1,r)},mg.prototype.writeDoubleLE=function(e,t,r){return Wg(this,e,t,!0,r)},mg.prototype.writeDoubleBE=function(e,t,r){return Wg(this,e,t,!1,r)},mg.prototype.copy=function(e,t,r,i){if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--n)e[n+t]=this[n+r];else if(o<1e3||!mg.TYPED_ARRAY_SUPPORT)for(n=0;n>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Xg(e){return function(e){var t,r,i,n,o,s;og||sg();var a=e.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[a-2]?2:"="===e[a-1]?1:0,s=new ng(3*a/4-o),i=o>0?a-4:a;var c=0;for(t=0,r=0;t>16&255,s[c++]=n>>8&255,s[c++]=255&n;return 2===o?(n=ig[e.charCodeAt(t)]<<2|ig[e.charCodeAt(t+1)]>>4,s[c++]=255&n):1===o&&(n=ig[e.charCodeAt(t)]<<10|ig[e.charCodeAt(t+1)]<<4|ig[e.charCodeAt(t+2)]>>2,s[c++]=n>>8&255,s[c++]=255&n),s}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Gg,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Qg(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function $g(e){return null!=e&&(!!e._isBuffer||Zg(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Zg(e.slice(0,0))}(e))}function Zg(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function e_(){throw new Error("setTimeout has not been defined")}function t_(){throw new Error("clearTimeout has not been defined")}var r_=e_,i_=t_;function n_(e){if(r_===setTimeout)return setTimeout(e,0);if((r_===e_||!r_)&&setTimeout)return r_=setTimeout,setTimeout(e,0);try{return r_(e,0)}catch(Aw){try{return r_.call(null,e,0)}catch(Aw){return r_.call(this,e,0)}}}"function"==typeof tg.setTimeout&&(r_=setTimeout),"function"==typeof tg.clearTimeout&&(i_=clearTimeout);var o_,s_=[],a_=!1,c_=-1;function u_(){a_&&o_&&(a_=!1,o_.length?s_=o_.concat(s_):c_=-1,s_.length&&d_())}function d_(){if(!a_){var e=n_(u_);a_=!0;for(var t=s_.length;t;){for(o_=s_,s_=[];++c_>2,a=(3&t)<<4|r>>4,c=1>6:64,u=2>4,r=(15&s)<<4|(a=o.indexOf(e.charAt(u++)))>>2,i=(3&a)<<6|(c=o.indexOf(e.charAt(u++))),h[d++]=t,64!==a&&(h[d++]=r),64!==c&&(h[d++]=i);return h}},{"./support":30,"./utils":32}],2:[function(e,t,r){var i=e("./external"),n=e("./stream/DataWorker"),o=e("./stream/Crc32Probe"),s=e("./stream/DataLengthProbe");function a(e,t,r,i,n){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=i,this.compressedContent=n}a.prototype={getContentWorker:function(){var e=new n(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new s("data_length")),t=this;return e.on("end",(function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),e},getCompressedWorker:function(){return new n(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,r){return e.pipe(new o).pipe(new s("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new s("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){var i=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(e){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},r.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){var i=e("./utils"),n=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,r,i){var o=n,s=i+r;e^=-1;for(var a=i;a>>8^o[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,r,i){var o=n,s=i+r;e^=-1;for(var a=i;a>>8^o[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(e,t,r){var i=null;i="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:i}},{lie:37}],7:[function(e,t,r){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=e("pako"),o=e("./utils"),s=e("./stream/GenericWorker"),a=i?"uint8array":"array";function c(e,t){s.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}r.magic="\b\0",o.inherits(c,s),c.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(o.transformTo(a,e.data),!1)},c.prototype.flush=function(){s.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},r.compressWorker=function(e){return new c("Deflate",e)},r.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,r){function i(e,t){var r,i="";for(r=0;r>>=8;return i}function n(e,t,r,n,s,d){var l,h,f=e.file,p=e.compression,m=d!==a.utf8encode,g=o.transformTo("string",d(f.name)),_=o.transformTo("string",a.utf8encode(f.name)),S=f.comment,v=o.transformTo("string",d(S)),y=o.transformTo("string",a.utf8encode(S)),I=_.length!==f.name.length,T=y.length!==S.length,R="",E="",b="",C=f.dir,A=f.date,w={crc32:0,compressedSize:0,uncompressedSize:0};t&&!r||(w.crc32=e.crc32,w.compressedSize=e.compressedSize,w.uncompressedSize=e.uncompressedSize);var k=0;t&&(k|=8),m||!I&&!T||(k|=2048);var O=0,P=0;C&&(O|=16),"UNIX"===s?(P=798,O|=function(e,t){var r=e;return e||(r=t?16893:33204),(65535&r)<<16}(f.unixPermissions,C)):(P=20,O|=function(e){return 63&(e||0)}(f.dosPermissions)),l=A.getUTCHours(),l<<=6,l|=A.getUTCMinutes(),l<<=5,l|=A.getUTCSeconds()/2,h=A.getUTCFullYear()-1980,h<<=4,h|=A.getUTCMonth()+1,h<<=5,h|=A.getUTCDate(),I&&(E=i(1,1)+i(c(g),4)+_,R+="up"+i(E.length,2)+E),T&&(b=i(1,1)+i(c(v),4)+y,R+="uc"+i(b.length,2)+b);var M="";return M+="\n\0",M+=i(k,2),M+=p.magic,M+=i(l,2),M+=i(h,2),M+=i(w.crc32,4),M+=i(w.compressedSize,4),M+=i(w.uncompressedSize,4),M+=i(g.length,2),M+=i(R.length,2),{fileRecord:u.LOCAL_FILE_HEADER+M+g+R,dirRecord:u.CENTRAL_FILE_HEADER+i(P,2)+M+i(v.length,2)+"\0\0\0\0"+i(O,4)+i(n,4)+g+R+v}}var o=e("../utils"),s=e("../stream/GenericWorker"),a=e("../utf8"),c=e("../crc32"),u=e("../signature");function d(e,t,r,i){s.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=i,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(d,s),d.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,s.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-i-1))/r:100}}))},d.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,r=n(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:function(e){return u.DATA_DESCRIPTOR+i(e.crc32,4)+i(e.compressedSize,4)+i(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)r=(r<<8)+this.byteAt(t);return this.index+=e,r},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(e){},lastIndexOfSignature:function(e){},readAndCheckSignature:function(e){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=n},{"../utils":32}],19:[function(e,t,r){var i=e("./Uint8ArrayReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,r){var i=e("./DataReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},n.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},n.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./DataReader":18}],21:[function(e,t,r){var i=e("./ArrayReader");function n(e){i.call(this,e)}e("../utils").inherits(n,i),n.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,r){var i=e("../utils"),n=e("../support"),o=e("./ArrayReader"),s=e("./StringReader"),a=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");t.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||n.uint8array?"nodebuffer"===t?new a(e):n.uint8array?new c(i.transformTo("uint8array",e)):new o(i.transformTo("array",e)):new s(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,r){r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,r){var i=e("./GenericWorker"),n=e("../utils");function o(e){i.call(this,"ConvertWorker to "+e),this.destType=e}n.inherits(o,i),o.prototype.processChunk=function(e){this.push({data:n.transformTo(this.destType,e.data),meta:e.meta})},t.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,r){var i=e("./GenericWorker"),n=e("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(o,i),o.prototype.processChunk=function(e){this.streamInfo.crc32=n(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,r){var i=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(o,n),o.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}n.prototype.processChunk.call(this,e)},t.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,r){var i=e("../utils"),n=e("./GenericWorker");function o(e){n.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then((function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()}),(function(e){t.error(e)}))}i.inherits(o,n),o.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,r){function i(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var r=0;r "+e:e}},t.exports=i},{}],29:[function(e,t,r){var i=e("../utils"),n=e("./ConvertWorker"),o=e("./GenericWorker"),s=e("../base64"),a=e("../support"),c=e("../external"),u=null;if(a.nodestream)try{u=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function d(e,t){return new c.Promise((function(r,n){var o=[],a=e._internalType,c=e._outputType,u=e._mimeType;e.on("data",(function(e,r){o.push(e),t&&t(r)})).on("error",(function(e){o=[],n(e)})).on("end",(function(){try{var e=function(e,t,r){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),r);case"base64":return s.encode(t);default:return i.transformTo(e,t)}}(c,function(e,t){var r,i=0,n=null,o=0;for(r=0;r>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t}(e)},r.utf8decode=function(e){return n.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,r,n,o,s=e.length,c=new Array(2*s);for(t=r=0;t>10&1023,c[r++]=56320|1023&n)}return c.length!==r&&(c.subarray?c=c.subarray(0,r):c.length=r),i.applyFromCharCode(c)}(e=i.transformTo(n.uint8array?"uint8array":"array",e))},i.inherits(u,s),u.prototype.processChunk=function(e){var t=i.transformTo(n.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var o=t;(t=new Uint8Array(o.length+this.leftOver.length)).set(this.leftOver,0),t.set(o,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var s=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0||0===r?t:r+a[e[r]]>t?r:t}(t),c=t;s!==t.length&&(n.uint8array?(c=t.subarray(0,s),this.leftOver=t.subarray(s,t.length)):(c=t.slice(0,s),this.leftOver=t.slice(s,t.length))),this.push({data:r.utf8decode(c),meta:e.meta})},u.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:r.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},r.Utf8DecodeWorker=u,i.inherits(d,s),d.prototype.processChunk=function(e){this.push({data:r.utf8encode(e.data),meta:e.meta})},r.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,r){var i=e("./support"),n=e("./base64"),o=e("./nodejsUtils"),s=e("./external");function a(e){return e}function c(e,t){for(var r=0;r>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(e){if(this.extraFields[1]){var t=i(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(e){var t,r,i,n=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t},r.buf2binstring=function(e){return c(e,e.length)},r.binstring2buf=function(e){for(var t=new i.Buf8(e.length),r=0,n=t.length;r>10&1023,u[i++]=56320|1023&n)}return c(u,i)},r.utf8border=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0||0===r?t:r+s[e[r]]>t?r:t}},{"./common":41}],43:[function(e,t,r){t.exports=function(e,t,r,i){for(var n=65535&e|0,o=e>>>16&65535|0,s=0;0!==r;){for(r-=s=2e3>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t,r,n){var o=i,s=n+r;e^=-1;for(var a=n;a>>8^o[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,r){var i,n=e("../utils/common"),o=e("./trees"),s=e("./adler32"),a=e("./crc32"),c=e("./messages"),u=0,d=4,l=0,h=-2,f=-1,p=4,m=2,g=8,_=9,S=286,v=30,y=19,I=2*S+1,T=15,R=3,E=258,b=E+R+1,C=42,A=113,w=1,k=2,O=3,P=4;function M(e,t){return e.msg=c[t],t}function D(e){return(e<<1)-(4e.avail_out&&(r=e.avail_out),0!==r&&(n.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function x(e,t){o._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,U(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function B(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function V(e,t){var r,i,n=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-b?e.strstart-(e.w_size-b):0,u=e.window,d=e.w_mask,l=e.prev,h=e.strstart+E,f=u[o+s-1],p=u[o+s];e.prev_length>=e.good_match&&(n>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(r=t)+s]===p&&u[r+s-1]===f&&u[r]===u[o]&&u[++r]===u[o+1]){o+=2,r++;do{}while(u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&oc&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Y(e){var t,r,i,o,c,u,d,l,h,f,p=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=p+(p-b)){for(n.arraySet(e.window,e.window,p,p,0),e.match_start-=p,e.strstart-=p,e.block_start-=p,t=r=e.hash_size;i=e.head[--t],e.head[t]=p<=i?i-p:0,--r;);for(t=r=p;i=e.prev[--t],e.prev[t]=p<=i?i-p:0,--r;);o+=p}if(0===e.strm.avail_in)break;if(u=e.strm,d=e.window,l=e.strstart+e.lookahead,f=void 0,(h=o)<(f=u.avail_in)&&(f=h),r=0===f?0:(u.avail_in-=f,n.arraySet(d,u.input,u.next_in,f,l),1===u.state.wrap?u.adler=s(u.adler,d,f,l):2===u.state.wrap&&(u.adler=a(u.adler,d,f,l)),u.next_in+=f,u.total_in+=f,f),e.lookahead+=r,e.lookahead+e.insert>=R)for(c=e.strstart-e.insert,e.ins_h=e.window[c],e.ins_h=(e.ins_h<=R&&(e.ins_h=(e.ins_h<=R)if(i=o._tr_tally(e,e.strstart-e.match_start,e.match_length-R),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=R){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=R&&(e.ins_h=(e.ins_h<=R&&e.match_length<=e.prev_length){for(n=e.strstart+e.lookahead-R,i=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-R),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Y(e),0===e.lookahead&&t===u)return w;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,x(e,!1),0===e.strm.avail_out))return w;if(e.strstart-e.block_start>=e.w_size-b&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):(e.strstart>e.block_start&&(x(e,!1),e.strm.avail_out),w)})),new H(4,4,8,4,j),new H(4,5,16,8,j),new H(4,6,32,32,j),new H(4,4,16,16,F),new H(8,16,32,32,F),new H(8,16,128,128,F),new H(8,32,128,256,F),new H(32,128,258,1024,F),new H(32,258,258,4096,F)],r.deflateInit=function(e,t){return G(e,t,g,15,8,0)},r.deflateInit2=G,r.deflateReset=W,r.deflateResetKeep=z,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?h:(e.state.gzhead=t,l):h},r.deflate=function(e,t){var r,n,s,c;if(!e||!e.state||5>8&255),L(n,n.gzhead.time>>16&255),L(n,n.gzhead.time>>24&255),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(L(n,255&n.gzhead.extra.length),L(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=a(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(L(n,0),L(n,0),L(n,0),L(n,0),L(n,0),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,3),n.status=A);else{var f=g+(n.w_bits-8<<4)<<8;f|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(f|=32),f+=31-f%31,n.status=A,B(n,f),0!==n.strstart&&(B(n,e.adler>>>16),B(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(s=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending!==n.pending_buf_size));)L(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindexs&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),U(e),s=n.pending,n.pending===n.pending_buf_size)){c=1;break}c=n.gzindexs&&(e.adler=a(e.adler,n.pending_buf,n.pending-s,s)),0===c&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&U(e),n.pending+2<=n.pending_buf_size&&(L(n,255&e.adler),L(n,e.adler>>8&255),e.adler=0,n.status=A)):n.status=A),0!==n.pending){if(U(e),0===e.avail_out)return n.last_flush=-1,l}else if(0===e.avail_in&&D(t)<=D(r)&&t!==d)return M(e,-5);if(666===n.status&&0!==e.avail_in)return M(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==u&&666!==n.status){var p=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(Y(e),0===e.lookahead)){if(t===u)return w;break}if(e.match_length=0,r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):e.last_lit&&(x(e,!1),0===e.strm.avail_out)?w:k}(n,t):3===n.strategy?function(e,t){for(var r,i,n,s,a=e.window;;){if(e.lookahead<=E){if(Y(e),e.lookahead<=E&&t===u)return w;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=R&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=R?(r=o._tr_tally(e,1,e.match_length-R),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(x(e,!1),0===e.strm.avail_out))return w}return e.insert=0,t===d?(x(e,!0),0===e.strm.avail_out?O:P):e.last_lit&&(x(e,!1),0===e.strm.avail_out)?w:k}(n,t):i[n.level].func(n,t);if(p!==O&&p!==P||(n.status=666),p===w||p===O)return 0===e.avail_out&&(n.last_flush=-1),l;if(p===k&&(1===t?o._tr_align(n):5!==t&&(o._tr_stored_block(n,0,0,!1),3===t&&(N(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),U(e),0===e.avail_out))return n.last_flush=-1,l}return t!==d?l:n.wrap<=0?1:(2===n.wrap?(L(n,255&e.adler),L(n,e.adler>>8&255),L(n,e.adler>>16&255),L(n,e.adler>>24&255),L(n,255&e.total_in),L(n,e.total_in>>8&255),L(n,e.total_in>>16&255),L(n,e.total_in>>24&255)):(B(n,e.adler>>>16),B(n,65535&e.adler)),U(e),0=r.w_size&&(0===a&&(N(r.head),r.strstart=0,r.block_start=0,r.insert=0),f=new n.Buf8(r.w_size),n.arraySet(f,t,p-r.w_size,r.w_size,0),t=f,p=r.w_size),c=e.avail_in,u=e.next_in,d=e.input,e.avail_in=p,e.next_in=0,e.input=t,Y(r);r.lookahead>=R;){for(i=r.strstart,o=r.lookahead-(R-1);r.ins_h=(r.ins_h<>>=y=v>>>24,p-=y,0==(y=v>>>16&255))C[o++]=65535&v;else{if(!(16&y)){if(0==(64&y)){v=m[(65535&v)+(f&(1<>>=y,p-=y),p<15&&(f+=b[i++]<>>=y=v>>>24,p-=y,!(16&(y=v>>>16&255))){if(0==(64&y)){v=g[(65535&v)+(f&(1<>>=y,p-=y,(y=o-s)>3,f&=(1<<(p-=I<<3))-1,e.next_in=i,e.next_out=o,e.avail_in=i>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new i.Buf32(f),t.distcode=t.distdyn=new i.Buf32(p),t.sane=1,t.back=-1,d):l}function S(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):l}function v(e,t){var r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=s.wsize?(i.arraySet(s.window,t,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(o=s.wsize-s.wnext)&&(o=n),i.arraySet(s.window,t,r-n,o,s.wnext),(n-=o)?(i.arraySet(s.window,t,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=o(r.check,Y,2,0),I=y=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&y)<<8)+(y>>8))%31){e.msg="incorrect header check",r.mode=30;break}if(8!=(15&y)){e.msg="unknown compression method",r.mode=30;break}if(I-=4,U=8+(15&(y>>>=4)),0===r.wbits)r.wbits=U;else if(U>r.wbits){e.msg="invalid window size",r.mode=30;break}r.dmax=1<>8&1),512&r.flags&&(Y[0]=255&y,Y[1]=y>>>8&255,r.check=o(r.check,Y,2,0)),I=y=0,r.mode=3;case 3:for(;I<32;){if(0===S)break e;S--,y+=f[g++]<>>8&255,Y[2]=y>>>16&255,Y[3]=y>>>24&255,r.check=o(r.check,Y,4,0)),I=y=0,r.mode=4;case 4:for(;I<16;){if(0===S)break e;S--,y+=f[g++]<>8),512&r.flags&&(Y[0]=255&y,Y[1]=y>>>8&255,r.check=o(r.check,Y,2,0)),I=y=0,r.mode=5;case 5:if(1024&r.flags){for(;I<16;){if(0===S)break e;S--,y+=f[g++]<>>8&255,r.check=o(r.check,Y,2,0)),I=y=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(S<(C=r.length)&&(C=S),C&&(r.head&&(U=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),i.arraySet(r.head.extra,f,g,C,U)),512&r.flags&&(r.check=o(r.check,f,C,g)),S-=C,g+=C,r.length-=C),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===S)break e;for(C=0;U=f[g+C++],r.head&&U&&r.length<65536&&(r.head.name+=String.fromCharCode(U)),U&&C>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=12;break;case 10:for(;I<32;){if(0===S)break e;S--,y+=f[g++]<>>=7&I,I-=7&I,r.mode=27;break}for(;I<3;){if(0===S)break e;S--,y+=f[g++]<>>=1)){case 0:r.mode=14;break;case 1:if(E(r),r.mode=20,6!==t)break;y>>>=2,I-=2;break e;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=30}y>>>=2,I-=2;break;case 14:for(y>>>=7&I,I-=7&I;I<32;){if(0===S)break e;S--,y+=f[g++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&y,I=y=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(C=r.length){if(S>>=5,I-=5,r.ndist=1+(31&y),y>>>=5,I-=5,r.ncode=4+(15&y),y>>>=4,I-=4,286>>=3,I-=3}for(;r.have<19;)r.lens[j[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,L={bits:r.lenbits},x=a(0,r.lens,0,19,r.lencode,0,r.work,L),r.lenbits=L.bits,x){e.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=k,I-=k,r.lens[r.have++]=P;else{if(16===P){for(B=k+2;I>>=k,I-=k,0===r.have){e.msg="invalid bit length repeat",r.mode=30;break}U=r.lens[r.have-1],C=3+(3&y),y>>>=2,I-=2}else if(17===P){for(B=k+3;I>>=k)),y>>>=3,I-=3}else{for(B=k+7;I>>=k)),y>>>=7,I-=7}if(r.have+C>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=30;break}for(;C--;)r.lens[r.have++]=U}}if(30===r.mode)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,L={bits:r.lenbits},x=a(c,r.lens,0,r.nlen,r.lencode,0,r.work,L),r.lenbits=L.bits,x){e.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,L={bits:r.distbits},x=a(u,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,L),r.distbits=L.bits,x){e.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(6<=S&&258<=v){e.next_out=_,e.avail_out=v,e.next_in=g,e.avail_in=S,r.hold=y,r.bits=I,s(e,R),_=e.next_out,p=e.output,v=e.avail_out,g=e.next_in,f=e.input,S=e.avail_in,y=r.hold,I=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;O=(V=r.lencode[y&(1<>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>M)])>>>16&255,P=65535&V,!(M+(k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=M,I-=M,r.back+=M}if(y>>>=k,I-=k,r.back+=k,r.length=P,0===O){r.mode=26;break}if(32&O){r.back=-1,r.mode=12;break}if(64&O){e.msg="invalid literal/length code",r.mode=30;break}r.extra=15&O,r.mode=22;case 22:if(r.extra){for(B=r.extra;I>>=r.extra,I-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;O=(V=r.distcode[y&(1<>>16&255,P=65535&V,!((k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>M)])>>>16&255,P=65535&V,!(M+(k=V>>>24)<=I);){if(0===S)break e;S--,y+=f[g++]<>>=M,I-=M,r.back+=M}if(y>>>=k,I-=k,r.back+=k,64&O){e.msg="invalid distance code",r.mode=30;break}r.offset=P,r.extra=15&O,r.mode=24;case 24:if(r.extra){for(B=r.extra;I>>=r.extra,I-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===v)break e;if(C=R-v,r.offset>C){if((C=r.offset-C)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=30;break}A=C>r.wnext?(C-=r.wnext,r.wsize-C):r.wnext-C,C>r.length&&(C=r.length),w=r.window}else w=p,A=_-r.offset,C=r.length;for(vS?(y=L[B+l[E]],D[N+l[E]]):(y=96,0),f=1<>k)+(p-=f)]=v<<24|y<<16|I|0,0!==p;);for(f=1<>=1;if(0!==f?(M&=f-1,M+=f):M=0,E++,0==--U[R]){if(R===C)break;R=t[r+l[E]]}if(A>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function B(e,t,r){e.bi_valid>m-r?(e.bi_buf|=t<>m-e.bi_valid,e.bi_valid+=r-m):(e.bi_buf|=t<>>=1,r<<=1,0<--t;);return r>>>1}function j(e,t,r){var i,n,o=new Array(p+1),s=0;for(i=1;i<=p;i++)o[i]=s=s+r[i-1]<<1;for(n=0;n<=t;n++){var a=e[2*n+1];0!==a&&(e[2*n]=Y(o[a]++,a))}}function F(e){var t;for(t=0;t>1;1<=r;r--)z(e,o,r);for(n=c;r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],z(e,o,1),i=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=i,o[2*n]=o[2*r]+o[2*i],e.depth[n]=(e.depth[r]>=e.depth[i]?e.depth[r]:e.depth[i])+1,o[2*r+1]=o[2*i+1]=n,e.heap[1]=n++,z(e,o,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,i,n,o,s,a,c=t.dyn_tree,u=t.max_code,d=t.stat_desc.static_tree,l=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,_=0;for(o=0;o<=p;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r>=7;i>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return n;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return o;for(t=32;t>>3,(a=e.static_len+3+7>>>3)<=s&&(s=a)):s=a=r+5,r+4<=s&&-1!==t?Q(e,t,r,i):4===e.strategy||a===s?(B(e,2+(i?1:0),3),W(e,b,C)):(B(e,4+(i?1:0),3),function(e,t,r,i){var n;for(B(e,t-257,5),B(e,r-1,5),B(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(w[r]+u+1)]++,e.dyn_dtree[2*x(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){B(e,2,3),V(e,_,b),function(e){16===e.bi_valid?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,r){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,r){(function(e){!function(e,t){if(!e.setImmediate){var r,i,n,o,s=1,a={},c=!1,u=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,r="[object process]"==={}.toString.call(e.process)?function(e){!function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r>1,d=23===t?E_(2,-24)-E_(2,-77):0,l=e<0||0===e&&1/e<0?1:0,h=0;for((e=R_(e))!=e||e===1/0?(n=e!=e?1:0,i=c):(i=b_(C_(e)/A_),e*(o=E_(2,-i))<1&&(i--,o*=2),(e+=i+u>=1?d/o:d*E_(2,1-u))*o>=2&&(i++,o/=2),i+u>=c?(n=0,i=c):i+u>=1?(n=(e*o-1)*E_(2,t),i+=u):(n=e*E_(2,u-1)*E_(2,t),i=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(i=i<0;)s[h++]=255&i,i/=256,a-=8;return s[--h]|=128*l,s},unpack:function(e,t){var r,i=e.length,n=8*i-t-1,o=(1<>1,a=n-7,c=i-1,u=e[c--],d=127&u;for(u>>=7;a>0;)d=256*d+e[c--],a-=8;for(r=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)r=256*r+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return r?NaN:u?-1/0:1/0;r+=E_(2,t),d-=s}return(u?-1:1)*r*E_(2,d-t)}},k_=Ue,O_=si,P_=li,M_=function(e){for(var t=k_(this),r=P_(t),i=arguments.length,n=O_(i>1?arguments[1]:void 0,r),o=i>2?arguments[2]:void 0,s=void 0===o?r:O_(o,r);s>n;)t[n++]=e;return t},D_=lt,N_=At,U_=T,x_=si,L_=li,B_=function(e,t,r){var i=D_(t);i in e?N_.f(e,i,U_(0,r)):e[i]=r},V_=Array,Y_=Math.max,j_=function(e,t,r){for(var i=L_(e),n=x_(t,i),o=x_(void 0===r?i:r,i),s=V_(Y_(o-n,0)),a=0;n>8&255]},OS=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},PS=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},MS=function(e){return CS(e,23,4)},DS=function(e){return CS(e,52,8)},NS=function(e,t){nS(e[pS],t,{get:function(){return dS(this)[t]}})},US=function(e,t,r,i){var n=Z_(r),o=dS(e);if(n+t>o.byteLength)throw RS(mS);var s=dS(o.buffer).bytes,a=n+o.byteOffset,c=sS(s,a,a+t);return i?c:bS(c)},xS=function(e,t,r,i,n,o){var s=Z_(r),a=dS(e);if(s+t>a.byteLength)throw RS(mS);for(var c=dS(a.buffer).bytes,u=s+a.byteOffset,d=i(+n),l=0;lYS;)(BS=VS[YS++])in _S||G_(_S,BS,gS[BS]);SS.constructor=_S}rS&&tS(yS)!==IS&&rS(yS,IS);var jS=new vS(new _S(2)),FS=H_(yS.setInt8);jS.setInt8(0,2147483648),jS.setInt8(1,2147483649),!jS.getInt8(0)&&jS.getInt8(1)||J_(yS,{setInt8:function(e,t){FS(this,e,t<<24>>24)},setUint8:function(e,t){FS(this,e,t<<24>>24)}},{unsafe:!0})}else _S=function(e){X_(this,SS);var t=Z_(e);lS(this,{bytes:ES(TS(t),0),byteLength:t}),K_||(this.byteLength=t)},SS=_S[pS],vS=function(e,t,r){X_(this,yS),X_(e,SS);var i=dS(e).byteLength,n=Q_(t);if(n<0||n>i)throw RS("Wrong offset");if(n+(r=void 0===r?i-n:$_(r))>i)throw RS("Wrong length");lS(this,{buffer:e,byteLength:r,byteOffset:n}),K_||(this.buffer=e,this.byteLength=r,this.byteOffset=n)},yS=vS[pS],K_&&(NS(_S,"byteLength"),NS(vS,"buffer"),NS(vS,"byteLength"),NS(vS,"byteOffset")),J_(yS,{getInt8:function(e){return US(this,1,e)[0]<<24>>24},getUint8:function(e){return US(this,1,e)[0]},getInt16:function(e){var t=US(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=US(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return PS(US(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return PS(US(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return AS(US(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return AS(US(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){xS(this,1,e,wS,t)},setUint8:function(e,t){xS(this,1,e,wS,t)},setInt16:function(e,t){xS(this,2,e,kS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){xS(this,2,e,kS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){xS(this,4,e,OS,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){xS(this,4,e,OS,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){xS(this,4,e,MS,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){xS(this,8,e,DS,t,arguments.length>2?arguments[2]:void 0)}});aS(_S,hS),aS(vS,fS);var HS={ArrayBuffer:_S,DataView:vS},KS=en,zS=w,WS=d,GS=Mt,JS=si,qS=ui,XS=to,QS=HS.ArrayBuffer,$S=HS.DataView,ZS=$S.prototype,ev=zS(QS.prototype.slice),tv=zS(ZS.getUint8),rv=zS(ZS.setUint8);KS({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:WS((function(){return!new QS(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(ev&&void 0===t)return ev(GS(this),e);for(var r=GS(this).byteLength,i=JS(e,r),n=JS(void 0===t?r:t,r),o=new(XS(this,QS))(qS(n-i)),s=new $S(this),a=new $S(o),c=0;i1?arguments[1]:void 0,l=void 0!==d,h=dy(c);if(h&&!ly(h))for(s=(o=uy(c,h)).next,c=[];!(n=oy(s,o)).done;)c.push(n.value);for(l&&u>2&&(d=ny(d,arguments[2])),r=cy(c),i=new(hy(a))(r),t=0;r>t;t++)i[t]=l?d(c[t],t):c[t];return i},Ly=Vh.forEach,By=Sn,Vy=At,Yy=u,jy=fm,Fy=Dr.get,Hy=Dr.set,Ky=Dr.enforce,zy=Vy.f,Wy=Yy.f,Gy=Math.round,Jy=py.RangeError,qy=vy.ArrayBuffer,Xy=qy.prototype,Qy=vy.DataView,$y=Sy.NATIVE_ARRAY_BUFFER_VIEWS,Zy=Sy.TYPED_ARRAY_TAG,eI=Sy.TypedArray,tI=Sy.TypedArrayPrototype,rI=Sy.aTypedArrayConstructor,iI=Sy.isTypedArray,nI="BYTES_PER_ELEMENT",oI="Wrong length",sI=function(e,t){rI(e);for(var r=0,i=t.length,n=new e(i);i>r;)n[r]=t[r++];return n},aI=function(e,t){zy(e,t,{get:function(){return Fy(this)[t]}})},cI=function(e){var t;return Dy(Xy,e)||"ArrayBuffer"==(t=ky(e))||"SharedArrayBuffer"==t},uI=function(e,t){return iI(e)&&!Py(t)&&t in e&&Ry(+t)&&t>=0},dI=function(e,t){return t=Ay(t),uI(e,t)?Iy(2,e[t]):Wy(e,t)},lI=function(e,t,r){return t=Ay(t),!(uI(e,t)&&Oy(r)&&wy(r,"value"))||wy(r,"get")||wy(r,"set")||r.configurable||wy(r,"writable")&&!r.writable||wy(r,"enumerable")&&!r.enumerable?zy(e,t,r):(e[t]=r.value,e)};gy?($y||(Yy.f=dI,Vy.f=lI,aI(tI,"buffer"),aI(tI,"byteOffset"),aI(tI,"byteLength"),aI(tI,"length")),fy({target:"Object",stat:!0,forced:!$y},{getOwnPropertyDescriptor:dI,defineProperty:lI}),sv.exports=function(e,t,r){var i=e.match(/\d+$/)[0]/8,n=e+(r?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=py[n],c=a,u=c&&c.prototype,d={},l=function(e,t){zy(e,t,{get:function(){return function(e,t){var r=Fy(e);return r.view[o](t*i+r.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=Fy(e);r&&(n=(n=Gy(n))<0?0:n>255?255:255&n),o.view[s](t*i+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};$y?_y&&(c=t((function(e,t,r,n){return yy(e,u),jy(Oy(t)?cI(t)?void 0!==n?new a(t,Cy(r,i),n):void 0!==r?new a(t,Cy(r,i)):new a(t):iI(t)?sI(c,t):my(xy,c,t):new a(by(t)),e,c)})),Ny&&Ny(c,eI),Ly(Uy(a),(function(e){e in c||Ty(c,e,a[e])})),c.prototype=u):(c=t((function(e,t,r,n){yy(e,u);var o,s,a,d=0,h=0;if(Oy(t)){if(!cI(t))return iI(t)?sI(c,t):my(xy,c,t);o=t,h=Cy(r,i);var f=t.byteLength;if(void 0===n){if(f%i)throw Jy(oI);if((s=f-h)<0)throw Jy(oI)}else if((s=Ey(n)*i)+h>f)throw Jy(oI);a=s/i}else a=by(t),o=new qy(s=a*i);for(Hy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Qy(o)});d1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),SI((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var TI=c,RI=m,EI=Fv,bI=li,CI=iy,AI=Ue,wI=d,kI=TI.RangeError,OI=TI.Int8Array,PI=OI&&OI.prototype,MI=PI&&PI.set,DI=EI.aTypedArray,NI=EI.exportTypedArrayMethod,UI=!wI((function(){var e=new Uint8ClampedArray(2);return RI(MI,e,{length:1,0:3},1),3!==e[1]})),xI=UI&&EI.NATIVE_ARRAY_BUFFER_VIEWS&&wI((function(){var e=new OI(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));NI("set",(function(e){DI(this);var t=CI(arguments.length>1?arguments[1]:void 0,1),r=AI(e);if(UI)return RI(MI,this,r,t);var i=this.length,n=bI(r),o=0;if(n+t>i)throw kI("Wrong length");for(;o0;)e[i]=e[--i];i!==o++&&(e[i]=r)}return e},jI=function(e,t,r,i){for(var n=t.length,o=r.length,s=0,a=0;s0&&1/r<0?1:-1:t>r}}(e))}),!aT||sT);var cT,uT={exports:{}},dT={exports:{}},lT=s(Object.freeze({__proto__:null,default:{}}));function hT(){return cT||(cT=1,function(e,t){var r;e.exports=(r=r||function(e,t){var r;if("undefined"!=typeof window&&window.crypto&&(r=window.crypto),"undefined"!=typeof self&&self.crypto&&(r=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(r=globalThis.crypto),!r&&"undefined"!=typeof window&&window.msCrypto&&(r=window.msCrypto),!r&&void 0!==o&&o.crypto&&(r=o.crypto),!r)try{r=lT}catch(g){}var i=function(){if(r){if("function"==typeof r.getRandomValues)try{return r.getRandomValues(new Uint32Array(1))[0]}catch(g){}if("function"==typeof r.randomBytes)try{return r.randomBytes(4).readInt32LE()}catch(g){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),s={},a=s.lib={},c=a.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},u=a.WordArray=c.extend({init:function(e,r){e=this.words=e||[],this.sigBytes=r!=t?r:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[i+o>>>2]|=s<<24-(i+o)%4*8}else for(var a=0;a>>2]=r[a>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r>>2]>>>24-n%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new u.init(r,t/2)}},h=d.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new u.init(r,t)}},f=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(Aw){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,i=this._data,n=i.words,o=i.sigBytes,s=this.blockSize,a=o/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,d=e.min(4*c,o);if(c){for(var l=0;l>>2]|=e[n]<<24-n%4*8;t.call(this,i,r)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray)}(_T)),_T.exports}var vT,yT={exports:{}};function IT(){return vT||(vT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib.WordArray,i=e.enc;function n(e){return e<<8&4278255360|e>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n>>2]>>>16-n%4*8&65535;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var r=e.length,i=[],n=0;n>>1]|=e.charCodeAt(n)<<16-n%2*16;return t.create(i,2*r)}},i.Utf16LE={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],o=0;o>>2]>>>16-o%4*8&65535);i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var r=e.length,i=[],o=0;o>>1]|=n(e.charCodeAt(o)<<16-o%2*16);return t.create(i,2*r)}}}(),r.enc.Utf16)}(yT)),yT.exports}var TT,RT={exports:{}};function ET(){return TT||(TT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib.WordArray;function i(e,r,i){for(var n=[],o=0,s=0;s>>6-s%4*2;n[o>>>2]|=a<<24-o%4*8,o++}return t.create(n,o)}e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,i=this._map;e.clamp();for(var n=[],o=0;o>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;n.length%4;)n.push(c);return n.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var o=0;o>>6-s%4*2;n[o>>>2]|=a<<24-o%4*8,o++}return t.create(n,o)}e.enc.Base64url={stringify:function(e,t=!0){var r=e.words,i=e.sigBytes,n=t?this._safe_map:this._map;e.clamp();for(var o=[],s=0;s>>2]>>>24-s%4*8&255)<<16|(r[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|r[s+2>>>2]>>>24-(s+2)%4*8&255,c=0;c<4&&s+.75*c>>6*(3-c)&63));var u=n.charAt(64);if(u)for(;o.length%4;)o.push(u);return o.join("")},parse:function(e,t=!0){var r=e.length,n=t?this._safe_map:this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var s=0;s>>24)|4278255360&(n<<24|n>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],f=e[t+2],p=e[t+3],m=e[t+4],g=e[t+5],_=e[t+6],S=e[t+7],v=e[t+8],y=e[t+9],I=e[t+10],T=e[t+11],R=e[t+12],E=e[t+13],b=e[t+14],C=e[t+15],A=o[0],w=o[1],k=o[2],O=o[3];A=u(A,w,k,O,s,7,a[0]),O=u(O,A,w,k,c,12,a[1]),k=u(k,O,A,w,f,17,a[2]),w=u(w,k,O,A,p,22,a[3]),A=u(A,w,k,O,m,7,a[4]),O=u(O,A,w,k,g,12,a[5]),k=u(k,O,A,w,_,17,a[6]),w=u(w,k,O,A,S,22,a[7]),A=u(A,w,k,O,v,7,a[8]),O=u(O,A,w,k,y,12,a[9]),k=u(k,O,A,w,I,17,a[10]),w=u(w,k,O,A,T,22,a[11]),A=u(A,w,k,O,R,7,a[12]),O=u(O,A,w,k,E,12,a[13]),k=u(k,O,A,w,b,17,a[14]),A=d(A,w=u(w,k,O,A,C,22,a[15]),k,O,c,5,a[16]),O=d(O,A,w,k,_,9,a[17]),k=d(k,O,A,w,T,14,a[18]),w=d(w,k,O,A,s,20,a[19]),A=d(A,w,k,O,g,5,a[20]),O=d(O,A,w,k,I,9,a[21]),k=d(k,O,A,w,C,14,a[22]),w=d(w,k,O,A,m,20,a[23]),A=d(A,w,k,O,y,5,a[24]),O=d(O,A,w,k,b,9,a[25]),k=d(k,O,A,w,p,14,a[26]),w=d(w,k,O,A,v,20,a[27]),A=d(A,w,k,O,E,5,a[28]),O=d(O,A,w,k,f,9,a[29]),k=d(k,O,A,w,S,14,a[30]),A=l(A,w=d(w,k,O,A,R,20,a[31]),k,O,g,4,a[32]),O=l(O,A,w,k,v,11,a[33]),k=l(k,O,A,w,T,16,a[34]),w=l(w,k,O,A,b,23,a[35]),A=l(A,w,k,O,c,4,a[36]),O=l(O,A,w,k,m,11,a[37]),k=l(k,O,A,w,S,16,a[38]),w=l(w,k,O,A,I,23,a[39]),A=l(A,w,k,O,E,4,a[40]),O=l(O,A,w,k,s,11,a[41]),k=l(k,O,A,w,p,16,a[42]),w=l(w,k,O,A,_,23,a[43]),A=l(A,w,k,O,y,4,a[44]),O=l(O,A,w,k,R,11,a[45]),k=l(k,O,A,w,C,16,a[46]),A=h(A,w=l(w,k,O,A,f,23,a[47]),k,O,s,6,a[48]),O=h(O,A,w,k,S,10,a[49]),k=h(k,O,A,w,b,15,a[50]),w=h(w,k,O,A,g,21,a[51]),A=h(A,w,k,O,R,6,a[52]),O=h(O,A,w,k,p,10,a[53]),k=h(k,O,A,w,I,15,a[54]),w=h(w,k,O,A,c,21,a[55]),A=h(A,w,k,O,v,6,a[56]),O=h(O,A,w,k,C,10,a[57]),k=h(k,O,A,w,_,15,a[58]),w=h(w,k,O,A,E,21,a[59]),A=h(A,w,k,O,m,6,a[60]),O=h(O,A,w,k,T,10,a[61]),k=h(k,O,A,w,f,15,a[62]),w=h(w,k,O,A,y,21,a[63]),o[0]=o[0]+A|0,o[1]=o[1]+w|0,o[2]=o[2]+k|0,o[3]=o[3]+O|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;r[n>>>5]|=128<<24-n%32;var o=e.floor(i/4294967296),s=i;r[15+(n+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(n+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(r.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var d=c[u];c[u]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,i,n,o,s){var a=e+(t&r|~t&i)+n+s;return(a<>>32-o)+t}function d(e,t,r,i,n,o,s){var a=e+(t&i|r&~i)+n+s;return(a<>>32-o)+t}function l(e,t,r,i,n,o,s){var a=e+(t^r^i)+n+s;return(a<>>32-o)+t}function h(e,t,r,i,n,o,s){var a=e+(r^(t|~i))+n+s;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),r.MD5)}(kT)),kT.exports}var PT,MT={exports:{}};function DT(){return PT||(PT=1,function(e,t){var r;e.exports=(r=hT(),function(){var e=r,t=e.lib,i=t.WordArray,n=t.Hasher,o=e.algo,s=[],a=o.SHA1=n.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],a=r[3],c=r[4],u=0;u<80;u++){if(u<16)s[u]=0|e[t+u];else{var d=s[u-3]^s[u-8]^s[u-14]^s[u-16];s[u]=d<<1|d>>>31}var l=(i<<5|i>>>27)+c+s[u];l+=u<20?1518500249+(n&o|~n&a):u<40?1859775393+(n^o^a):u<60?(n&o|n&a|o&a)-1894007588:(n^o^a)-899497514,c=a,a=o,o=n<<30|n>>>2,n=i,i=l}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(i+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=n._createHelper(a),e.HmacSHA1=n._createHmacHelper(a)}(),r.SHA1)}(MT)),MT.exports}var NT,UT={exports:{}};function xT(){return NT||(NT=1,function(e,t){var r;e.exports=(r=hT(),function(e){var t=r,i=t.lib,n=i.WordArray,o=i.Hasher,s=t.algo,a=[],c=[];!function(){function t(t){for(var r=e.sqrt(t),i=2;i<=r;i++)if(!(t%i))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var i=2,n=0;n<64;)t(i)&&(n<8&&(a[n]=r(e.pow(i,.5))),c[n]=r(e.pow(i,1/3)),n++),i++}();var u=[],d=s.SHA256=o.extend({_doReset:function(){this._hash=new n.init(a.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],s=r[3],a=r[4],d=r[5],l=r[6],h=r[7],f=0;f<64;f++){if(f<16)u[f]=0|e[t+f];else{var p=u[f-15],m=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,g=u[f-2],_=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;u[f]=m+u[f-7]+_+u[f-16]}var S=i&n^i&o^n&o,v=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),y=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&l)+c[f]+u[f];h=l,l=d,d=a,a=s+y|0,s=o,o=n,n=i,i=y+(v+S)|0}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0,r[5]=r[5]+d|0,r[6]=r[6]+l|0,r[7]=r[7]+h|0},_doFinalize:function(){var t=this._data,r=t.words,i=8*this._nDataBytes,n=8*t.sigBytes;return r[n>>>5]|=128<<24-n%32,r[14+(n+64>>>9<<4)]=e.floor(i/4294967296),r[15+(n+64>>>9<<4)]=i,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(d),t.HmacSHA256=o._createHmacHelper(d)}(Math),r.SHA256)}(UT)),UT.exports}var LT,BT={exports:{}};var VT,YT={exports:{}};function jT(){return VT||(VT=1,function(e,t){var r;e.exports=(r=hT(),mT(),function(){var e=r,t=e.lib.Hasher,i=e.x64,n=i.Word,o=i.WordArray,s=e.algo;function a(){return n.create.apply(n,arguments)}var c=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],u=[];!function(){for(var e=0;e<80;e++)u[e]=a()}();var d=s.SHA512=t.extend({_doReset:function(){this._hash=new o.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],s=r[3],a=r[4],d=r[5],l=r[6],h=r[7],f=i.high,p=i.low,m=n.high,g=n.low,_=o.high,S=o.low,v=s.high,y=s.low,I=a.high,T=a.low,R=d.high,E=d.low,b=l.high,C=l.low,A=h.high,w=h.low,k=f,O=p,P=m,M=g,D=_,N=S,U=v,x=y,L=I,B=T,V=R,Y=E,j=b,F=C,H=A,K=w,z=0;z<80;z++){var W,G,J=u[z];if(z<16)G=J.high=0|e[t+2*z],W=J.low=0|e[t+2*z+1];else{var q=u[z-15],X=q.high,Q=q.low,$=(X>>>1|Q<<31)^(X>>>8|Q<<24)^X>>>7,Z=(Q>>>1|X<<31)^(Q>>>8|X<<24)^(Q>>>7|X<<25),ee=u[z-2],te=ee.high,re=ee.low,ie=(te>>>19|re<<13)^(te<<3|re>>>29)^te>>>6,ne=(re>>>19|te<<13)^(re<<3|te>>>29)^(re>>>6|te<<26),oe=u[z-7],se=oe.high,ae=oe.low,ce=u[z-16],ue=ce.high,de=ce.low;G=(G=(G=$+se+((W=Z+ae)>>>0>>0?1:0))+ie+((W+=ne)>>>0>>0?1:0))+ue+((W+=de)>>>0>>0?1:0),J.high=G,J.low=W}var le,he=L&V^~L&j,fe=B&Y^~B&F,pe=k&P^k&D^P&D,me=O&M^O&N^M&N,ge=(k>>>28|O<<4)^(k<<30|O>>>2)^(k<<25|O>>>7),_e=(O>>>28|k<<4)^(O<<30|k>>>2)^(O<<25|k>>>7),Se=(L>>>14|B<<18)^(L>>>18|B<<14)^(L<<23|B>>>9),ve=(B>>>14|L<<18)^(B>>>18|L<<14)^(B<<23|L>>>9),ye=c[z],Ie=ye.high,Te=ye.low,Re=H+Se+((le=K+ve)>>>0>>0?1:0),Ee=_e+me;H=j,K=F,j=V,F=Y,V=L,Y=B,L=U+(Re=(Re=(Re=Re+he+((le+=fe)>>>0>>0?1:0))+Ie+((le+=Te)>>>0>>0?1:0))+G+((le+=W)>>>0>>0?1:0))+((B=x+le|0)>>>0>>0?1:0)|0,U=D,x=N,D=P,N=M,P=k,M=O,k=Re+(ge+pe+(Ee>>>0<_e>>>0?1:0))+((O=le+Ee|0)>>>0>>0?1:0)|0}p=i.low=p+O,i.high=f+k+(p>>>0>>0?1:0),g=n.low=g+M,n.high=m+P+(g>>>0>>0?1:0),S=o.low=S+N,o.high=_+D+(S>>>0>>0?1:0),y=s.low=y+x,s.high=v+U+(y>>>0>>0?1:0),T=a.low=T+B,a.high=I+L+(T>>>0>>0?1:0),E=d.low=E+Y,d.high=R+V+(E>>>0>>0?1:0),C=l.low=C+F,l.high=b+j+(C>>>0>>0?1:0),w=h.low=w+K,h.high=A+H+(w>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[30+(i+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(i+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=t.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32});e.SHA512=t._createHelper(d),e.HmacSHA512=t._createHmacHelper(d)}(),r.SHA512)}(YT)),YT.exports}var FT,HT={exports:{}};var KT,zT={exports:{}};function WT(){return KT||(KT=1,function(e,t){var r;e.exports=(r=hT(),mT(),function(e){var t=r,i=t.lib,n=i.WordArray,o=i.Hasher,s=t.x64.Word,a=t.algo,c=[],u=[],d=[];!function(){for(var e=1,t=0,r=0;r<24;r++){c[e+5*t]=(r+1)*(r+2)/2%64;var i=(2*e+3*t)%5;e=t%5,t=i}for(e=0;e<5;e++)for(t=0;t<5;t++)u[e+5*t]=t+(2*e+3*t)%5*5;for(var n=1,o=0;o<24;o++){for(var a=0,l=0,h=0;h<7;h++){if(1&n){var f=(1<>>24)|4278255360&(o<<24|o>>>8),s=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),(w=r[n]).high^=s,w.low^=o}for(var a=0;a<24;a++){for(var h=0;h<5;h++){for(var f=0,p=0,m=0;m<5;m++)f^=(w=r[h+5*m]).high,p^=w.low;var g=l[h];g.high=f,g.low=p}for(h=0;h<5;h++){var _=l[(h+4)%5],S=l[(h+1)%5],v=S.high,y=S.low;for(f=_.high^(v<<1|y>>>31),p=_.low^(y<<1|v>>>31),m=0;m<5;m++)(w=r[h+5*m]).high^=f,w.low^=p}for(var I=1;I<25;I++){var T=(w=r[I]).high,R=w.low,E=c[I];E<32?(f=T<>>32-E,p=R<>>32-E):(f=R<>>64-E,p=T<>>64-E);var b=l[u[I]];b.high=f,b.low=p}var C=l[0],A=r[0];for(C.high=A.high,C.low=A.low,h=0;h<5;h++)for(m=0;m<5;m++){var w=r[I=h+5*m],k=l[I],O=l[(h+1)%5+5*m],P=l[(h+2)%5+5*m];w.high=k.high^~O.high&P.high,w.low=k.low^~O.low&P.low}w=r[0];var M=d[a];w.high^=M.high,w.low^=M.low}},_doFinalize:function(){var t=this._data,r=t.words;this._nDataBytes;var i=8*t.sigBytes,o=32*this.blockSize;r[i>>>5]|=1<<24-i%32,r[(e.ceil((i+1)/o)*o>>>5)-1]|=128,t.sigBytes=4*r.length,this._process();for(var s=this._state,a=this.cfg.outputLength/8,c=a/8,u=[],d=0;d>>24)|4278255360&(h<<24|h>>>8),f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),u.push(f),u.push(h)}return new n.init(u,a)},clone:function(){for(var e=o.clone.call(this),t=e._state=this._state.slice(0),r=0;r<25;r++)t[r]=t[r].clone();return e}});t.SHA3=o._createHelper(h),t.HmacSHA3=o._createHmacHelper(h)}(Math),r.SHA3)}(zT)),zT.exports}var GT,JT={exports:{}};var qT,XT={exports:{}};function QT(){return qT||(qT=1,function(e,t){var r;e.exports=(r=hT(),void function(){var e=r,t=e.lib.Base,i=e.enc.Utf8;e.algo.HMAC=t.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=i.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var o=this._oKey=t.clone(),s=this._iKey=t.clone(),a=o.words,c=s.words,u=0;u>>2];e.sigBytes-=t}};i.BlockCipher=d.extend({cfg:d.cfg.extend({mode:f,padding:p}),reset:function(){var e;d.reset.call(this);var t=this.cfg,r=t.iv,i=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=i.createEncryptor:(e=i.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,r&&r.words):(this._mode=e.call(i,this,r&&r.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var m=i.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),g=(t.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;return(r?o.create([1398893684,1701076831]).concat(r).concat(t):t).toString(c)},parse:function(e){var t,r=c.parse(e),i=r.words;return 1398893684==i[0]&&1701076831==i[1]&&(t=o.create(i.slice(2,4)),i.splice(0,4),r.sigBytes-=16),m.create({ciphertext:r,salt:t})}},_=i.SerializableCipher=n.extend({cfg:n.extend({format:g}),encrypt:function(e,t,r,i){i=this.cfg.extend(i);var n=e.createEncryptor(r,i),o=n.finalize(t),s=n.cfg;return m.create({ciphertext:o,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:i.format})},decrypt:function(e,t,r,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),e.createDecryptor(r,i).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),S=(t.kdf={}).OpenSSL={execute:function(e,t,r,i){i||(i=o.random(8));var n=u.create({keySize:t+r}).compute(e,i),s=o.create(n.words.slice(t),4*r);return n.sigBytes=4*t,m.create({key:n,iv:s,salt:i})}},v=i.PasswordBasedCipher=_.extend({cfg:_.cfg.extend({kdf:S}),encrypt:function(e,t,r,i){var n=(i=this.cfg.extend(i)).kdf.execute(r,e.keySize,e.ivSize);i.iv=n.iv;var o=_.encrypt.call(this,e,t,n.key,i);return o.mixIn(n),o},decrypt:function(e,t,r,i){i=this.cfg.extend(i),t=this._parse(t,i.format);var n=i.kdf.execute(r,e.keySize,e.ivSize,t.salt);return i.iv=n.iv,_.decrypt.call(this,e,t,n.key,i)}})}()))}(nR)),nR.exports}var sR,aR={exports:{}};function cR(){return sR||(sR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(e,t,r,i){var n,o=this._iv;o?(n=o.slice(0),this._iv=void 0):n=this._prevBlock,i.encryptBlock(n,0);for(var s=0;s>>24)|4278255360&(n<<24|n>>>8)}var o,s,f,y,I,T,R,E,b,C,A,w=this._hash.words,k=l.words,O=h.words,P=a.words,M=c.words,D=u.words,N=d.words;for(T=o=w[0],R=s=w[1],E=f=w[2],b=y=w[3],C=I=w[4],r=0;r<80;r+=1)A=o+e[t+P[r]]|0,A+=r<16?p(s,f,y)+k[0]:r<32?m(s,f,y)+k[1]:r<48?g(s,f,y)+k[2]:r<64?_(s,f,y)+k[3]:S(s,f,y)+k[4],A=(A=v(A|=0,D[r]))+I|0,o=I,I=y,y=v(f,10),f=s,s=A,A=T+e[t+M[r]]|0,A+=r<16?S(R,E,b)+O[0]:r<32?_(R,E,b)+O[1]:r<48?g(R,E,b)+O[2]:r<64?m(R,E,b)+O[3]:p(R,E,b)+O[4],A=(A=v(A|=0,N[r]))+C|0,T=C,C=b,b=v(E,10),E=R,R=A;A=w[1]+f+b|0,w[1]=w[2]+y+C|0,w[2]=w[3]+I+T|0,w[3]=w[4]+o+R|0,w[4]=w[0]+s+E|0,w[0]=A},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process();for(var n=this._hash,o=n.words,s=0;s<5;s++){var a=o[s];o[s]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}return n},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function p(e,t,r){return e^t^r}function m(e,t,r){return e&t|~e&r}function g(e,t,r){return(e|~t)^r}function _(e,t,r){return e&r|t&~r}function S(e,t,r){return e^(t|~r)}function v(e,t){return e<>>32-t}t.RIPEMD160=o._createHelper(f),t.HmacRIPEMD160=o._createHmacHelper(f)}(),r.RIPEMD160)}(JT)),QT(),$T||($T=1,function(e,t){var r;e.exports=(r=hT(),DT(),QT(),function(){var e=r,t=e.lib,i=t.Base,n=t.WordArray,o=e.algo,s=o.SHA1,a=o.HMAC,c=o.PBKDF2=i.extend({cfg:i.extend({keySize:4,hasher:s,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,i=a.create(r.hasher,e),o=n.create(),s=n.create([1]),c=o.words,u=s.words,d=r.keySize,l=r.iterations;c.length>>2]|=n<<24-o%4*8,e.sigBytes+=n},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},r.pad.Ansix923)}(IR)),TR||(TR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.Iso10126={pad:function(e,t){var i=4*t,n=i-e.sigBytes%i;e.concat(r.lib.WordArray.random(n-1)).concat(r.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},r.pad.Iso10126)}(RR)),ER||(ER=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.Iso97971={pad:function(e,t){e.concat(r.lib.WordArray.create([2147483648],1)),r.pad.ZeroPadding.pad(e,t)},unpad:function(e){r.pad.ZeroPadding.unpad(e),e.sigBytes--}},r.pad.Iso97971)}(bR)),CR||(CR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.ZeroPadding={pad:function(e,t){var r=4*t;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){var t=e.words,r=e.sigBytes-1;for(r=e.sigBytes-1;r>=0;r--)if(t[r>>>2]>>>24-r%4*8&255){e.sigBytes=r+1;break}}},r.pad.ZeroPadding)}(AR)),wR||(wR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.NoPadding={pad:function(){},unpad:function(){}},r.pad.NoPadding)}(kR)),OR||(OR=1,function(e,t){var r;e.exports=(r=hT(),oR(),function(e){var t=r,i=t.lib.CipherParams,n=t.enc.Hex;t.format.Hex={stringify:function(e){return e.ciphertext.toString(n)},parse:function(e){var t=n.parse(e);return i.create({ciphertext:t})}}}(),r.format.Hex)}(PR)),MR||(MR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.BlockCipher,i=e.algo,n=[],o=[],s=[],a=[],c=[],u=[],d=[],l=[],h=[],f=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,i=0;for(t=0;t<256;t++){var p=i^i<<1^i<<2^i<<3^i<<4;p=p>>>8^255&p^99,n[r]=p,o[p]=r;var m=e[r],g=e[m],_=e[g],S=257*e[p]^16843008*p;s[r]=S<<24|S>>>8,a[r]=S<<16|S>>>16,c[r]=S<<8|S>>>24,u[r]=S,S=16843009*_^65537*g^257*m^16843008*r,d[p]=S<<24|S>>>8,l[p]=S<<16|S>>>16,h[p]=S<<8|S>>>24,f[p]=S,r?(r=m^e[e[e[_^m]]],i^=e[e[i]]):r=i=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],m=i.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,i=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],s=0;s6&&s%r==4&&(u=n[u>>>24]<<24|n[u>>>16&255]<<16|n[u>>>8&255]<<8|n[255&u]):(u=n[(u=u<<8|u>>>24)>>>24]<<24|n[u>>>16&255]<<16|n[u>>>8&255]<<8|n[255&u],u^=p[s/r|0]<<24),o[s]=o[s-r]^u);for(var a=this._invKeySchedule=[],c=0;c>>24]]^l[n[u>>>16&255]]^h[n[u>>>8&255]]^f[n[255&u]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,c,u,n)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,d,l,h,f,o),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,i,n,o,s,a){for(var c=this._nRounds,u=e[t]^r[0],d=e[t+1]^r[1],l=e[t+2]^r[2],h=e[t+3]^r[3],f=4,p=1;p>>24]^n[d>>>16&255]^o[l>>>8&255]^s[255&h]^r[f++],g=i[d>>>24]^n[l>>>16&255]^o[h>>>8&255]^s[255&u]^r[f++],_=i[l>>>24]^n[h>>>16&255]^o[u>>>8&255]^s[255&d]^r[f++],S=i[h>>>24]^n[u>>>16&255]^o[d>>>8&255]^s[255&l]^r[f++];u=m,d=g,l=_,h=S}m=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^r[f++],g=(a[d>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&u])^r[f++],_=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[f++],S=(a[h>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&l])^r[f++],e[t]=m,e[t+1]=g,e[t+2]=_,e[t+3]=S},keySize:8});e.AES=t._createHelper(m)}(),r.AES)}(DR)),xR(),LR||(LR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=i.RC4=t.extend({_doReset:function(){for(var e=this._key,t=e.words,r=e.sigBytes,i=this._S=[],n=0;n<256;n++)i[n]=n;n=0;for(var o=0;n<256;n++){var s=n%r,a=t[s>>>2]>>>24-s%4*8&255;o=(o+i[n]+a)%256;var c=i[n];i[n]=i[o],i[o]=c}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=o.call(this)},keySize:8,ivSize:0});function o(){for(var e=this._S,t=this._i,r=this._j,i=0,n=0;n<4;n++){r=(r+e[t=(t+1)%256])%256;var o=e[t];e[t]=e[r],e[r]=o,i|=e[(e[t]+e[r])%256]<<24-8*n}return this._i=t,this._j=r,i}e.RC4=t._createHelper(n);var s=i.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)o.call(this)}});e.RC4Drop=t._createHelper(s)}(),r.RC4)}(BR)),VR||(VR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=[],o=[],s=[],a=i.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,r=0;r<4;r++)e[r]=16711935&(e[r]<<8|e[r]>>>24)|4278255360&(e[r]<<24|e[r]>>>8);var i=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],n=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,r=0;r<4;r++)c.call(this);for(r=0;r<8;r++)n[r]^=i[r+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),l=u>>>16|4294901760&d,h=d<<16|65535&u;for(n[0]^=u,n[1]^=l,n[2]^=d,n[3]^=h,n[4]^=u,n[5]^=l,n[6]^=d,n[7]^=h,r=0;r<4;r++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),n[0]=r[0]^r[5]>>>16^r[3]<<16,n[1]=r[2]^r[7]>>>16^r[5]<<16,n[2]=r[4]^r[1]>>>16^r[7]<<16,n[3]=r[6]^r[3]>>>16^r[1]<<16;for(var i=0;i<4;i++)n[i]=16711935&(n[i]<<8|n[i]>>>24)|4278255360&(n[i]<<24|n[i]>>>8),e[t+i]^=n[i]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var i=e[r]+t[r],n=65535&i,a=i>>>16,c=((n*n>>>17)+n*a>>>15)+a*a,u=((4294901760&i)*i|0)+((65535&i)*i|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.Rabbit=t._createHelper(a)}(),r.Rabbit)}(YR)),jR||(jR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=[],o=[],s=[],a=i.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var n=0;n<4;n++)c.call(this);for(n=0;n<8;n++)i[n]^=r[n+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),l=u>>>16|4294901760&d,h=d<<16|65535&u;for(i[0]^=u,i[1]^=l,i[2]^=d,i[3]^=h,i[4]^=u,i[5]^=l,i[6]^=d,i[7]^=h,n=0;n<4;n++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),n[0]=r[0]^r[5]>>>16^r[3]<<16,n[1]=r[2]^r[7]>>>16^r[5]<<16,n[2]=r[4]^r[1]>>>16^r[7]<<16,n[3]=r[6]^r[3]>>>16^r[1]<<16;for(var i=0;i<4;i++)n[i]=16711935&(n[i]<<8|n[i]>>>24)|4278255360&(n[i]<<24|n[i]>>>8),e[t+i]^=n[i]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var i=e[r]+t[r],n=65535&i,a=i>>>16,c=((n*n>>>17)+n*a>>>15)+a*a,u=((4294901760&i)*i|0)+((65535&i)*i|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.RabbitLegacy=t._createHelper(a)}(),r.RabbitLegacy)}(FR)),r)}(uT);const HR=window.crypto||window.webkitCrypto||window.mozCrypto||window.oCrypto||window.msCrypto,KR={Mac:/(mac os x)\s+([\w_]+)/,Windows:/(windows nt)\s+([\w.]+)/,Ios:/(i(?:pad|phone|pod)).*cpu(?: i(?:pad|phone|pod))? os (\d+(?:[.|_]\d+)+)/,Android:/(android)\s+([\d.]+)/,Ipad:/(ipad).*os\s([\d_]+)/,Iphone:/(iphone\sos)\s([\d_]+)/,Linux:/(x11;)\s(linux)\s(x86_64|mips64|aarch64)/,ChromiumOS:/(x11;)\s(cros)\s(x86_64|mips64|aarch64)\s([\w.]+)\)/},zR=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","-","_"];let WR,GR;const JR="CommonUtil";class qR{constructor(){this.uuidCount=0,this.timeDiff=0,this.platform=(()=>{const e=navigator.userAgent.toLowerCase(),t=e.match(/(micromessenger)\/([\w.()]+)/i),r=t?"-WeChat".concat(t[2]):"";for(const i in KR)if(Object.prototype.hasOwnProperty.call(KR,i)){const t=e.match(KR[i]);if(t)return GR="Ios"===i?t[2].replace(/_/g,"."):"Linux"===i?t[3]:"ChromiumOS"===i?t[4]:t[2],WR=["Ios","Ipad","Iphone"].includes(i)?"IOS":i,i+GR+r}return"unknown"})(),this.userAgent=(()=>{const e=navigator.userAgent.match(/(chrome|safari|firefox|microMessenger)\/(\d+(\.\d+)*)/i);return e?"".concat(e[1],"-").concat(e[2]):""})()}async sleep(e){return new Promise((t=>{const r=setTimeout((()=>{clearTimeout(r),t()}),e)}))}getDeviceID(){return this.deviceID||(this.deviceID=this.generateStandardUuid()),this.deviceID}generateStandardUuid(){let e;if(HR&&(e="function"==typeof HR.randomUUID?HR.randomUUID():""),!e){let t=(new Date).getTime();window.performance&&"function"==typeof window.performance.now&&(t+=performance.now()),e="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/[x]/g,(()=>{const e=(t+16*this.getRandom())%16|0;return t=Math.floor(t/16),e.toString(16)}))}return e}static getRandomArray(e){const t=new Uint8Array(e);return HR&&HR.getRandomValues(t),t}getRandom(){return qR.getRandomArray(1)[0]/256}getRandomUint32(){const e=qR.getRandomArray(4);return new DataView(e.buffer).getUint32(0)}generateUuid(e){let t="";const r=qR.getRandomArray(33),i=e?22:33;for(let s=0;s>=6;let o=this.uuidCount.toString(16);for(let s=3-o.length;s>0;s--)o="0"+o;return this.uuidCount>4094?this.uuidCount=0:this.uuidCount++,"".concat(t).concat(n).concat(o)}generateRandomId(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:62,r="";const i=qR.getRandomArray(e);for(let n=0;n=0?p:-p,g=(p<=0?"+":"-")+(m<10?"0".concat(m):"".concat(m))+":00";return{year:"".concat(t),month:"".concat(i),day:"".concat(o),hour:"".concat(a),min:"".concat(u),sec:"".concat(l),millsec:f,zoneOff:g}}adjustTimeByOffset(e){return e-this.timeDiff}convertString2Timestamp(e){return new Date(e).getTime()}generateStreamId(){return"2xxxxxxx-8xxx-xxxx-yxxx-xxxx".replace(/[xy]/g,(e=>{const t=16*this.getRandom()|0;return("x"==e?t:3&t|8).toString(16)}))}isWKWebview(){return/I.*-WeChat.*/gi.test(this.platform)}isAppleDevice(){return/^(Mac|I).*/gi.test(this.platform)}isSafari(){return this.isAppleDevice()&&/Safari/i.test(this.getUserAgent())}isMobileDevice(){return!/^(Mac|Windows).*/gi.test(this.platform)}isMobileWeChatBrowser(){return this.isMobileDevice()&&/.*MicroMessenger.*/gi.test(navigator.userAgent)}isSupportConstraints(e){var t;return!!(null===(t=navigator.mediaDevices)||void 0===t?void 0:t.getSupportedConstraints())[e]}async calculateSha256(e){return new Promise((t=>{const r=new FileReader;r.onloadend=e=>{if(e.target.readyState==FileReader.DONE){const r=uT.exports.lib.WordArray.create(e.target.result),i=uT.exports.SHA256(r).toString();t(i)}},r.readAsArrayBuffer(e)}))}getValue(e,t){return e||t}shieldIpAddress(e){return e?e.replace(/\b(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\b/g,"$1.*.*.$2"):null}shieldUrlParameters(e){if(!e)return e;const t=e.match(/([^?|=|&]+)=([^&]+)/g);return t&&t.forEach((t=>{const r=/([^=]*)=(.*)/g.exec(t);e=e.replace(t,"".concat(r[1],"=").concat(this.secretString(r[2])))})),e}shieldNickname(e){if(!e)return e;let t="";for(let r=0;r{r.includes(t)&&(r=r.replace(e.pattern,e.newString))}));const n=XR.getCurrentTime(),o=["".concat(n.year,"-").concat(n.month,"-").concat(n.day," ").concat(n.hour,":").concat(n.min,":").concat(n.sec,".").concat(n.millsec),e];Object.entries($R($R({},i),{},{tag:t,msg:r})).forEach((e=>{let[t,r]=e;"string"==typeof r&&o.push("[".concat(t,": ").concat(r,"]"))}));const s=o.join(" ");for(this.logBuffer.push(s);this.logBuffer.length>=this.logBufferSize;)this.logBuffer.shift();const a=["".concat(n.year,"-").concat(n.month,"-").concat(n.day," ").concat(n.hour,":").concat(n.min,":").concat(n.sec,".").concat(n.millsec)];eg.indexOf(iE.logLevel)>=eg.indexOf(e)&&console[e](a+" [HRTC] "+"[".concat(e,"] [").concat(t,"] [").concat(r,"]"))}clearLogs(){this.logBuffer=[]}setLogBufferSize(e){this.logBufferSize=e}getLogBufferSize(){return this.logBufferSize}getLogBuffer(){return this.logBuffer}}class iE{static getLogger(e){const t=e||ZR;if(!eE.has(t)){const e=new rE;return eE.set(t,e),e}return eE.get(t)}static setAllLogLevel(e){if(!(eg.indexOf(e)>=0))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"log level is invalid");iE.logLevel=e}static addPrivacyString(e){if(!e)return;if(tE.has(e))return;const t=XR.secretString(e);if(!t)return;const r=e.replaceAll(/([\^|\$|\\|\.|\*|\+|\?|\(|\)|\[|\]|\{|\}|\|])/g,"\\$1"),i={pattern:new RegExp("\\b"+r+"\\b","g"),newString:t};tE.set(e,i)}static async getLogFile(e,t){const r=e.logger,i=XR.getCurrentTime(),n="".concat(i.year,"-").concat(i.month,"-").concat(i.day,"T").concat(i.hour,":").concat(i.min,":").concat(i.sec).concat(i.zoneOff),o="".concat(i.year,"-").concat(i.month,"-").concat(i.day,"T").concat(i.hour,".").concat(i.min,".").concat(i.sec).concat(i.zoneOff.replace(":",".")),s=iE.getLogger(),a=r.getLogBuffer(),c=s.getLogBuffer();if(0===a.length&&0===c.length)return null;const u=e.getInfo(),d="".concat(u.userName,"_").concat(u.userId,"##").concat(u.domain,"##").concat(u.appId,"##").concat(o),l=XR.getDeviceID(),h=encodeURIComponent("".concat(t,"##").concat(l,"##").concat(u.appId,"##").concat(n)),f=new m_,p=f.folder("".concat(u.userName,"_").concat(u.userId,"##").concat(u.roomId,"##").concat(u.domain,"##").concat(u.appId));p.file("".concat(d,".log"),"".concat(a.join("\n"))),p.file("hrtc##".concat(n,".log"),"".concat(c.join("\n")));const m=await f.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:9}});return{sha256:await XR.calculateSha256(m),length:m.size,content:m,urlFileNameEncode:h}}}i(iE,"logLevel",eg[3]);var nE=en,oE=vs,sE=d,aE=J,cE=H,uE=to,dE=Hc,lE=Xr,hE=oE&&oE.prototype;if(nE({target:"Promise",proto:!0,real:!0,forced:!!oE&&sE((function(){hE.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=uE(this,aE("Promise")),r=cE(e);return this.then(r?function(r){return dE(t,e()).then((function(){return r}))}:e,r?function(r){return dE(t,e()).then((function(){throw r}))}:e)}}),cE(oE)){var fE=aE("Promise").prototype.finally;hE.finally!==fE&&lE(hE,"finally",fE,{unsafe:!0})}var pE=Se,mE=Ue,gE=L,_E=li,SE=TypeError,vE=function(e){return function(t,r,i,n){pE(r);var o=mE(t),s=gE(o),a=_E(o),c=e?a-1:0,u=e?-1:1;if(i<2)for(;;){if(c in s){n=s[c],c+=u;break}if(c+=u,e?c<0:a<=c)throw SE("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=u)c in s&&(n=r(n,s[c],c,o));return n}},yE={left:vE(!1),right:vE(!0)}.left,IE=ie,TE=tn;en({target:"Array",proto:!0,forced:!jh("reduce")||!TE&&IE>79&&IE<83},{reduce:function(e){var t=arguments.length;return yE(this,e,t,t>1?arguments[1]:void 0)}});var RE=m,EE=Se,bE=Mt,CE=function(){for(var e=bE(this),t=EE(e.add),r=0,i=arguments.length;r1?arguments[1]:void 0);return!BE(r,(function(e,r){if(!i(e,e,t))return r()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var VE=J,YE=m,jE=Se,FE=Mt,HE=lo,KE=to,zE=NE,WE=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{filter:function(e){var t=FE(this),r=zE(t),i=HE(e,arguments.length>1?arguments[1]:void 0),n=new(KE(t,VE("Set"))),o=jE(n.add);return WE(r,(function(e){i(e,e,t)&&YE(o,n,e)}),{IS_ITERATOR:!0}),n}});var GE=Mt,JE=lo,qE=NE,XE=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{find:function(e){var t=GE(this),r=qE(t),i=JE(e,arguments.length>1?arguments[1]:void 0);return XE(r,(function(e,r){if(i(e,e,t))return r(e)}),{IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var QE=J,$E=m,ZE=Se,eb=Mt,tb=to,rb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{intersection:function(e){var t=eb(this),r=new(tb(t,QE("Set"))),i=ZE(t.has),n=ZE(r.add);return rb(e,(function(e){$E(i,t,e)&&$E(n,r,e)})),r}});var ib=m,nb=Se,ob=Mt,sb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isDisjointFrom:function(e){var t=ob(this),r=nb(t.has);return!sb(e,(function(e,i){if(!0===ib(r,t,e))return i()}),{INTERRUPTED:!0}).stopped}});var ab=J,cb=m,ub=Se,db=H,lb=Mt,hb=qa,fb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isSubsetOf:function(e){var t=hb(this),r=lb(e),i=r.has;return db(i)||(r=new(ab("Set"))(e),i=ub(r.has)),!fb(t,(function(e,t){if(!1===cb(i,r,e))return t()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var pb=m,mb=Se,gb=Mt,_b=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isSupersetOf:function(e){var t=gb(this),r=mb(t.has);return!_b(e,(function(e,i){if(!1===pb(r,t,e))return i()}),{INTERRUPTED:!0}).stopped}});var Sb=en,vb=Mt,yb=$c,Ib=NE,Tb=hc,Rb=w([].join),Eb=[].push;Sb({target:"Set",proto:!0,real:!0,forced:!0},{join:function(e){var t=vb(this),r=Ib(t),i=void 0===e?",":yb(e),n=[];return Tb(r,Eb,{that:n,IS_ITERATOR:!0}),Rb(n,i)}});var bb=J,Cb=lo,Ab=m,wb=Se,kb=Mt,Ob=to,Pb=NE,Mb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{map:function(e){var t=kb(this),r=Pb(t),i=Cb(e,arguments.length>1?arguments[1]:void 0),n=new(Ob(t,bb("Set"))),o=wb(n.add);return Mb(r,(function(e){Ab(o,n,i(e,e,t))}),{IS_ITERATOR:!0}),n}});var Db=Se,Nb=Mt,Ub=NE,xb=hc,Lb=TypeError;en({target:"Set",proto:!0,real:!0,forced:!0},{reduce:function(e){var t=Nb(this),r=Ub(t),i=arguments.length<2,n=i?void 0:arguments[1];if(Db(e),xb(r,(function(r){i?(i=!1,n=r):n=e(n,r,r,t)}),{IS_ITERATOR:!0}),i)throw Lb("Reduce of empty set with no initial value");return n}});var Bb=Mt,Vb=lo,Yb=NE,jb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{some:function(e){var t=Bb(this),r=Yb(t),i=Vb(e,arguments.length>1?arguments[1]:void 0);return jb(r,(function(e,r){if(i(e,e,t))return r()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var Fb=J,Hb=m,Kb=Se,zb=Mt,Wb=to,Gb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{symmetricDifference:function(e){var t=zb(this),r=new(Wb(t,Fb("Set")))(t),i=Kb(r.delete),n=Kb(r.add);return Gb(e,(function(e){Hb(i,r,e)||Hb(n,r,e)})),r}});var Jb=J,qb=Se,Xb=Mt,Qb=to,$b=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{union:function(e){var t=Xb(this),r=new(Qb(t,Jb("Set")))(t);return $b(e,qb(r.add),{that:r}),r}});const Zb="player-state-change",eC="screen-sharing-stopped",tC="audio-mixing-finished",rC="audio-mixing-played",iC="player-state-trace",nC=["camera-capture"],oC={CameraCapture:nC[0]},sC={low:{sampleRate:16e3,channelCount:1,bitrate:24e3},standard:{sampleRate:48e3,channelCount:1,bitrate:4e4},high:{sampleRate:48e3,channelCount:1,bitrate:128e3}},aC=["low","standard","high"],cC={"90p_1":{width:160,height:90,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"90p_2":{width:120,height:90,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"120p_1":{width:160,height:120,frameRate:15,minBitrate:64e3,maxBitrate:12e4},"120p_2":{width:120,height:120,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"180p_1":{width:320,height:180,frameRate:15,minBitrate:8e4,maxBitrate:32e4},"180p_2":{width:240,height:180,frameRate:15,minBitrate:8e4,maxBitrate:17e4},"180p_3":{width:180,height:180,frameRate:15,minBitrate:64e3,maxBitrate:13e4},"240p_1":{width:320,height:240,frameRate:15,minBitrate:1e5,maxBitrate:4e5},"240p_2":{width:240,height:240,frameRate:15,minBitrate:8e4,maxBitrate:32e4},"270p_1":{width:480,height:270,frameRate:15,minBitrate:16e4,maxBitrate:6e5},"300p_1":{width:400,height:300,frameRate:15,minBitrate:2e5,maxBitrate:5e5},"360p_1":{width:640,height:360,frameRate:15,minBitrate:2e5,maxBitrate:8e5},"360p_2":{width:480,height:360,frameRate:15,minBitrate:2e5,maxBitrate:7e5},"360p_3":{width:360,height:360,frameRate:15,minBitrate:15e4,maxBitrate:6e5},"450p_1":{width:800,height:450,frameRate:15,minBitrate:3e5,maxBitrate:95e4},"480p_1":{width:640,height:480,frameRate:15,minBitrate:25e4,maxBitrate:9e5},"480p_2":{width:480,height:480,frameRate:15,minBitrate:2e5,maxBitrate:8e5},"540p_1":{width:960,height:540,frameRate:15,minBitrate:4e5,maxBitrate:1e6},"630p_1":{width:1120,height:630,frameRate:15,minBitrate:45e4,maxBitrate:115e4},"720p_1":{width:1280,height:720,frameRate:15,minBitrate:5e5,maxBitrate:15e5},"720p_2":{width:960,height:720,frameRate:15,minBitrate:45e4,maxBitrate:11e5},"1080p_1":{width:1920,height:1080,frameRate:15,minBitrate:6e5,maxBitrate:2e6},"1080p_2":{width:1440,height:1080,frameRate:15,minBitrate:55e4,maxBitrate:17e5}},uC=["90p_1","90p_2","120p_1","120p_2","180p_1","180p_2","180p_3","240p_1","240p_2","270p_1","300p_1","360p_1","360p_2","360p_3","450p_1","480p_1","480p_2","540p_1","630p_1","720p_1","720p_2","1080p_1","1080p_2"],dC={"720p":{width:1280,height:720,frameRate:15,bitrate:12e5},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e6}},lC=["720p","1080p"],hC="inbound-rtp-audio",fC="inbound-rtp-video",pC="outbound-rtp-audio",mC="outbound-rtp-video",gC="remote-inbound-rtp-audio",_C="remote-inbound-rtp-video";let SC=function(e){return e[e.IDLE=0]="IDLE",e[e.INIT=1]="INIT",e[e.PLAY=2]="PLAY",e[e.PAUSE=3]="PAUSE",e}({});const vC=["IDLE","DISCONNECTED","CONNECTING","RECONNECTING","CONNECTED"];let yC=function(e){return e[e.IDLE=0]="IDLE",e[e.DISCONNECTED=1]="DISCONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.RECONNECTING=3]="RECONNECTING",e[e.CONNECTED=4]="CONNECTED",e}({}),IC=function(e){return e[e.MediaStatusAvailable=1]="MediaStatusAvailable",e[e.MediaStatusUnavailable=2]="MediaStatusUnavailable",e}({}),TC=function(e){return e[e.BackgroundMusic=1]="BackgroundMusic",e[e.Audio=2]="Audio",e[e.Video=3]="Video",e[e.Aux=4]="Aux",e}({}),RC=function(e){return e[e.MediaOffline=0]="MediaOffline",e[e.MediaMuted=1]="MediaMuted",e[e.MediaUnmuted=2]="MediaUnmuted",e}({});const EC=new Set(["TOP_AUDIO"]);let bC=function(e){return e.configNotify="NOTIFY_CONFIG",e.watchStreamNotify="WATCH_STREAM_NOTIFY",e.disconnectNotify="DISCONNECT_NOTIFY",e.pushStreamNotify="PUSH_STREAM_NOTIFY",e.reconnectNotify="RECONNECT_NOTIFY",e.stopPushStreamNotify="STOP_PUSH_STREAM_NOTIFY",e.changeStreamStatusNotify="CHANGE_STREAM_STATUS_NOTIFY",e.appDataChangeNotify="APP_DATA_NOTIFY",e.top3AudioVolumeNotify="TOP_AUDIO",e.statusChangeNotify="NOTIFY_STATUS",e.publishStatusNotify="PUBLISH_STATUS_NOTIFY",e.uploadLogNotify="UPLOAD_LOG_NOTIFY",e.roomStreamStatusNotify="ROOM_STREAM_STATUS_NOTIFY",e}({}),CC=function(e){return e.main="main",e.middle1="middle1",e.middle2="middle2",e.middle3="middle3",e.middle4="middle4",e.slides="slides",e.desktop="desktop",e}({});async function AC(){return new Promise(((e,t)=>{navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices||t(new qc(Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES)),navigator.mediaDevices.enumerateDevices().then((r=>{r&&0!==r.length?e(r):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES))})).catch((e=>{t(e)}))}))}const wC="0",kC=-1e3;let OC=function(e){return e[e.Idle=0]="Idle",e[e.Joining=1]="Joining",e[e.Joined=2]="Joined",e[e.Leaving=3]="Leaving",e[e.Rejoining=4]="Rejoining",e}({}),PC=function(e){return e[e.DEFAULT_BANDWIDTH_4M=4096e3]="DEFAULT_BANDWIDTH_4M",e[e.MIN_BAND_WIDTH=3072]="MIN_BAND_WIDTH",e[e.MAX_BAND_WIDTH=51200]="MAX_BAND_WIDTH",e}({}),MC=function(e){return e[e.HRTC_LEAVE_REASON_USER_LEAVE_ROOM=0]="HRTC_LEAVE_REASON_USER_LEAVE_ROOM",e[e.HRTC_LEAVE_REASON_SERVER_ERROR=1]="HRTC_LEAVE_REASON_SERVER_ERROR",e[e.HRTC_LEAVE_REASON_BREAKDOWN=2]="HRTC_LEAVE_REASON_BREAKDOWN",e[e.HRTC_LEAVE_REASON_SERVICE_UNREACHABLE=3]="HRTC_LEAVE_REASON_SERVICE_UNREACHABLE",e[e.HRTC_LEAVE_REASON_INTERNAL_ERROR=4]="HRTC_LEAVE_REASON_INTERNAL_ERROR",e[e.HRTC_LEAVE_REASON_KICKED_OFF=5]="HRTC_LEAVE_REASON_KICKED_OFF",e[e.HRTC_LEAVE_REASON_SIGNATURE_EXPIRED=6]="HRTC_LEAVE_REASON_SIGNATURE_EXPIRED",e[e.HRTC_LEAVE_REASON_RECONNECT_FAILED=7]="HRTC_LEAVE_REASON_RECONNECT_FAILED",e[e.HRTC_LEAVE_REASON_NETWORK_TEST=8]="HRTC_LEAVE_REASON_NETWORK_TEST",e[e.HRTC_LEAVE_REASON_USER_REMOVED=9]="HRTC_LEAVE_REASON_USER_REMOVED",e[e.HRTC_LEAVE_REASON_ROOM_DISMISSED=10]="HRTC_LEAVE_REASON_ROOM_DISMISSED",e}({}),DC=function(e){return e[e.ON=1]="ON",e[e.OFF=2]="OFF",e}({}),NC=function(e){return e[e.portNormal=1]="portNormal",e[e.portReduce=2]="portReduce",e}({});const UC={Error:"Error",StreamAdded:"stream-added",StreamRemoved:"stream-removed",StreamUpdated:"stream-updated",StreamSubscribed:"stream-subscribed",ClientBanned:"client-banned",NetworkQuality:"network-quality",ConnectionStateChanged:"connection-state-changed",PeerJoin:"peer-join",PeerLeave:"peer-leave",MuteAudio:"mute-audio",UnmuteAudio:"unmute-audio",MuteVideo:"mute-video",UnmuteVideo:"unmute-video",LogUploaded:"log-upload-result",SignatureExpired:"signature-expired",CameraChanged:"camera-changed",RecordingDeviceChanged:"recording-device-changed",PlaybackDeviceChanged:"playback-device-changed",StreamInterrupted:"stream-interrupted",StreamRecovered:"stream-recovered",VolumeIndicator:"volume-indicator",UserNameChanged:"remote-user-name-changed",BatchSubscribeFailed:"batch-subscribe-failed",LiveStreamingUpdated:"live-streaming-updated",RtcStats:"rtc-stats",CmdMsgReceived:"cmd-msg-received",CmdChannelEstablished:"cmd-channel-established",CmdChannelDisconnect:"cmd-channel-disconnect",MediaConnectionStateChanged:"media-connection-state-changed",TransportProtocolChanged:"transport-protocol-changed",TransportStats:"transport-stats",RoomStreamStatus:"room-stream-status"};let xC=function(e){return e[e.NON_ENCRYPTION=0]="NON_ENCRYPTION",e[e.ENCRYPTION_FRAME_SDK=1]="ENCRYPTION_FRAME_SDK",e[e.ENCRYPTION_FRAME_APP=2]="ENCRYPTION_FRAME_APP",e[e.ENCRYPTION_E2E_WITHOUT_MEDIA=3]="ENCRYPTION_E2E_WITHOUT_MEDIA",e}({}),LC=function(e){return e.Connected="CONNECTED",e.Reconnecting="RECONNECTING",e.DisConnected="DISCONNECTED",e}({}),BC=function(e){return e.WEBSOCKET="WebSocket",e.DATA_CHANNEL="DataChannel",e}({}),VC=function(e){return e[e.ARRAY_BUFFER=0]="ARRAY_BUFFER",e[e.STRING=1]="STRING",e}({}),YC=function(e){return e[e.PAUSE=0]="PAUSE",e[e.NORMAL=1]="NORMAL",e}({}),jC=function(e){return e[e.NET_OR_SERVERIP_ERROR=1]="NET_OR_SERVERIP_ERROR",e[e.ROOM_NOT_AVAILABLE=2]="ROOM_NOT_AVAILABLE",e[e.SERVER_ERROR=3]="SERVER_ERROR",e[e.SERVER_NO_RESPONSE=4]="SERVER_NO_RESPONSE",e[e.AUTHENTICATION_FAILED=5]="AUTHENTICATION_FAILED",e[e.RETRY_AUTHENTICATION=6]="RETRY_AUTHENTICATION",e[e.SYNCHRONIZE_FAILED=7]="SYNCHRONIZE_FAILED",e[e.URL_ERROR=8]="URL_ERROR",e[e.TERMINAL_ERROR=9]="TERMINAL_ERROR",e}({}),FC=function(e){return e[e.LEAVE_ROOM_SUCCESS=0]="LEAVE_ROOM_SUCCESS",e[e.LEAVE_ROOM_ERROR=1]="LEAVE_ROOM_ERROR",e}({}),HC=function(e){return e[e.ACTION_START=0]="ACTION_START",e[e.ACTION_STOP=1]="ACTION_STOP",e}({}),KC=function(e){return e[e.RESULT_SUCCESS=0]="RESULT_SUCCESS",e[e.RESULT_ERROR=1]="RESULT_ERROR",e}({}),zC=function(e){return e[e.OUTPUT_AUDIO=0]="OUTPUT_AUDIO",e[e.INPUT_AUDIO=1]="INPUT_AUDIO",e[e.INPUT_VIDEO=2]="INPUT_VIDEO",e}({}),WC=function(e){return e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.AUX=2]="AUX",e}({}),GC=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.FAIL=1]="FAIL",e}({});const JC=0,qC=1;let XC=function(e){return e[e.SIGNAL=0]="SIGNAL",e[e.MEDIA=1]="MEDIA",e}({}),QC=function(e){return e[e.CLOSED=0]="CLOSED",e[e.CONNECTED=1]="CONNECTED",e}({}),$C=function(e){return e[e.EVENT_JOIN_ROOM=1]="EVENT_JOIN_ROOM",e[e.EVENT_LEAVE_ROOM=2]="EVENT_LEAVE_ROOM",e[e.EVENT_WATCH=3]="EVENT_WATCH",e[e.EVENT_OPT_AUDIO=5]="EVENT_OPT_AUDIO",e[e.EVENT_SWITCH_NET=6]="EVENT_SWITCH_NET",e[e.EVENT_OPT_VIDEO=7]="EVENT_OPT_VIDEO",e[e.EVENT_SWITCH_DEVICE=9]="EVENT_SWITCH_DEVICE",e[e.EVENT_DNS_TIME=10]="EVENT_DNS_TIME",e[e.EVENT_SWITCH_ROLE=11]="EVENT_SWITCH_ROLE",e[e.EVENT_SEND_MEDIA=12]="EVENT_SEND_MEDIA",e[e.EVENT_START_MEDIA=13]="EVENT_START_MEDIA",e[e.EVENT_SEND_AUX_STREAM=14]="EVENT_SEND_AUX_STREAM",e[e.EVENT_SUBSCIBE=16]="EVENT_SUBSCIBE",e[e.EVENT_CONNECT_OTHER_ROOM=17]="EVENT_CONNECT_OTHER_ROOM",e[e.EVENT_CONNECTION_CHANNEL_STATUS=18]="EVENT_CONNECTION_CHANNEL_STATUS",e[e.EVENT_SET_UP_STREAM=19]="EVENT_SET_UP_STREAM",e[e.EVENT_SET_AUDIO_POLICY=20]="EVENT_SET_AUDIO_POLICY",e}({}),ZC=function(e){return e[e.QoS_UP_STREAM_VIDEO=1001]="QoS_UP_STREAM_VIDEO",e[e.QoS_DOWN_STREAM_VIDEO=1002]="QoS_DOWN_STREAM_VIDEO",e[e.QoS_UP_STREAM_AUDIO=1003]="QoS_UP_STREAM_AUDIO",e[e.QoS_DOWN_STREAM_AUDIO=1004]="QoS_DOWN_STREAM_AUDIO",e[e.QoS_AUX_UP_STREAM_VIDEO=1005]="QoS_AUX_UP_STREAM_VIDEO",e[e.QoS_AUX_DOWN_STREAM_VIDEO=1006]="QoS_AUX_DOWN_STREAM_VIDEO",e[e.QoS_DOWN_STREAM_AUDIO_STAT=1007]="QoS_DOWN_STREAM_AUDIO_STAT",e[e.QoS_UP_STREAM_VIDEO_SUM=1011]="QoS_UP_STREAM_VIDEO_SUM",e[e.QoS_DOWN_STREAM_VIDEO_SUM=1012]="QoS_DOWN_STREAM_VIDEO_SUM",e[e.QoS_UP_STREAM_AUDIO_SUM=1013]="QoS_UP_STREAM_AUDIO_SUM",e[e.QoS_DOWN_STREAM_AUDIO_SUM=1014]="QoS_DOWN_STREAM_AUDIO_SUM",e}({}),eA=function(e){return e[e.DEVICE_RT_SYSTEM=2001]="DEVICE_RT_SYSTEM",e[e.DEVICE_RT_CAMERA=2002]="DEVICE_RT_CAMERA",e[e.DEVICE_RT_SPEAKER=2003]="DEVICE_RT_SPEAKER",e[e.DEVICE_RT_MICROPHONE=2004]="DEVICE_RT_MICROPHONE",e}({}),tA=function(e){return e[e.DEVICE_STATUS_SPEAKER=3001]="DEVICE_STATUS_SPEAKER",e[e.DEVICE_STATUS_CAMERA=3002]="DEVICE_STATUS_CAMERA",e[e.DEVICE_STATUS_MICROPHONE=3003]="DEVICE_STATUS_MICROPHONE",e[e.DEVICE_STATUS_DEVICE_CHANGE=3004]="DEVICE_STATUS_DEVICE_CHANGE",e[e.DEVICE_STATUS_ERROR=3005]="DEVICE_STATUS_ERROR",e[e.DEVICE_STATUS_MEDIA_QUALITY=3006]="DEVICE_STATUS_MEDIA_QUALITY",e[e.DEVICE_STATUS_USERAGENT=3007]="DEVICE_STATUS_USERAGENT",e}({}),rA=function(e){return e[e.SIGNAL_REQUEST=401]="SIGNAL_REQUEST",e[e.SIGNAL_RESPONSE=402]="SIGNAL_RESPONSE",e}({}),iA=function(e){return e[e.API_CALL=501]="API_CALL",e[e.CALLBACK_API=502]="CALLBACK_API",e}({}),nA=function(e){return e[e.FirstFrame=606]="FirstFrame",e}({}),oA=function(e){return e[e.TraceNuwa=2998]="TraceNuwa",e}({}),sA=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.FAIL=1]="FAIL",e}({});const aA=["watch","batch_watch","cancel_watch"];let cA=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.NETWORK_CONNECT_ERROR=1]="NETWORK_CONNECT_ERROR",e[e.CLIENT_NOT_IDEL=2]="CLIENT_NOT_IDEL",e[e.SERVER_ERROR=3]="SERVER_ERROR",e[e.INTERNAL_ERROR=9]="INTERNAL_ERROR",e}({});const uA="2.0.9.300",dA="95f4253",lA="v3",hA=5e3,fA=1e4,pA=5,mA=6,gA=120,_A="https://rtc-sdk.obs.cn-north-4.myhuaweicloud.com:443/WebRTCSDK-Release/whitelist/browserSupportWhiteList.conf?AccessKeyId=J8YMIPY8O5U8D7REC0IM&Expires=1698541564&Signature=f8dGtzjfDERoMWQcW9MVlSqu/Y8%3D",SA="https://logservice.hicloud.com:443",vA="1090",yA=4,IA=["webCongestionAlgorithm"];class TA{static checkStringParameter(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3?arguments[3]:void 0;if(!e&&0===r)return;if("string"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid type: ".concat(e));const n=this.getStringBytes(e);if(n>t||n?@[\\]^_{}|~,]{1,128}$")}static checkRoomId(e){this.checkStringParameter(e,64,1,"^[a-zA-Z0-9-_]{1,64}$")}static checkUserId(e){this.checkStringParameter(e,64,1,"^[a-zA-Z0-9-_]{1,64}$")}static checkUserName(e){this.checkStringParameter(e,256,0)}static checkUserRole(e){if("number"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid parameter: ".concat(e));this.checkStringParameter("".concat(e),1,1,"^[0|2]$")}static checkSFUResourceType(e){if(null!=e){if("number"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramter: ".concat(e));this.checkStringParameter("".concat(e),1,1,"^[0|1|2|3]$")}}static checkResourceTags(e){if(null!=e&&(!Array.isArray(e)||e.filter((e=>"string"!=typeof e)).length>0))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramter of resourceTags: ".concat(e))}static checkUserInfo(e){if("object"!=typeof e)throw this.logger.error("ParameterValidator","userInfo type invalid "),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userInfo type invalid");this.checkUserId(e.userId),this.checkUserName(e.userName),this.checkUserRole(e.role),this.checkUserOptionInfo(e.optionInfo)}static checkJoinParams(e,t){this.checkRoomId(e),this.checkUserInfo(t)}static getStringBytes(e){if(!e)return 0;if("string"!=typeof e)return e.byteLength;let t=0;if(window.TextEncoder){return t=(new TextEncoder).encode(e).length,t}const r=e.length;for(let i=0;i255?t+=3:t++;return t}static checkUserOptionInfo(e){if(e&&![!0,!1,null,void 0].includes(e.recordPlaceholder))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid parameter: ".concat(e.recordPlaceholder))}static checkSrcMultiRoomInfo(e){if(!e.authorization||!e.ctime||"0"!==e.userId)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramters: ".concat(e.authorization," ").concat(e.ctime," ").concat(e.userId))}static checkDstMultiRoomInfo(e,t){this.checkRoomId(e.roomId),this.checkUserRole(t);const r=e.role>=t;if(!e.authorization||!e.ctime||!r)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramters: ".concat(e.authorization," ").concat(e.ctime," ").concat(e.role))}static checkCmdMsgValid(e){const t=TA.getStringBytes(e);if(t>32768)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid msg length: ".concat(t))}}i(TA,"logger",iE.getLogger());var RA=new class{setPorxyServer(e){TA.checkStringParameter(e,256,1);const t=/(.*:\/\/)?([^:]+):?(.*)?/.exec(e);let r=e;/^((\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))(\.|$)){4}$/.test(t[2])?t[1]||(r="http://".concat(t[2]).concat(t[3]?":":"").concat(t[3]||"")):t[1]||(r="https://".concat(t[2]).concat(t[3]?":":"").concat(t[3]||"")),this.proxyServer=r}getProxyServer(){return this.proxyServer}};function EA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function bA(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2e4,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,a=0;for(;a1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;const s=new Promise(((e,r)=>{t=setTimeout((()=>{clearTimeout(t),r(new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT))}),n)})),a=new Promise(((n,s)=>{fetch(this.getFetchUrl(e),bA(bA(bA({},this.defaultRequestOption),r),{headers:i})).then((t=>{if(XR.syncLocalTime(t.headers.get("Date")),!t.ok)return 504===t.status?this.logger.error(CA,"[HTTP_ID:".concat(o,"] doFetch failed: 504")):0===t.status?this.logger.error(CA,"[HTTP_ID:".concat(o,"] doFetch failed: 0")):this.logger.error(CA,"[HTTP_ID:".concat(o,"] doFetch failed: ").concat(t.status)),void s(new qc(t.status,"network error"));let r;const a=t.headers.get("Content-Type")||i["Content-Type"];r=/.*application\/json.*/.test(a)?t.json():/^text.*/.test(a)?t.text():t.arrayBuffer(),r.then((e=>{n({httpCode:t.status,data:e})})).catch((t=>{this.logger.error(CA,"[HTTP_ID:".concat(o,"], requestUrl: ").concat(XR.shieldUrlParameters(e),", doFetch get response failed: ").concat(t)),s(new qc(null==t?void 0:t.name,null==t?void 0:t.message))}))})).catch((t=>{this.logger.error(CA,"[HTTP_ID:".concat(o,"], requestUrl: ").concat(XR.shieldUrlParameters(e),", doFetch failed for exception: ").concat(t)),s(new qc(null==t?void 0:t.name,null==t?void 0:t.message))})).finally((()=>{clearTimeout(t)}))}));return Promise.race([s,a])}extendInfosHandle(e,t,r,i,n){i&&("start"===t?Object.assign(r,{id:i.length+1,domain:e,start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"dispatch",rspCode:"",errMsg:""}):"end"===t?((/v1\/dns/.test(e)||/global\.talk-cloud\.net/.test(e))&&(r.start_ms=XR.adjustTimeByOffset(r.start_ms)),n instanceof qc?(r.delay_ms=XR.getCurrentTimestamp()-r.start_ms,r.rspCode="".concat(n.getCode()),r.errMsg=n.getMsg()):(r.delay_ms=XR.getCurrentTimestamp()-r.start_ms,r.rspCode=n.httpCode||"200"),i.push(r)):this.logger.info(CA,"cannot handle"))}};let wA=!0,kA=!0;function OA(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function PA(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),n.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function MA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(wA=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function DA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(kA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function NA(){if("object"==typeof window){if(wA)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function UA(e,t){kA&&console.warn(e+" is deprecated, please use "+t+" instead.")}function xA(e){return"[object Object]"===Object.prototype.toString.call(e)}function LA(e){return xA(e)?Object.keys(e).reduce((function(t,r){const i=xA(e[r]),n=i?LA(e[r]):e[r],o=i&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[r]:n})}),{}):e}function BA(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?BA(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{BA(e,e.get(t),r)}))})))}function VA(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&BA(e,r,n)}))})),n}const YA=NA;function jA(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{r=r.filter((e=>"videoinput"===e.kind));let s=r.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&r.length&&t.includes("back")&&(s=r[r.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),YA("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return YA("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function FA(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function HA(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else PA(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function KA(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function zA(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(n(t)))},r])})).then(r,i)}}function WA(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>VA(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),PA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>VA(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function GA(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function JA(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return GA(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qA(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function XA(e,t){PA(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var QA=Object.freeze({__proto__:null,shimMediaStream:FA,shimOnTrack:HA,shimGetSendersWithDtmf:KA,shimGetStats:zA,shimSenderReceiverGetStats:WA,shimAddTrackRemoveTrackWithNative:GA,shimAddTrackRemoveTrack:JA,shimPeerConnection:qA,fixNegotiationNeeded:XA,shimGetUserMedia:jA,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function $A(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){UA("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function ZA(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ew(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(Dw){if("TypeError"!==Dw.name)throw Dw;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,o)}}function tw(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function rw(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),PA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function iw(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){UA("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function nw(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ow(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function sw(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function aw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function cw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var uw=Object.freeze({__proto__:null,shimOnTrack:ZA,shimPeerConnection:ew,shimSenderGetStats:tw,shimReceiverGetStats:rw,shimRemoveStream:iw,shimRTCDataChannel:nw,shimAddTransceiver:ow,shimGetParameters:sw,shimCreateOffer:aw,shimCreateAnswer:cw,shimGetUserMedia:$A,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function dw(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function lw(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function hw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function fw(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(pw(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function pw(e){return e&&void 0!==e.video?Object.assign({},e,{video:LA(e.video)}):e}function mw(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;rt.generateCertificate})}function gw(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function _w(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Sw(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var vw=Object.freeze({__proto__:null,shimLocalStreamsAPI:dw,shimRemoteStreamsAPI:lw,shimCallbacksAPI:hw,shimGetUserMedia:fw,shimConstraints:pw,shimRTCIceServerUrls:mw,shimTrackEventTransceiver:gw,shimCreateOfferLegacy:_w,shimAudioContext:Sw}),yw={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let i=8;i0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let o=3;o{r.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let n=0;return r.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const u=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));u.length>0&&u[0].length>1&&u[0][0]===a&&(c=u[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=d}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const o=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let t=0;t(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Ew(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Iw.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Iw.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=Iw.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return r.apply(this,arguments)}}function bw(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},PA(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Cw(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function Aw(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function ww(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function kw(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var Ow=Object.freeze({__proto__:null,shimRTCIceCandidate:Rw,shimMaxMessageSize:Ew,shimSendThrowTypeError:bw,shimConnectionState:Cw,removeExtmapAllowMixed:Aw,shimAddIceCandidateNullOrEmpty:ww,shimParameterlessSetLocalDescription:kw});const Pw=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=NA,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=OA(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=OA(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=OA(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Ow,extractVersion:OA,disableLog:MA,disableWarnings:DA,sdp:Tw};switch(i.browser){case"chrome":if(!QA||!qA||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=QA,ww(e,i),kw(e),jA(e,i),FA(e),qA(e,i),HA(e),JA(e,i),KA(e),zA(e),WA(e),XA(e,i),Rw(e),Cw(e),Ew(e,i),bw(e),Aw(e,i);break;case"firefox":if(!uw||!ew||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=uw,ww(e,i),kw(e),$A(e,i),ew(e,i),ZA(e),iw(e),tw(e),rw(e),nw(e),ow(e),sw(e),aw(e),cw(e),Rw(e),Cw(e),Ew(e,i),bw(e);break;case"safari":if(!vw||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=vw,ww(e,i),kw(e),mw(e),_w(e),hw(e),dw(e),lw(e),gw(e),fw(e),Sw(e),Rw(e),Ew(e,i),bw(e),Aw(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});window.AudioContext=window.AudioContext||window.webkitAudioContext,window.RTCPeerConnection=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;class Mw{static async checkSystemRequirements(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!window||!navigator)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"window or navigator error");if("chrome"===Pw.browserDetails.browser&&Mw.getBrowserVersion()<67)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"browser not support: ".concat(navigator.userAgent));if(!("WebSocket"in window))throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"WebSocket error");if(!window.RTCPeerConnection)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection Object not exist");let t=null;try{let e=new RTCPeerConnection;t=await e.createOffer({offerToReceiveAudio:!1,offerToReceiveVideo:!0}),Mw.isChrome()&&!/H264/i.test(t.sdp)&&(e.close(),e=new RTCPeerConnection,t=await e.createOffer({offerToReceiveAudio:!1,offerToReceiveVideo:!0})),e.close()}catch(jN){throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection construct error: ".concat(jN.message))}if(t&&!/H264/i.test(t.sdp))throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection unsupport AVC codec.");if(!("mediaDevices"in navigator))throw new qc(Gc.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED,"navigator.mediaDevices is not supported");return!XR.isMobileWeChatBrowser()||!e||await Mw.checkwWeChatSupported()}static async checkwWeChatSupported(){let e=[".*(iphone|ipad).*OS\\s1[4-9]_.*MicroMessenger.*",".*huawei.*(TBS|XWEB).*MicroMessenger.*",".*honor.*(TBS|XWEB).*MicroMessenger.*"];if(localStorage){const r=JSON.parse(localStorage.getItem("supportDeviceWhiteList")||"{}");var t;if(XR.getCurrentTimestamp()-parseInt(r.expire||"0")<=3e4)e=r.rules;else null===(t=localStorage)||void 0===t||t.removeItem("supportDeviceWhiteList")}if(Mw.checkSupportByRegexRules(e))return!0;try{const e=await AA.fetch(_A,{},{"Cache-Control":"no-cache"},2e3);if(e.data){var r;const t=e.data;if(t.expire=XR.getCurrentTimestamp(),null===(r=localStorage)||void 0===r||r.setItem("supportDeviceWhiteList",JSON.stringify(t)),Mw.checkSupportByRegexRules(t.rules))return!0}else{var i;null===(i=localStorage)||void 0===i||i.removeItem("supportDeviceWhiteList")}throw new Error("browser not support")}catch(jN){throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"browser not support: ".concat(navigator.userAgent))}}static checkSupportByRegexRules(e){const t=navigator.userAgent;let r=!1;for(const i of e){if(new RegExp(i,"ig").test(t)){r=!0;break}}return r}static isRTCScreenShareSupported(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}static isChrome(){return"chrome"===Pw.browserDetails.browser}static isFirefox(){return"firefox"===Pw.browserDetails.browser}static getBrowserVersion(){if("safari"===Pw.browserDetails.browser){const e=/.*Version\/(\d+).*/gi.exec(navigator.userAgent);if(e&&2===e.length)return parseInt(e[1])}return"chrome"===Pw.browserDetails.browser?Pw.browserDetails.version||91:Pw.browserDetails.version}static isOnlySupportUnfiedPlan(){let e=!0;if("chrome"===Pw.browserDetails.browser){e=Mw.getBrowserVersion()>90}else"safari"===Pw.browserDetails.browser&&(e=Pw.browserDetails.supportsUnifiedPlan);return e}static getBrowserInfo(){return"".concat(Pw.browserDetails.browser.toLowerCase(),"-").concat(Mw.getBrowserVersion())}}var Dw=function(e){return function(t){return function(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}(t)===e}},Nw=Dw("function"),Uw=Dw("object"),xw=Dw("array"),Lw=Dw("string"),Bw=Dw("number"),Vw=Dw("boolean"),Yw=Dw("undefined"),jw=Dw("null");function Fw(e){return Fw="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fw(e)}function Hw(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Kw(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r=0&&i.length===Math.floor(i.length)&&i.length3&&void 0!==arguments[3]&&arguments[3];e.addEventListener?e.addEventListener(t,r,i):e.attachEvent("on".concat(t),r)}var Bk=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Zw(e.split("?"),2),i=r[0],n=r[1];if(!n)return e;var o=n.split("&").filter((function(e){return!fk(t,e.split("=")[0].toLocaleLowerCase())}));return o.length?"".concat(i,"?").concat(o.join("&")):i},Vk=function(e){var t={};e.includes("#")&&(e=e.split("#")[0]);var r=e.split("?")[1];if(!r)return t;for(var i=r.split("&"),n=0;n0&&void 0!==arguments[0]&&arguments[0];Hw(this,e),this.isH5=r,this.waitTime=0,this.waitTimeFlagTime=0,this.waitTimeFlag=!0,this.accessTime=Ak(),this.config={defaultCookie:{},useCookie:!0,isInit:!1,usedPageUrl:!0,intervalTime:18e5,batchSend:!1},this.globals={idsite:"",title:Fk.title,id:"unknown",rid:"unknown",idts:Ak(),idvc:0,idn:"",di:{sessionId:"unknown"},refts:Ak(),viewts:Ak(),CXX:"",uid:"",cvar:""},this.customData={},pk(Yk,(function(e,r){t[r]=e})),Lk(Hk,"beforeunload",this.beforeUnloadHandler.bind(this)),Lk(Fk,"visibilitychange",this.stateChanged.bind(this)),this.updateSessionId()}return zw(e,[{key:"updateSessionId",value:function(){var e=Ok("sessionId");e&&e.sessionId&&(this.globals.di.sessionId=e.sessionId)}},{key:"beforeUnloadHandler",value:function(){this.config.isInit&&this.config.useCookie&&Uk(this.getStoreName(dk),Ak(),31536e6,"/"),this.stateChanged()}},{key:"getStoreName",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk,r=arguments.length>2?arguments[2]:void 0;return e&&this.globals.idsite?"".concat(t).concat(e,"_").concat(this.globals.idsite,"_").concat((r||location.host).replace(/\./g,"_")):""}},{key:"handleSessionId",value:function(){var e=this.getStoreName("idn"),t=Nk(e);t||(t=_k()),this.globals.idn=t,this.config.useCookie&&Uk(e,t,this.config.intervalTime,"/")}},{key:"stateChanged",value:function(){"visible"===Fk.visibilityState&&this.updateSessionId(),"hidden"===Fk.visibilityState&&this.config.batchSend&&this.batchSendNow(),this.waitTimeFlag?this.waitTime+=Ak()-(this.waitTimeFlagTime||this.accessTime):this.waitTimeFlagTime=Ak(),this.waitTimeFlag=!this.waitTimeFlag}},{key:"getData",value:function(e,t,r){var i=Hk.navigator.userAgent,n=this.globals,o=n.id,s=n.rid,a=n.di,c=n.CXX,u=n.idsite,d=n.uid,l=n.cvar,h=n.idts,f=n.idvc,p=n.idn,m=n.refts,g=n.viewts;return{type:e,vf:o,rid:s,nsid:a.sessionId,rt:t.eventTime,ut:i.match(/AppleWebKit.*Mobile.*/)?-1!==gk(i," wv")?2:1:0,cxx:c,idsite:u,suid:d,cvar:t.cvar||l,idts:h,idvc:f,idn:p,refts:m,viewts:g,hsv:Sk,data:r}}},{key:"getFinalSendData",value:function(e){var t=new Date,r=this.globals,i=r.title,n=r.id,o=r.idsite,s=r.cvar,a=r.idts,c=r.idvc,u=r.idn,d=r.refts,l=r.viewts,h=r.rid,f=r.di,p=this.config.usedPageUrl,m={idsite:encodeURIComponent(o),rec:"1",r:"886244",h:t.getHours(),m:t.getMinutes(),s:t.getSeconds(),url:encodeURIComponent(this.deleteUrlQuery(p?Hk.location.href:"/",vk)),_id:encodeURIComponent(n),_rid:encodeURIComponent(h),_nsid:encodeURIComponent(f.sessionId),_idts:a,_idvc:c,_idn:u,urlref:this.deleteUrlQuery(Fk.referrer,vk),_refts:d,_viewts:l,scd:"24",vpr:"".concat(Hk.screen.width," X ").concat(Hk.screen.height),cvar:Uw(e.cvar||s)?encodeURIComponent(JSON.stringify(e.cvar||s)):encodeURIComponent(e.cvar||s),pdf:"1",qt:"0",data:this.isH5?JSON.stringify(e):encodeURIComponent(JSON.stringify(e))};return e.type===ok||e.type===nk?mk({link:encodeURIComponent(i)},m):mk({action_name:encodeURIComponent(i)},m)}},{key:"initCookie",value:function(e){this.config.isInit=!0;var t=this.config,r=t.useCookie,i=t.defaultCookie.domain;if(r){if(i){var n=this.getStoreName(ck,sk),o=this.getStoreName(uk,sk);xk(n),xk(o)}var s=this.getStoreName(ck,sk,i),a=this.getStoreName(uk,sk,i),c=Nk(s),u=Nk(a);e&&e(s,c,a,u,i),c||(Mk.isSupport()&&Mk.get(s)?(c=Mk.get(s),u=Mk.get(a)||Ak()):(c=_k(),u=Ak()),Uk(s,c,31536e6,"/",i),Uk(a,u,31536e6,"/",i)),this.globals.id=c,this.globals.idts=u||Ak();var d=this.getStoreName("refts"),l=Nk(d);l||Fk.referrer&&(l=Ak(),Uk(d,l,15552e6,"/")),this.globals.refts=l||Ak();var h=this.getStoreName(dk),f=Nk(h);this.globals.viewts=f||Ak();var p=this.getStoreName("idvc"),m=Nk(p);m=m?Number(m)+1:Mk.isSupport()&&Mk.get(p)?Number(Mk.get(p))+1:1,Uk(p,m,31536e6,"/"),this.globals.idvc=m,Mk.isSupport()&&!Mk.get(s)&&(Mk.set(s,c),Mk.set(a,u),Mk.set(p,m))}else this.globals.id="unknown",this.globals.idts=Ak(),this.globals.refts=Ak(),this.globals.viewts=Ak(),this.globals.idvc=0;this.handleSessionId()}},{key:"setIdsite",value:function(e){return Lw(e)?new RegExp("^[a-zA-Z0-9_./][A-Za-z0-9_./]*$").test(e)?(this.globals.idsite=e,this.initCookie(),this):(console.error("idsite is invalid."),this):(console.error("idsite type should be string."),this)}},{key:"setAutoTrack",value:function(e,t,r){var i=this;if(!Uw(e))return this;var n=function(t,r){var n=new t(i);n.init(e),r&&r(n)};if(t)n(t,r);else if(Hk.HAAutoTracker)n(Hk.HAAutoTracker,r);else{var o=Ak();!function(e,t){var r=jk.createElement("script");r.type="text/javascript",r.readyState?r.onreadystatechange=function(){"loaded"!==r.readyState&&"complete"!==r.readyState||(r.onreadystatechange=null,t())}:r.onload=t,r.src=e,jk.getElementsByTagName("head")[0].appendChild(r)}(e.autotracker_url||yk,(function(){var e=Ak();wk("[load+excute] HAWebSDK autotracker module use ".concat(e-o," ms.")),n(Hk.HAAutoTracker,r)}))}return this}}]),e}(),zk=function(){function e(t,r,i){Hw(this,e),this.core=t,this.dataType=r,this.serverUrl=i,this.state=0,this.keys=[],this.queue=[],this.intervalID=null}return zw(e,[{key:"isH5",value:function(){return!0===this.core.isH5||void 0!==kk().haGetDeviceInfo}},{key:"init",value:function(){var e=this;this.core.config.batchSend?(pk(["batchSend"],(function(t){var r=e[t];e[t]=function(){0===this.state?r.apply(this,arguments):this.queue.push([t,arguments])}})),!this.intervalID&&this.core.config.batchSend.interval&&(this.intervalID=setInterval((function(){e.batchSend()}),this.core.config.batchSend.interval))):this.intervalID&&clearInterval(this.intervalID)}},{key:"batchSend",value:function(){var e=this,t=this.getEventsToSendFromStorage();0!==t.length&&(this.state=1,this.onReport(this.core.getFinalSendData(t),(function(t){e.state=0,200===t.status?(e.core.config.batchSend.retryTimes=10,pk(e.keys,(function(e){Mk.remove(e)})),e.keys=[],e.batchSend(),e.queue.length>0&&(e[e.queue[0][0]].apply(e,e.queue[0][1]),e.queue=e.queue.splice(0,1))):e.core.config.batchSend.retryTimes<=1?e.intervalID&&clearInterval(e.intervalID):e.core.config.batchSend.retryTimes--}),!0))}},{key:"onceSend",value:function(e,t){this.onReport(this.core.getFinalSendData(e),t,!1)}},{key:"addToStorage",value:function(e,t){try{var r=JSON.stringify(e);if(kk().haEncrypt){var i=Ak();r=kk().haEncrypt(r);var n=Ak();wk("data encrypt use ".concat(n-i," ms. encrypted data: ").concat(r))}Mk.set(this.core.getStoreName(_k(),ak),r)}catch(r){r.message===lk&&(this.onceSend(e,t),this.batchSend())}}},{key:"getEventsToSendFromStorage",value:function(){var e=[],t=0;if(this.isH5())for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];return Hw(this,r),(e=t.call(this,i)).config.linker={},e.config.serverUrl="",e.config.requestMode="",e.config.isImg=!1,e.config.debugMode=!1,e.config.customUrlParams={},e.config.defaultHeaders={"Content-type":"application/x-www-form-urlencoded;charset=UTF-8"},e.defaultSender=new zk(Xw(e)),e.reportMap={},Lk(Wk,"click",e.hrefIntercept.bind(Xw(e)),!0),e}return zw(r,[{key:"urlAddLinker",value:function(e,t){if(!e)return e;var r=e.split("#"),i=r[0],n=r[1]?"#".concat(r[1]):"",o=i.replace(/(https|http):\/\/([^/?]+)(.*)/,"$2"),s=!1;if(this.config.linker.exclude&&(s=this.config.linker.exclude.includes(o)),this.config.linker.domains&&!s&&this.config.linker.domains.filter((function(e){return new RegExp("".concat(e,"$"),"i").test(o)})).length){t&&t.preventDefault();var a=this.getStoreName(ck,sk,this.config.defaultCookie.domain),c={ts:Ak(),id:Nk(a)};this.config.linker.ext&&(c.ext=this.config.linker.ext),i=gk(i,"?")>-1?"".concat(i,"&ha_linker=").concat(Gk.btoa(JSON.stringify(c))).concat(n):"".concat(i,"?ha_linker=").concat(Gk.btoa(JSON.stringify(c))).concat(n)}return i}},{key:"hrefIntercept",value:function(e){var t=e.target||e.srcElement;if("a"!==Ik(t)){var r=Ck(t);if(!r)return;t=r}var i=t.getAttribute("href");i&&(i=this.urlAddLinker(i,e),gk(i,"ha_linker")>-1&&Gk.open(i,t.getAttribute("target")||"_self"))}},{key:"initCookie",value:function(){var e=this;$w(Jw(r.prototype),"initCookie",this).call(this,(function(t,r,i,n,o){var s=Vk(Wk.location.href).ha_linker;if(s)try{var a=JSON.parse(Gk.atob(s));!(Ak()-a.ts>(a.ext||1e4))&&a.id&&(r||(r=a.id,Uk(t,r,31536e6,"/",o),n=Ak(),Uk(i,n,31536e6,"/",o)),e.globals.rid=a.id)}catch(e){console.error("Invalid linker:"+e)}}))}},{key:"getSender",value:function(){var e=this,t=null;return pk(this.reportMap,(function(r){r.url===e.config.serverUrl&&(t=r.sender)})),t||this.defaultSender}},{key:"push",value:function(){for(var e=arguments,t=this,r=function(){var r=e[i],n=r.shift();try{setTimeout((function(){Lw(n)?t[n].apply(t,r):t.apply(t,r)}),0)}catch(e){console.error("Invalid method:"+n+", please check!")}},i=0;i0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1?arguments[1]:void 0;this.config.serverUrl=e;var r=e;return Yw(t)||(r=t),this.reportMap[r]||(this.reportMap[r]={url:e,sender:new zk(this,r,e)},this.config.batchSend&&this.reportMap[r].sender.init()),this}},{key:"setTitle",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.title=e,this}},{key:"setUserAccount",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.id=e,this}},{key:"setCXX",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.CXX=e,this}},{key:"setUid",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.uid=e,this}},{key:"setPageData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.cvar=e,this}},{key:"setCustomData",value:function(e){return Uw(e)||Nw(e)?this.customData=e:console.error("The arguments of the setCustomData() method is invalid."),this}},{key:"setHttpHeader",value:function(e){return Uw(e)?(mk(this.config.defaultHeaders,e),this):(console.error("custom header type should be object."),this)}},{key:"setIsUseCookie",value:function(e){if(!Vw(e))return console.error("useCookie type should be boolean"),this;if(this.config.useCookie=e,!this.config.useCookie){var t=Wk.cookie.split("; "),r=/^(HW_)(id|idts|idvc|idn|viewts|refts)_/;pk(t,(function(e){var t=e.split("=");r.test(t[0])&&xk(t[0])})),this.initCookie()}return this}},{key:"setReportMethod",value:function(e){return Vw(e)?(this.config.isImg=e,this):(console.error("isImg type should be boolean."),this)}},{key:"setSessionTimeoutDuration",value:function(e){return Bw(e)?(this.config.intervalTime=e,this):(console.error("intervalTime type should be number."),this)}},{key:"setDebugMode",value:function(e){return Vw(e)?(this.config.debugMode=e,this):(console.error("debugMode type should be boolean"),this)}},{key:"setCustomUrlParams",value:function(e){if(!Uw(e))return console.error("customUrlParams type should be object"),this;for(var t in e){if(fk(["x_hasdk_debug","url","_id","_idts","_idvc","h","m","s","_rid"],t))return console.error("customUrlParams can'n include x_hasdk_debug, url, _id, _idts, _idvc, h, m, s, _rid"),this;var r=e[t];if(!r||!Bw(r)&&!Lw(r))return console.error("customUrlParams object value should be number or string"),this;if(!new RegExp("^[a-zA-Z0-9_./][A-Za-z0-9_./]*$").test(t)||!new RegExp("^[a-zA-Z_0-9_./][A-Za-z0-9_./]*$").test(r))return console.error("customUrlParams object include invalid key or value"),this;mk(this.config.customUrlParams,Ww({},t,r))}return this}},{key:"setIstUseUrl",value:function(e){return Vw(e)?(this.config.usedPageUrl=e,this):(console.error("usedPageUrl type should be boolean."),this)}},{key:"setRequestMode",value:function(e){return"ajax"!==e||Rk()?"beacon"!==e||bk()?(fk(["beacon","ajax","img"],e)&&(this.config.requestMode=e),this):(console.error("navigator.sendBeacon() is not supported."),this):(console.error("XMLHttpRequest is not supported."),this)}},{key:"setBatchSend",value:function(e){if(!Mk.isSupport())return console.error("localStorage is not supported, so batch send is not supported."),this;if(!Rk())return console.error("XMLHttpRequest is not supported, so batch send is not supported."),this;var t={timeout:6e3,interval:6e3,maxLength:6,retryTimes:10};return Vw(e)&&e?this.config.batchSend=t:Uw(e)&&(this.config.batchSend=mk(t,e)),pk(this.reportMap,(function(e){e.sender&&e.sender.init()})),this}},{key:"batchSendNow",value:function(){return pk(this.reportMap,(function(e){e.sender&&e.sender.batchSend()})),this}},{key:"setLinker",value:function(e){return Uw(e)?xw(e.domains)?e.exclude&&!xw(e.exclude)?(console.error("custom exclude type should be Array."),this):(this.config.linker=e,this):(console.error("custom domains type should be Array."),this):(console.error("custom linker type should be object."),this)}},{key:"setUrlLinker",value:function(e){return this.urlAddLinker(e)}},{key:"setCookie",value:function(e){return Uw(e)?(this.config.defaultCookie=e,this):(console.error("custom cookie type should be object."),this)}}]),r}(),qk=document,Xk=window,Qk=qk.documentElement,$k=qk.body,Zk=document,eO=window,tO=function(e){Gw(r,Jk);var t=Qw(r);function r(){var e;return Hw(this,r),(e=t.call(this)).config.baseinfotypeSwitch1=!1,e.switch1Num=0,e.config.baseinfotypeSwitch2=!1,e.switch2Num=0,e}return zw(r,[{key:"setBaseinfotypeSwitch",value:function(e){return Vw(e)?(this.config.baseinfotypeSwitch1=e,e&&0===this.switch1Num&&(this.switch1Num++,Lk(Zk,"DOMContentLoaded",this.reportPageEntryEvent.bind(this))),this):(console.error("baseinfotypeSwitch1 type should be boolean."),this)}},{key:"setWindowCloseSwitch",value:function(e){return Vw(e)?(this.config.baseinfotypeSwitch2=e,e&&0===this.switch2Num&&(this.switch2Num++,Lk(eO,"beforeunload",this.reportPageCloseEvent.bind(this))),this):(console.error("baseinfotypeSwitch2 type should be boolean."),this)}},{key:"sendPageinfo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.waitTime=0,this.waitTimeFlagTime=0,this.waitTimeFlag=!0,this.accessTime=Ak(),this.config.baseinfotypeSwitch1=!0,this.reportPageEntryEvent(e,t),this}},{key:"sendPageClose",value:function(){return this.config.baseinfotypeSwitch2=!0,this.reportPageCloseEvent(),this}},{key:"sendData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s={eventTime:Ak(),eventName:e,eventLabel:t,customData:r,cvar:i};return this.execReport(ik,s,n,o),this}},{key:"sendClickData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s={eventTime:Ak(),eventName:e,eventLabel:t,customData:r,cvar:i};return this.execReport(ok,s,n,o),this}},{key:"bindclick",value:function(e,t,r,i,n){var o=this,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],a=e===Zk?Zk:Zk.getElementById(e);return a?(Lk(a,t,(function(t){var c=t.screenX,u=t.screenY,d=t.clientX,l=t.clientY,h=Xk.innerHeight||Qk.clientHeight||$k.clientHeight||0,f=Xk.innerWidth||Qk.clientWidth||$k.clientWidth||0,p={eventTime:Ak(),elementId:e,cls:a.className,data:r,cvar:i,position:{res:"".concat(c,"X").concat(u),vpr:"".concat(d,"X").concat(l),doc:"".concat(f,"X").concat(h)}};o.execReport(nk,p,n,s)})),this):this}},{key:"reportPageEntryEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.execReport(rk,{eventTime:Ak()},e,t)}},{key:"reportPageCloseEvent",value:function(){this.execReport(rk,{eventTime:Ak()})}},{key:"execReport",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this.handleSessionId();var n=this.getEventData(e,t),o=this.getSender();this.config.batchSend&&!i?(n.dataType=o.dataType,o.addToStorage(n,r)):o.onceSend(n,r)}},{key:"getEventData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.currentUrl,i=void 0===r?eO.location.href:r,n={url:Bk(this.config.usedPageUrl?i:"/",vk),title:this.globals.title,at:this.accessTime,rf:Bk(Zk.referrer,vk)};return e===rk?(n.res="".concat(eO.screen.width," X ").concat(eO.screen.height),n.cwt=t.eventTime,n.dt=this.waitTime):e===ik||e===ok?(n.en=t.eventName,n.el=t.eventLabel,n.cd=t.customData):e===nk&&(n.ei=t.elementId===Zk?"#document":t.elementId,n.ec=t.cls,n.ps=t.position,n.data=t.data||""),this.getData(e,t,n)}}]),r}(),rO=Ak(),iO=new tO,nO=Ak();wk("[excute] hawebsdk use ".concat(nO-rO," ms."));const oO={},sO={grs_sdk_global_route_config_hwrtc:{applications:[],services:[{name:"com.huawei.cloud.videortn",routeBy:"ser_country>geo_ip",servings:[{countryOrAreaGroup:"DR1",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-drcn.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR2",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-dra.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR3",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-dre.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR4",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-drru.platform.dbankcloud.com"}}],countryOrAreaGroups:[]}],countryOrAreaGroups:[{id:"DR1",name:"China",countriesOrAreas:["CN"],description:"China zone"},{id:"DR2",name:"Asian-African-Latin American",countriesOrAreas:["AE","AF","AG","AI","AM","AO","AQ","AR","AS","AW","AZ","BB","BD","BF","BH","BI","BJ","BL","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CC","CD","CF","CG","CI","CK","CL","CM","CO","CR","CU","CV","CX","DJ","DM","DO","DZ","EC","EG","EH","ER","ET","FJ","FK","FM","GA","GD","GE","GF","GH","GM","GN","GP","GQ","GS","GT","GU","GW","GY","HK","HM","HN","HT","ID","IN","IO","IQ","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LK","LR","LS","LY","MA","MG","MH","ML","MM","MN","MO","MP","MQ","MR","MS","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NP","NR","NU","OM","PA","PE","PF","PG","PH","PK","PN","PR","PS","PW","PY","QA","RE","RW","SA","SB","SC","SD","SG","SH","SL","SN","SO","SR","SS","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TT","TV","TW","TZ","UG","UY","UZ","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"],description:"Asian-African-Latin American zone"},{id:"DR3",name:"Europe",countriesOrAreas:["AD","AL","AN","AT","AU","AX","BA","BE","BG","BQ","CA","CH","CW","CY","CZ","DE","DK","EE","ES","FI","FO","FR","GB","GG","GI","GL","GR","HR","HU","IE","IL","IM","IS","IT","JE","LI","LT","LU","LV","MC","MD","ME","MF","MK","MT","NL","NO","NZ","PL","PM","PT","RO","RS","SE","SI","SJ","SK","SM","SX","TR","UA","UM","US","VA","VC","XK","YK"],description:"Europe zone"},{id:"DR4",name:"Russia",countriesOrAreas:["RU"],description:"Russia zone"},{id:"DR5",name:"A2",countriesOrAreas:["IR"],description:"A2 zone"}]},grs_sdk_global_route_config_rtcha:{applications:[],services:[{name:"com.huawei.cloud.hianalytics",routeBy:"ser_country",servings:[{countryOrAreaGroup:"DR1",addresses:{ROOT:"https://metrics1.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR2",addresses:{ROOT:"https://metrics3.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR3",addresses:{ROOT:"https://metrics2.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR4",addresses:{ROOT:"https://metrics5.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR5",addresses:{ROOT:"https://metrics4.data.hicloud.com:6447"}}],countryOrAreaGroups:[]},{name:"com.huawei.cloud.hianalytics.aspg",routeBy:"ser_country",servings:[{countryOrAreaGroup:"DR1",addresses:{ROOT:"https://metrics1.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR2",addresses:{ROOT:"https://metrics-dra.dt.hicloud.com:6447"}},{countryOrAreaGroup:"DR3",addresses:{ROOT:"https://metrics2.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR4",addresses:{ROOT:"https://metrics5.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR5",addresses:{ROOT:"https://metrics4.data.hicloud.com:6447"}}],countryOrAreaGroups:[]}],countryOrAreaGroups:[{id:"DR1",name:"China",countriesOrAreas:["CN"],description:"China zone"},{id:"DR2",name:"Asian-African-Latin American",countriesOrAreas:["AE","AF","AG","AI","AM","AO","AQ","AR","AS","AW","AZ","BB","BD","BF","BH","BI","BJ","BL","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CC","CD","CF","CG","CI","CK","CL","CM","CO","CR","CU","CV","CX","DJ","DM","DO","DZ","EC","EG","EH","ER","ET","FJ","FK","FM","GA","GD","GE","GF","GH","GM","GN","GP","GQ","GS","GT","GU","GW","GY","HK","HM","HN","HT","ID","IN","IO","IQ","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LK","LR","LS","LY","MA","MG","MH","ML","MM","MN","MO","MP","MQ","MR","MS","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NP","NR","NU","OM","PA","PE","PF","PG","PH","PK","PN","PR","PS","PW","PY","QA","RE","RW","SA","SB","SC","SD","SG","SH","SL","SN","SO","SR","SS","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TT","TV","TW","TZ","UG","UY","UZ","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"],description:"Asian-African-Latin American zone"},{id:"DR3",name:"Europe",countriesOrAreas:["AD","AL","AN","AT","AU","AX","BA","BE","BG","BQ","CA","CH","CW","CY","CZ","DE","DK","EE","ES","FI","FO","FR","GB","GG","GI","GL","GR","HR","HU","IE","IL","IM","IS","IT","JE","LI","LT","LU","LV","MC","MD","ME","MF","MK","MT","NL","NO","NZ","PL","PM","PT","RO","RS","SE","SI","SJ","SK","SM","SX","TR","UA","UM","US","VA","VC","XK","YK"],description:"Europe zone"},{id:"DR4",name:"Russia",countriesOrAreas:["RU"],description:"Russia zone"},{id:"DR5",name:"A2",countriesOrAreas:["IR"],description:"A2 zone"}]}},aO="RTCReport";const cO=new class{constructor(){this.logger=iE.getLogger(),this.regularReport(hA),iO.push(["setOnReportUrl","".concat(sO.grs_sdk_global_route_config_rtcha.services[0].servings[0].addresses.ROOT,"/webv4")]),iO.push(["setIdsite","com.huawei.rtcsdk"]),iO.setBatchSend({timeout:13e3,interval:!0,maxLength:30}),this.records=[],Mw.isFirefox()||(window.onbeforeunload=()=>{this.logger.info("stat","window is closing, emergency report"),this.records.length>0&&this.reportRecordsBeacon(this.records),this.clearData()})}setReportServer(e){this.opsServer=null;const t=RA.getProxyServer();if(t){const r=e.replace(/http(s)?:\/\//,"");this.opsServer="".concat(t,"/").concat(r,"/webv4")}else this.opsServer="".concat(e,"/webv4");iO.push(["setOnReportUrl",this.opsServer])}regularReport(e){this.reportInterval&&clearInterval(this.reportInterval),this.reportInterval=setInterval((()=>{if(this.opsServer&&0!=this.records.length)try{iO.setRequestMode("ajax"),this.records.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};iO.push(["sendData",t,t,r,null,null])})),this.clearData()}catch(jN){this.logger.error(aO,"regularReport failed")}}),e)}async addRecords(e){this.records=this.records.concat(e||[]),this.adjustRecordsLength(this.records)}async addRecord(e){this.records.push(e),this.adjustRecordsLength(this.records)}adjustRecordsLength(e){e.length>1e4&&e.splice(0,e.length-1e4)}clearData(){this.records.length=0}immediateReportRecords(){this.opsServer&&(this.reportRecords(this.records),this.clearData())}reportRecords(e){if(this.opsServer)try{iO.setRequestMode("ajax"),e.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};iO.push(["sendData",t,t,r,null,t=>{4===t.readyState&&200===t.status||this.addRecord(e)},!0])}))}catch(jN){throw this.logger.error(aO,"fetch request failed"),jN}}async reportRecordsBeacon(e){if(this.opsServer)try{iO.setRequestMode("beacon"),e.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};iO.push(["sendData",t,t,r,null,null,!0])}))}catch(jN){throw this.logger.error(aO,"beacon request failed"),jN}}},uO="STATISTIC_ENABLE",dO="ACCESS_RESOURCE_TYPE",lO="RESOURCE_TAGS",hO="FRAME_ENCRYPTION_MODE",fO="PORT_TYPE",pO="ENVIRONMENT_SUFFIX",mO="GRS_LOCAL_EXT_INFO",gO={ACCESS_RESOURCE_TYPE:e=>TA.checkSFUResourceType(e),RESOURCE_TAGS:e=>TA.checkResourceTags(e)},_O="ParametersUtil";const SO=new class{constructor(){this.logger=iE.getLogger(),this.parameters=new Map}setParameter(e,t){if(!e)return this.logger.error(_O,"setParameter, parameterKey is null"),!1;try{return this.logger.debug(_O,"setParameter, parameterKey: ".concat(e,", parameterValue: ").concat(t)),gO[e]&&gO[e](t),this.parameters.set(e.toLowerCase(),t),!0}catch(jN){return this.logger.error(_O,"setParameter occur error: ".concat(jN)),!1}}getParameter(e){try{return e&&this.parameters.has(e.toLowerCase())?this.parameters.get(e.toLowerCase()):null}catch(jN){return this.logger.error(_O,"getParameter occur error: ".concat(jN)),null}}};let vO=function(e){return e.TRACK_TYPE_AUDIO="audio",e.TRACK_TYPE_VIDEO="video",e.TYPE_APPLICATION="application",e}({}),yO=function(e){return e.STREAM_TYPE_MAIN="main",e.STREAM_TYPE_AUX="aux",e}({}),IO=function(e){return e[e.USER_SUBSCRIBE_AUDIOPOLICY=0]="USER_SUBSCRIBE_AUDIOPOLICY",e[e.TOPN_AUDIOPOLICY=1]="TOPN_AUDIOPOLICY",e}({}),TO=function(e){return e[e.USER_SUBSCRIBE_AUDIOPOLICY=2]="USER_SUBSCRIBE_AUDIOPOLICY",e[e.TOPN_AUDIOPOLICY=3]="TOPN_AUDIOPOLICY",e}({}),RO=function(e){return e[e.COMMON_SFU_RESOURCE=0]="COMMON_SFU_RESOURCE",e[e.COMPANY_SFU_RESOURCE=1]="COMPANY_SFU_RESOURCE",e[e.MPC_SFU_RESOURCE=2]="MPC_SFU_RESOURCE",e[e.LLL_SFU_RESOURCE=3]="LLL_SFU_RESOURCE",e}({});let EO=function(e){return e[e.NETWORK_QUALITY_UNKNOW=0]="NETWORK_QUALITY_UNKNOW",e[e.NETWORK_QUALITY_GREAT=1]="NETWORK_QUALITY_GREAT",e[e.NETWORK_QUALITY_GOOD=2]="NETWORK_QUALITY_GOOD",e[e.NETWORK_QUALITY_DEFECTS=3]="NETWORK_QUALITY_DEFECTS",e[e.NETWORK_QUALITY_WEAK=4]="NETWORK_QUALITY_WEAK",e[e.NETWORK_QUALITY_BAD=5]="NETWORK_QUALITY_BAD",e[e.NETWORK_QUALITY_DISCONNECT=6]="NETWORK_QUALITY_DISCONNECT",e}({}),bO=function(e){return e[e.NotJoin=0]="NotJoin",e[e.Joined=1]="Joined",e[e.Rejoining=2]="Rejoining",e}({}),CO=function(e){return e[e.normal=0]="normal",e[e.resolutionChange=1]="resolutionChange",e[e.remoteRejoinCache=2]="remoteRejoinCache",e[e.localRejoin=3]="localRejoin",e}({});const AO={"90p-":{width:120,height:90},"90p":{width:160,height:90},"120p":{width:160,height:120},"180p-":{width:240,height:180},"180p":{width:320,height:180},"240p":{width:320,height:240},"270p":{width:480,height:270},"300p":{width:400,height:300},"360p-":{width:480,height:360},"360p":{width:640,height:360},"450p":{width:800,height:450},"480p":{width:640,height:480},"540p":{width:960,height:540},"630p":{width:1120,height:630},"720p-":{width:960,height:720},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}};class wO{static getResolution(e,t){const r=Math.min(e,t);return r<180?"LD":r<360?"SD":r<720?"HD":"FHD"}static getResolutionType(e,t){return Object.keys(AO).find((r=>AO[r].width===e&&AO[r].height===t))}}class kO{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;this.elements=new Array(e+1),this.front=0,this.tail=0,this._size=0}getCapacity(){return this.elements.length-1}isEmpty(){return this.front===this.tail}size(){return this._size}push(e){this._size===this.getCapacity()&&this.dequeue(),this.elements[this.tail]=e,this.tail=(this.tail+1)%this.elements.length,this._size++}dequeue(){if(this.isEmpty())throw new Error("Cannot dequeue from an empty queue.");const e=this.elements[this.front];return this.elements[this.front]=null,this.front=(this.front+1)%this.elements.length,this._size--,e}getFront(){return this.isEmpty()?null:this.elements[this.front]}getTail(){if(this.isEmpty())return null;const e=0===this.tail?this.elements.length-1:this.tail-1;return this.elements[e]}getElement(e){return e<0||e>=this.size()?null:this.elements[(this.front+e)%this.elements.length]}}const OO=new class{constructor(){i(this,"isFireFox",Mw.isFirefox()),this.reportSymbol=Symbol("RTCInterval_".concat(XR.getCurrentTimestamp())),this.mapInterval=new kO}getSymbol(){return this.reportSymbol}reset(){delete this.mapInterval,this.mapInterval=new kO,clearTimeout(this.gatherTimer),this.gatherTimer=null}addConnection(e,t){this.connectionsManagers||(this.connectionsManagers=new Map),this.connectionsManagers.set(e,t),this.execMyInterval((async()=>{await this.execInterval()}),100)}checkIsMediaStatsType(e){return["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp"].includes(e.type)}checkCandidatePair(e){return"candidate-pair"===e.type.toString()&&(!0===e.selected||!0===e["nominated "]||"succeeded"===e.state)}async getStatsData(e,t){const r=await(null==t?void 0:t.getStats());r&&r.forEach(((t,r)=>{this.checkIsMediaStatsType(t)?e.set(t.type+"-"+t.kind+"_"+t.ssrc,t):this.checkCandidatePair(t)?(t.currentRoundTripTime=t.currentRoundTripTime||Math.abs(t.lastPacketReceivedTimestamp-t.lastPacketSentTimestamp),e.set(t.type,t)):"track"===t.type.toString()&&e.set(r,t)}))}async getData(e,t,r){const i=e.getConnection(r);await this.getStatsData(t,i)}async execInterval(){const e=new Map;for(const t of this.connectionsManagers.keys()){const r=new Map,i=new Map,n=new Map,o=[];o.push(this.getData(this.connectionsManagers.get(t),i,yO.STREAM_TYPE_MAIN)),o.push(this.getData(this.connectionsManagers.get(t),n,yO.STREAM_TYPE_AUX)),await Promise.all(o),r.set(yO.STREAM_TYPE_MAIN,i),r.set(yO.STREAM_TYPE_AUX,n),e.set(t,r)}this.mapInterval.push(e)}getLatestRemoteInboundStats(e,t,r){var i,n;const o=null===(i=this.mapInterval.getTail())||void 0===i||null===(n=i.get(e))||void 0===n?void 0:n.get(t);if(this.isFireFox){const t=r.split("_"),i=parseInt(t[1]),n=this.connectionsManagers.get(e).getMappingSsrcs(i),s=t[0].concat("_").concat(n).toString();return o&&o.get(s)}return o&&o.get(r)?o.get(r):null}getLatestStatsByTrackId(e,t,r){var i,n;const o=null===(i=this.mapInterval.getTail())||void 0===i||null===(n=i.get(e))||void 0===n?void 0:n.get(t);return o&&o.get(r)?o.get(r):null}getLatestReport(e,t){var r,i;return null===(r=this.mapInterval.getTail())||void 0===r||null===(i=r.get(e))||void 0===i?void 0:i.get(t)}getLatestStats(e,t,r){const i=this.getLatestReport(e,t);return this.getStatsBySsrcLabel(i,r,e)}getElementStats(e,t,r,i){var n,o;const s=null===(n=this.mapInterval.getElement(i))||void 0===n||null===(o=n.get(e))||void 0===o?void 0:o.get(t);return this.getStatsBySsrcLabel(s,r,e)}getStatsBySsrcLabel(e,t,r){if(!e)return null;if(this.isFireFox){const i=t.split("_"),n=parseInt(i[1]),o=this.connectionsManagers.get(r).getMappingSsrcs(n),s=i[0].concat("_").concat(o).toString();return e.get(s)}return e.get(t)}getLatestValue(e,t,r,i){const n=this.getLatestStats(e,t,r);return n?n[i]:null}getAllNumber(e,t,r,i){const n=this.mapInterval.size(),o=new Array(n);for(let s=0;sn&&(c+=a),a=0);return a>n&&(c+=a),c}execMyInterval(e,t){const r=()=>{this.gatherTimer=setTimeout((()=>{e(),r()}),t)};e(),r()}};class PO{constructor(e){i(this,"videoFreezeKey",Mw.isFirefox()?"packetsReceived":"framesReceived"),i(this,"mediaStatInfo",[]),i(this,"mediaStatDebugInfo",[]),i(this,"mediaStatSumInfo",[]),i(this,"mediaStatSumDebugInfo",[]),i(this,"ACSAddr",""),i(this,"SFUAddr",""),i(this,"lastSenderInfo",new Map),i(this,"lastSenderDebugInfo",new Map),i(this,"encryUserId",new Map),i(this,"remoteStreamInfo",[]),i(this,"audioPolicy",IO.USER_SUBSCRIBE_AUDIOPOLICY),i(this,"LocalStreamInfo",new Map),i(this,"auxsStreamInfo",new Map),i(this,"audioReceiveInfo",{audioReceivePackets:new Map,audioReceivePacketsLost:new Map,audioReceiveBytes:new Map}),i(this,"videoReceiveInfo",{videoReceivePackets:new Map,videoReceivePacketsLost:new Map,videoReceiveBytes:new Map,videoReceiveFrame:new Map}),i(this,"audioReceiveDebugInfo",{audioReceivePackets:new Map,audioReceivePacketsLost:new Map,audioReceiveBytes:new Map}),i(this,"videoReceiveDebugInfo",{videoReceivePackets:new Map,videoReceivePacketsLost:new Map,videoReceiveBytes:new Map,videoReceiveFrame:new Map}),i(this,"inBoundAudioSsrcInfos",[]),i(this,"audioPolicyLastCycle",IO.USER_SUBSCRIBE_AUDIOPOLICY),i(this,"audioStreamReceiverMap",new Map),i(this,"ssrcChangeCount",0),i(this,"audioStreamInfos",[]),i(this,"audioCount",0),i(this,"audioStreamAllInfos",[]),i(this,"audioAllCount",0),i(this,"audioStreamTop3Count",0),i(this,"module_","MediaStats"),i(this,"tempStat",{bytesSent:0,bytesReceived:0,sendBitrate:0,recvBitrate:0,rtt:0,upPktsLostRate:0,downPktsLostRate:0}),i(this,"stat",{bytesSent:0,bytesReceived:0,sendBitrate:0,recvBitrate:0,rtt:0,upPktsLostRate:0,downPktsLostRate:0}),i(this,"audioLevelInfo",{localAudio:new Map,remoteAudio:new Map,top3Audio:new Map}),i(this,"remoteUserMuteStatus",new Map),this.logger=e}setEncryInfo(e,t){this.encryUserId.set(e,t)}getEncryInfo(e){return this.encryUserId.get(e)}clearEncryUserId(){this.encryUserId.clear()}setRemoteUserManager(e){this.remoteUserManager=e}setStartSsrc(e){this.startSsrc=e}updateAudioLevel(e){if("local"===e.type){if(!this.audioLevelInfo.localAudio.get("local")){const e=[];this.audioLevelInfo.localAudio.set("local",e)}this.audioLevelInfo.localAudio.get("local").push(e.level)}else if("remoteTop3"===e.type){if(!this.audioLevelInfo.top3Audio.get("".concat(null==e?void 0:e.ssrc))){const t=[];this.audioLevelInfo.top3Audio.set("".concat(null==e?void 0:e.ssrc),t)}this.audioLevelInfo.top3Audio.get("".concat(null==e?void 0:e.ssrc)).push(e.level)}else{if(!this.audioLevelInfo.remoteAudio.get("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId))){const t=[];this.audioLevelInfo.remoteAudio.set("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId),t)}this.audioLevelInfo.remoteAudio.get("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId)).push(e.level)}}getAudioLevel(e,t,r){let i=0,n=0;return"local"===e&&this.audioLevelInfo.localAudio.get("local")?(this.audioLevelInfo.localAudio.get("local").forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.localAudio.clear()):"remoteTop3"===e&&this.audioLevelInfo.top3Audio.get("".concat(t))?(this.audioLevelInfo.top3Audio.get("".concat(t)).forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.top3Audio.clear()):"remote"===e&&this.audioLevelInfo.remoteAudio.get("".concat(t,"_").concat(r))&&(this.audioLevelInfo.remoteAudio.get("".concat(t,"_").concat(r)).forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.remoteAudio.clear()),0===n?0:Math.ceil(i/n)}setConnectionsManager(e){this.logger.info(this.module_,"setConnectionsManager"),this.connectionsManager=e}setSubscribeInfo(e){var t,r,i,n;if(!e)return;const o=this.remoteStreamInfo.find((t=>t.userId===e.userId));if(!o)return this.clearRemoteStreamInfoCache(e),void this.remoteStreamInfo.push(e);(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0&&e.mainStream.tracks.forEach((t=>{o.mainStream.tracks.find((e=>e.trackId===t.trackId))||(this.doClearRemoteStreamInfoCache(e,e.userId,t.cssrc),o.mainStream.tracks.push(t))})),(null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n?void 0:n.length)>0&&e.auxStream.tracks.forEach((t=>{o.auxStream.tracks.find((e=>e.trackId===t.trackId))||(this.doClearRemoteStreamInfoCache(e,e.userId,t.cssrc),o.auxStream.tracks.push(t))}))}doClearRemoteStreamInfoCache(e,t,r){let i=null;if(e.mainStream.tracks.forEach((e=>{e.cssrc===r&&(i=e.type)})),e.auxStream.tracks.forEach((e=>{e.cssrc===r&&(i=e.type)})),i===vO.TRACK_TYPE_AUDIO){const e="".concat(r,"-").concat(t);this.audioReceiveInfo.audioReceivePackets.delete(e),this.audioReceiveInfo.audioReceivePacketsLost.delete(e),this.audioReceiveInfo.audioReceiveBytes.delete(e)}else if(i===vO.TRACK_TYPE_VIDEO){const e="".concat(r,"-").concat(t);this.videoReceiveInfo.videoReceivePackets.delete(e),this.videoReceiveInfo.videoReceivePacketsLost.delete(e),this.videoReceiveInfo.videoReceiveBytes.delete(e),this.videoReceiveInfo.videoReceiveFrame.delete(e)}}clearRemoteStreamInfoCache(e){this.remoteStreamInfo.filter((t=>t.userId===e.userId)).forEach((t=>{this.clearRemoteStreamInfoCache4Stream(e,t.mainStream),this.clearRemoteStreamInfoCache4Stream(e,t.auxStream)}))}clearRemoteStreamInfoCache4Stream(e,t){t.tracks.forEach((t=>{const r=t.trackId,i=t.cssrc,n=e.userId;e.mainStream.tracks.forEach((t=>{t.cssrc===i&&t.trackId!==r&&this.doClearRemoteStreamInfoCache(e,n,i)}))}))}clearLocalStreamInfoCache(e){e&&this.LocalStreamInfo.forEach((t=>{e.ssrc===t.ssrc&&e.uid===t.uid&&e.streamId!==t.streamId&&this.lastSenderInfo.delete("".concat(e.ssrc,"-").concat(e.uid))}))}clearAuxsStreamInfoCache(e){e&&this.auxsStreamInfo.forEach((t=>{e.ssrc===t.ssrc&&e.uid===t.uid&&e.streamId!==t.streamId&&this.lastSenderInfo.delete("".concat(e.ssrc,"-").concat(e.uid))}))}setLocalMainStreamInfo(e,t){return!(!t||0===t.length)&&(this.LocalStreamInfo.clear(),t.forEach((t=>{const r={uid:e,streamId:"",ssrc:t.ssrc,type:t.type};t.type===vO.TRACK_TYPE_AUDIO?r.streamId=t.upstream.streamUid.toString():(r.streamId=t.upstream.streamUid.toString(),r.width=t.upstream.width,r.height=t.upstream.height,r.frame=t.upstream.fps),this.clearLocalStreamInfoCache(r),this.LocalStreamInfo.set(t.resolutionId,r)})),!0)}setLocalAuxsStreamInfo(e,t){if(!t)return!1;const r=Array.from(t.localTrackPublishInfos.values());return!!r&&(this.auxsStreamInfo.clear(),r.forEach((r=>{const i={uid:e,streamId:r.upstream.streamUid.toString(),ssrc:r.ssrc,type:r.type};r.type===vO.TRACK_TYPE_VIDEO&&(i.publishInfo={stream:t.localStream}),this.clearAuxsStreamInfoCache(i),this.auxsStreamInfo.set(r.resolutionId,i)})),!0)}deleteSubscribeInfo(e,t,r){if(r||t){if(t){const i=this.remoteStreamInfo.find((t=>t.userId===e));if(!i)return;const n=t===yO.STREAM_TYPE_MAIN?i.mainStream:i.auxStream;n.tracks=r?n.tracks.filter((e=>e.trackId!==r)):null}}else this.remoteStreamInfo=this.remoteStreamInfo.filter((t=>t.userId!==e))}setAudioPolicy(e){this.audioPolicyLastCycle=this.audioPolicy,this.audioPolicy=e,this.setAudioStreamInfo()}setSFUAddr(e){this.SFUAddr=e}setACSAddr(e){this.ACSAddr=e}leaveRoom(){this.mediaStatInfo=[]}getAudioPolicy(){return this.audioPolicy}getTransportMediaStats(){return this.stat}getMediaStatInfo(){const e=this.mediaStatInfo;return this.mediaStatInfo=[],e}getMediaStatSum(){const e=this.mediaStatSumInfo;return this.mediaStatSumInfo=[],e}getInBoundAudioSsrc(){const e=this.inBoundAudioSsrcInfos;return this.inBoundAudioSsrcInfos=[],e}async dealStats(){this.connectionsManager.isConnectionsExist()?(this.getAudioStreamInfo(),await this.getSenderInfo(!1),await this.getReceiverInfo(!1),this.stat.bytesSent+=this.tempStat.bytesSent,this.stat.bytesReceived+=this.tempStat.bytesReceived,this.stat.sendBitrate=this.tempStat.sendBitrate,this.stat.recvBitrate=this.tempStat.recvBitrate,this.clearTempStats()):this.logger.debug(this.module_,"peerConnection is undefined")}clearTempStats(){this.tempStat.bytesSent=0,this.tempStat.bytesReceived=0,this.tempStat.sendBitrate=0,this.tempStat.recvBitrate=0}clearMediaStatBytes(){this.stat.bytesSent=0,this.stat.bytesReceived=0}cleanAudioStreamInfos(){this.audioCount=this.audioStreamInfos.length,this.audioAllCount=this.audioStreamAllInfos.length,this.audioStreamInfos=[],this.audioStreamAllInfos=[]}updateAudioStreamInfos(e,t){if("add"===t){let t=0;this.remoteStreamInfo.forEach((r=>{if(e===r.userId){const e=r.mainStream.tracks.filter((e=>e.streamType===yO.STREAM_TYPE_MAIN&&e.type===vO.TRACK_TYPE_AUDIO));t=e.length>0?e[0].cssrc:0}}));const r={userid:e,audioSsrc:t};this.audioStreamInfos=this.audioStreamInfos.filter((r=>r.userid!=e||r.audioSsrc!=t)),this.audioStreamAllInfos=this.audioStreamAllInfos.filter((r=>r.userid!=e||r.audioSsrc!=t)),this.audioStreamInfos.push(r),this.audioStreamAllInfos.push(r)}"delete"!==t&&"removed"!==t||(this.audioStreamInfos=this.audioStreamInfos.filter((t=>t.userid!==e)),this.audioStreamAllInfos=this.audioStreamAllInfos.filter((t=>t.userid!==e))),this.audioPolicy!==IO.USER_SUBSCRIBE_AUDIOPOLICY&&this.audioCount===this.audioStreamInfos.length||this.ssrcChangeCount++,this.audioPolicy!==IO.TOPN_AUDIOPOLICY&&this.audioAllCount===this.audioStreamAllInfos.length||this.ssrcChangeCount++}updateAudioStreamTop3(e){this.audioStreamTop3CountTimer&&clearTimeout(this.audioStreamTop3CountTimer),this.audioStreamTop3CountTimer=setTimeout((()=>{this.audioStreamTop3Count=0}),4e3),this.audioStreamTop3Count=e}checkAudioStreamInfosIsExist(e,t){return 0!==this.audioStreamInfos.filter((r=>r.userid===e&&r.audioSsrc===t)).length}setAudioStreamInfo(){this.audioPolicy!==this.audioPolicyLastCycle&&(this.ssrcChangeCount=1,this.audioStreamReceiverMap.clear(),this.audioStreamTop3Count=0,this.audioReceiveInfo.audioReceiveBytes.clear(),this.audioReceiveInfo.audioReceivePackets.clear(),this.audioReceiveInfo.audioReceivePacketsLost.clear())}async getAudioStreamInfo(){this.audioPolicy===IO.TOPN_AUDIOPOLICY?await this.buildAudioStreamInfo3():this.audioPolicy===IO.USER_SUBSCRIBE_AUDIOPOLICY?await this.buildAudioStreamInfo2():this.logger.debug(this.module_,"mode 1 not uesed")}async buildAudioStreamInfo3(){const e=[],t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_STAT,access_addr:this.ACSAddr,sfu_addr:this.SFUAddr,audio_policy:this.audioPolicy,topn:3,audios_change_cnt:0,audios:e,no_stream_cnt:0};for(let n=0;n<3;n++){var r;const i=this.startSsrc+n,o="".concat(hC,"_").concat(i),s=OO.getLatestStats(null===(r=this.connectionsManager)||void 0===r?void 0:r.getConnectionId(),yO.STREAM_TYPE_MAIN,o);if(s){const r=this.connectionsManager.calcChangedStatistic(s.id,s.packetsReceived||0,["packetsReceived"])||s.packetsReceived,n=this.audioStreamReceiverMap.get(i)||0;let o=!0;0===r?o=!1:void 0===n?o=!0:r===n&&(o=!1),e.push({ssrc:i,userid:"",packet_cnt:r-n}),this.audioStreamReceiverMap.set(i,r),o||t.no_stream_cnt++}}const i=this.audioAllCount<3?this.audioAllCount:3;if(i<3){const e=t.no_stream_cnt-(3-i);t.no_stream_cnt=e<0?0:e}t.audios_change_cnt=this.ssrcChangeCount,this.inBoundAudioSsrcInfos.push(t)}async buildAudioStreamInfo2(){const e=[],t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_STAT,access_addr:this.ACSAddr,sfu_addr:this.SFUAddr,audio_policy:this.audioPolicy,topn:17,audios_change_cnt:0,audios:e,no_stream_cnt:0};this.remoteStreamInfo.every((r=>{var i;if(-1===this.audioStreamInfos.findIndex((e=>e.userid===r.userId)))return!0;const n=Array.from(r.mainStream.tracks.values()).find((e=>e.type===vO.TRACK_TYPE_AUDIO)),o="".concat(hC,"_").concat(null==n?void 0:n.cssrc),s=OO.getLatestStats(null===(i=this.connectionsManager)||void 0===i?void 0:i.getConnectionId(),yO.STREAM_TYPE_MAIN,o);if(r&&n&&s){const i=r.userId,o=this.connectionsManager.calcChangedStatistic(s.id,s.packetsReceived||0,["packetsReceived"])||s.packetsReceived,a=this.audioStreamReceiverMap.get(n.cssrc)||0;let c=!0;0===o?c=!1:void 0===a?c=!0:o===a&&(c=!1);const u=this.getEncryInfo(r.userId)||XR.secretString(r.userId)||"";e.push({ssrc:n.cssrc,userid:u,packet_cnt:o-a}),this.audioStreamReceiverMap.set(n.cssrc,o),!c&&this.checkAudioStreamInfosIsExist(i,n.cssrc)&&t.no_stream_cnt++}return!0})),t.audios_change_cnt=this.ssrcChangeCount,e.length>0&&this.inBoundAudioSsrcInfos.push(t)}async getVideoReceiverFrameDecodedMap(){const e=new Map;return await this.buildFrameDecodedMap(yO.STREAM_TYPE_MAIN,e),await this.buildFrameDecodedMap(yO.STREAM_TYPE_AUX,e),e}async buildFrameDecodedMap(e,t){const r=e===yO.STREAM_TYPE_AUX,i=this.connectionsManager.getReceivers(r?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN);for(let n=0;n{const n={};(r?i.auxStream.tracks:i.mainStream.tracks).forEach((o=>{var s;const a=OO.getLatestStats(null===(s=this.connectionsManager)||void 0===s?void 0:s.getConnectionId(),e,"".concat(fC,"_").concat(o.cssrc));if(a){n.userId=i.userId,n.isAux=r,n.decodedFrame=this.connectionsManager.calcChangedStatistic(a.id,a.framesDecoded||0,["framesDecoded"]);const e="".concat(i.userId,",").concat(r?"1":"0");t.get(e)||t.set(e,n)}}))}))}}async getReceiverInfo(e){const t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_SUM,real_band_width:0,bytes:0,pkt_loss:0},r={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_VIDEO_SUM,real_band_width:0,tmmbr:0,video_tmmbr:0,req_band_width:0,pkt_loss:0,jitter:0,frame_rate:0,first_frame_count:0,bytes:0},i={isAudio:!1,isVideo:!1};await this.buildReceiverInfo(yO.STREAM_TYPE_MAIN,t,r,i,e),await this.buildReceiverInfo(yO.STREAM_TYPE_AUX,t,r,i,e),i.isAudio&&(e?this.mediaStatSumDebugInfo.push(t):this.mediaStatSumInfo.push(t)),i.isVideo&&(e?this.mediaStatSumDebugInfo.push(r):this.mediaStatSumInfo.push(r))}async buildReceiverInfo(e,t,r,i,n){const o=e===yO.STREAM_TYPE_AUX,s={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO,streams:[]},a={timestamp:XR.getCurrentTimestamp(),event:o?ZC.QoS_AUX_DOWN_STREAM_VIDEO:ZC.QoS_DOWN_STREAM_VIDEO,qos_estimate:3,streams:[]};o||this.buildAudioReceiverInfo(s,t,n),this.buildVideoReceiverInfo(e,a,r,n),0!==a.streams.length&&(n?this.mediaStatDebugInfo.push(a):this.mediaStatInfo.push(a),i.isVideo=!0),0!==s.streams.length&&(n?this.mediaStatDebugInfo.push(s):this.mediaStatInfo.push(s),i.isAudio=!0)}checkMuteStatusIsChange(e){const t=this.remoteUserManager.checkSsrcIsMute(e),r=this.remoteUserMuteStatus.get(e),i=!t&&t===r;return this.remoteUserMuteStatus.set(e,t),i}buildAudioReceiverInfo(e,t,r){let i=null,n=null,o=null,s=0;if(r?(i=this.audioReceiveDebugInfo.audioReceivePackets,n=this.audioReceiveDebugInfo.audioReceivePacketsLost,o=this.audioReceiveDebugInfo.audioReceiveBytes,s=this.rtcStatsInteval):(i=this.audioReceiveInfo.audioReceivePackets,n=this.audioReceiveInfo.audioReceivePacketsLost,o=this.audioReceiveInfo.audioReceiveBytes,s=5),this.audioPolicy===IO.TOPN_AUDIOPOLICY){for(let u=0;u<3;u++){var a;const d={ssrc_uid:"",stream_uid:"",sfu_addr:"",dst_rcv_vel:0,dst_rcv_nel:0,bit_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,lost_pkt_cnt:0,srtp_decode_err:0,max_cont_lost_pkts:0,mos:0,jb_depth:0,play_err:0,play_total_time:5e3,freeze_loss_time:0,freeze_time:0,jitter90:0,jitter95:0,jitter100:0,tsm_count:0,ts_exp_cnt:0,ssrc_change_cnt:0,audio_pkt_error:0,audio_decode_error:0,dst_burst_pkt_lost_cnt:0,dst_burst_cnt:0,dst_burst_pkt_lost_rate:0,dst_audio_jb_discard_lost_rate:0,net_loss:0,rtp_loss:0,dst_mean_lost_rate:0,buffer_max_length:0,buffer_mean_length:0,net_ate_max_delay:0,net_ate_cur_delay:0,jb_max_num_delay:0,jb_cur_num_delay:0,pkt_recv_max_interval:0,pkt_recv_mean_interval:0,ui_sample_rate:0,ui_channels:0,en_codec_type:0,ui_total_pkt_loss:0,ui_buffer_total_length:0,ui_buffer_cal_cnt:0,ui_rec_pkt_cnt:0,i_channel_id:0,ui_dst_inc_bytes:0,ui_recv_redn_rate:0,ui_plc_count:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},l=this.startSsrc+u,h="".concat(hC,"_").concat(l),f=OO.getLatestStats(null===(a=this.connectionsManager)||void 0===a?void 0:a.getConnectionId(),yO.STREAM_TYPE_MAIN,h);if(f){d.ssrc_uid="".concat(l,"-").concat(l),d.stream_uid="STREAMUUID-".concat(l),d.sfu_addr=this.SFUAddr,this.connectionsManager.calcChangedStatistic(f.id,f,["bytesReceived","packetsReceived","packetsLost"]);const e=f.bytesReceived||0;o.get(l)||o.set(l,0),d.bytes=en.get(l)?a-n.get(l):0;d.lost_pkt_cnt=u;const p=t{var o;const s={ssrc_uid:"",stream_uid:"",sfu_addr:"",dst_rcv_vel:0,dst_rcv_nel:0,bit_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,lost_pkt_cnt:0,srtp_decode_err:0,max_cont_lost_pkts:0,mos:0,jb_depth:0,play_err:0,play_total_time:5e3,freeze_loss_time:0,freeze_time:0,jitter90:0,jitter95:0,jitter100:0,tsm_count:0,ts_exp_cnt:0,ssrc_change_cnt:0,audio_pkt_error:0,audio_decode_error:0,dst_burst_pkt_lost_cnt:0,dst_burst_cnt:0,dst_burst_pkt_lost_rate:0,dst_audio_jb_discard_lost_rate:0,net_loss:0,rtp_loss:0,dst_mean_lost_rate:0,buffer_max_length:0,buffer_mean_length:0,net_ate_max_delay:0,net_ate_cur_delay:0,jb_max_num_delay:0,jb_cur_num_delay:0,pkt_recv_max_interval:0,pkt_recv_mean_interval:0,ui_sample_rate:0,ui_channels:0,en_codec_type:0,ui_total_pkt_loss:0,ui_buffer_total_length:0,ui_buffer_cal_cnt:0,ui_rec_pkt_cnt:0,i_channel_id:0,ui_dst_inc_bytes:0,ui_recv_redn_rate:0,ui_plc_count:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},a=Array.from(n.mainStream.tracks.values()).find((e=>e.type===vO.TRACK_TYPE_AUDIO&&e.state===CO.normal)),c="".concat(hC,"_").concat(null==a?void 0:a.cssrc),u=OO.getLatestStats(null===(o=this.connectionsManager)||void 0===o?void 0:o.getConnectionId(),yO.STREAM_TYPE_MAIN,c);if(n&&a&&u){const t=this.getEncryInfo(n.userId)||XR.secretString(n.userId),r="".concat(a.cssrc,"-").concat(t);s.ssrc_uid=r,s.stream_uid="".concat(a.trackId)||"STREAMUUID-".concat(a.cssrc),s.sfu_addr=this.SFUAddr,this.connectionsManager.calcChangedStatistic(u.id,u,["bytesReceived","packetsReceived","packetsLost"]);const o=u.bytesReceived||0;e.audioReceiveBytes.get(r)||e.audioReceiveBytes.set(r,0),s.bytes=oe.audioReceivePacketsLost.get(r)?h-e.audioReceivePacketsLost.get(r):0;s.lost_pkt_cnt=f;const p=l{(e===yO.STREAM_TYPE_MAIN?d.mainStream.tracks.filter((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.state===CO.normal)):d.auxStream.tracks.filter((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.state===CO.normal))).forEach((l=>{var h,f;const p={ssrc_uid:"",stream_uid:"",sfu_addr:"",expect_pic_w:0,expect_pic_h:0,image_width:0,image_height:0,roc:0,buffered:0,bit_rate:0,frame_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,jb_depth:0,fir_req_cnt:0,parse_srtp_fail:0,fir_frame_cnt:0,freeze_200ms_cnt:0,freeze_600ms_cnt:0,freeze_1000ms_cnt:0,freeze_200ms_time:0,freeze_600ms_time:0,freeze_1000ms_time:0,dec_key_frame_cnt:0,dec_key_frame_size:0,max_cont_lost_pkts:0,freeze_cnt:0,act_dec_runtime:5e3,ui_first_rcv_seq:0,ui_max_decode_delay:0,ui_min_decode_delay:0,ui_mean_decode_delay:0,ui_current_decode_delay:0,ui_max_channel_decode_delay:0,ui_min_channel_decode_delay:0,ui_mean_channel_decode_delay:0,ui_current_channel_decode_delay:0,ui_abnormal_pkt_count:0,ui_codec_pt_error:0,ui_no_dec_data_cnt:0,jb_discard_bytes:0,net_lost_pkt_counts:0,rcv_frame_counts:0,dec_bytes_out:0,rcv_red_bytes:0,dec_delay_over_time_cnt:0,channel_decode_over_time_cnt:0,dec_non_key_frame_size:0,dec_non_key_frame_cnt:0,us_loss_frame_rate:0,ui_pkt_rate:0,us_residual_pkt_loss:0,ul_decoder_start_time:0,us_mean_pkt_loss:0,ui_mean_rtt:0,e_dec_protocol:0,ui_distribute_tmmbr:0,frame_fail_cnt:0,advanced_frame_count:0,base_frame_count:0,before_postprocess_frames_rate:0,after_postprocess_frames_rate:0,red_rate:0,recover_rate:0,jb_listpacket_num:0,not_recv_pkt_cnt:0,not_recv_pkt_total_time:0,nack_request_cnt:0,send_key_request_cnt:0,jb_jitter:0,recv_frame_rate:0,recv_base_layer_frame_cnt:0,recv_mid_layer_frame_cnt:0,recv_out_layer_frame_cnt:0,jb_total_frame_cnt:0,jb_listframe_num:0,output_total_freezetime:0,output_freeze_cnt:0,ref_frame_error_cnt:0,force_out4_key_cnt:0,force_out4_struct_cnt:0,current_output_diftime:0,current_complete_type:0,jb_base_layer_frame_num:0,jb_mid_layer_frame_num:0,jb_out_layer_frame_num:0,freeze_400ms_cnt:0,freeze_400ms_time:0,freeze_200ms_rate:0,freeze_400ms_rate:0,freeze_600ms_rate:0,freeze_1000ms_rate:0,freeze_loss_time:0,first_frame_cnt:0,p_frame_cnt:0,lost_pkt_cnt:0,play_err:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},m="".concat(fC,"_").concat(l.cssrc),g=OO.getLatestStats(null===(h=this.connectionsManager)||void 0===h?void 0:h.getConnectionId(),e,m);if(g){const t=this.getEncryInfo(d.userId)||XR.secretString(d.userId),r="".concat(l.cssrc,"-").concat(t);p.ssrc_uid=r,this.connectionsManager.calcChangedStatistic(g.id,g,["keyFramesDecoded","packetsReceived","packetsLost","bytesReceived","framesDecoded","freezeCount"]),this.buildCommonVideoRecvInfo(p,g,l),this.buildBitRateVideoRecvInfo(g,r,o,s,p);const h=XR.getValue(g.bytesReceived,0),f=a.get(r)||0;p.bytes=hc?s-c:0;n.real_lost_pkt_cnt=u;const d=oe.type!==vO.TRACK_TYPE_AUDIO)):Array.from(this.LocalStreamInfo.values());if(0===c.length)return;const u=c.find((e=>e.type===vO.TRACK_TYPE_AUDIO)),d=c.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)),l=n?this.rtcStatsInteval:5;this.buildAudioSenderInfo(u,a,n),a.ssrc_uid&&(t.real_band_width+=Math.round(a.bytes/(1024*l)*8),i.isAudio=!0,s.push(a)),null==d||d.forEach((t=>{const s={ssrc_uid:"",stream_uid:"",sfu_addr:"",expect_pic_w:0,expect_pic_h:0,expect_frame_rate:0,image_width:0,image_height:0,frame_rate:0,bit_rate:0,max_cont_loss:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,roc:0,first_req_count:0,first_frame_count:0,frame_count:0,redn_rate:0,ui_first_send_seq:0,ui_no_ref_redundance_rate:0,ui_enc_max_bit_rate_set:0,ui_enc_min_bit_rate_set:0,ui_enc_current_bit_rate_set:0,ui_max_encode_delay:0,ui_min_encode_delay:0,ui_mean_encode_delay:0,ui_current_encode_delay:0,ui_buffer_data:0,ui_snd_fir_frame_key_count:0,ui_snd_fir_frame_arq_count:0,ui_snd_fir_frame_period_count:0,ui_max_channel_encode_delay:0,ui_min_channel_encode_delay:0,ui_mean_channel_encode_delay:0,ui_current_channel_encode_delay:0,ui_enc_frame_counts:0,ui_enc_bytes_out:0,ui_estimate_bitrate:0,ui_red_bytes_out:0,ui_nack_bytes_out:0,ui_enc_over_time_cnt:0,ui_enc_delay_over_time_cnt:0,ui_channel_encode_over_time_cnt:0,ui_before_pre_process_frm_cnt:0,ui_after_pre_process_frm_cnt:0,repeat_red_pkt_count:0,usable_bitrate:0,available_enc_bitrate:0,send_pkt_hungry_cnt:0,send_buffer_frm_cnt:0,advanced_frame_cnt:0,base_frame_cnt:0,avg_pre_process_time_in_period:0,max_pre_process_time:0,before_encode_lost_frm_cnt:0,us_sent_mean_lost_rate:0,ui_mean_r_t_t:0,ui_cumulative_lost:0,ui_extended_max_seq_num:0,ui_pkt_rate:0,ui_send_bit_rate:0,f_key_redundance_rate:0,f_ref_redundance_rate:0,f_no_ref_redundance_rate:0,e_enc_protocol:0,before_encode_frames_rate:0,before_send_frames_rate:0,after_send_frames_rate:0,data_cache_bytes:0,input_frame_cnt:0,input_pacing_pkt_cnt:0,input_pacing_fec_pkt_cnt:0,input_pacing_arq_pkt_cnt:0,send_fec_pkt_cnt:0,send_arq_pkt_cnt:0,nack_not_rsp_for_not_find_cnt:0,nack_not_rsp_for_key_cnt:0,nack_not_rsp_for_rtt_cnt:0,nack_not_rsp_for_time_cnt:0,nack_not_rsp_for_bw_cnt:0,deliver_red_rate:0,output_frame_cnt:0,estimate_bit_rate:0,tmmbr:0,p_frame_count:0,key_frame_count:0,bad_pkt_cnt:0,qos_estimate:3};this.buildVideoSenderInfo(t,s,e,n),s.ssrc_uid&&(r.real_band_width+=Math.round(s.bytes/(1024*l)*8),i.isVideo=!0,o.push(s))}));const h=this.getConnectionRemb(e);if(r.video_tmmbr=h>0?Math.round(h/1024):0,r.tmmbr+=r.video_tmmbr,s.length>0){const e={timestamp:XR.getCurrentTimestamp()};e.event=ZC.QoS_UP_STREAM_AUDIO,e.streams=s,n?this.mediaStatDebugInfo.push(e):this.mediaStatInfo.push(e)}if(o.length>0){const t={timestamp:XR.getCurrentTimestamp()};t.event=e?ZC.QoS_AUX_UP_STREAM_VIDEO:ZC.QoS_UP_STREAM_VIDEO,t.streams=o,n?this.mediaStatDebugInfo.push(t):this.mediaStatInfo.push(t)}}buildAudioSenderInfo(e,t,r){var i,n;if(!e)return;const o=r?this.lastSenderDebugInfo:this.lastSenderInfo,s=r?this.rtcStatsInteval:5,a=o.get("".concat(e.ssrc,"-").concat(e.uid))||{audioSendPackets:0,audioSendPacketsLost:0,audioSendBytes:0,videoSendPackets:0,videoSendPacketsLost:0,videoSendBytes:0};let c="".concat(pC,"_").concat(e.ssrc),u=OO.getLatestStats(null===(i=this.connectionsManager)||void 0===i?void 0:i.getConnectionId(),yO.STREAM_TYPE_MAIN,c);if(u){const i=this.getEncryInfo(e.uid)||XR.secretString(e.uid);t.ssrc_uid="".concat(e.ssrc,"-").concat(i),t.stream_uid=e.streamId,t.sfu_addr=this.SFUAddr;const n=u.bytesSent||0;t.bytes=na.audioSendPacketsLost?e-a.audioSendPacketsLost:0,i=t.pkts;t.pkt_loss=i>0?Math.round(r/(i+r)*100):0,a.audioSendPacketsLost=e}o.set("".concat(e.ssrc,"-").concat(e.uid),a)}addExpectInfo(e,t){t.expect_pic_w=(null==e?void 0:e.width)||0,t.expect_pic_h=(null==e?void 0:e.height)||0,t.expect_frame_rate=(null==e?void 0:e.frame)||0}addRembInfo(e,t){const r=this.getConnectionRemb(e);t.usable_bitrate=r>0?Math.round(r/1024):0}getConnectionRemb(e){let t=0;return this.connectionsManager.isConnectionsExist()?(t+=e?this.getRemb(yO.STREAM_TYPE_AUX):this.getRemb(yO.STREAM_TYPE_MAIN),t):t}getRemb(e){let t=0;try{const r=OO.getLatestReport(this.connectionsManager.getConnectionId(),e);if(r){const e=r.get("candidate-pair");e&&Object.prototype.hasOwnProperty.call(e,"availableOutgoingBitrate")&&(t=e.availableOutgoingBitrate||0)}}catch(jN){this.logger.error(this.module_,"getRemb failed",jN)}return t}buildVideoSenderInfo(e,t,r,i){var n,o;if(!e)return;const s=i?this.lastSenderDebugInfo:this.lastSenderInfo,a=i?this.rtcStatsInteval:5,c=s.get("".concat(e.ssrc,"-").concat(e.uid))||{audioSendPackets:0,audioSendPacketsLost:0,audioSendBytes:0,videoSendPackets:0,videoSendPacketsLost:0,videoSendBytes:0};this.addExpectInfo(e,t),this.addRembInfo(r,t);const u="".concat(mC,"_").concat(e.ssrc),d=OO.getLatestStats(null===(n=this.connectionsManager)||void 0===n?void 0:n.getConnectionId(),r?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,u);if(d){const n=this.getEncryInfo(e.uid)||XR.secretString(e.uid);t.ssrc_uid="".concat(e.ssrc,"-").concat(n),t.stream_uid=e.streamId,t.sfu_addr=this.SFUAddr,PO.buildCommonVideoSendInfo(t,d,e,r);const o=XR.getValue(d.bytesSent,0);t.bytes=oc.videoSendPacketsLost?e-c.videoSendPacketsLost:0,i=t.pkts;t.pkt_loss=Math.round(r/(i+r)*100)}else t.pkt_loss=0;c.videoSendPacketsLost=e,t.rtt=Math.round(1e3*(h.roundTripTime||0))}s.set("".concat(e.ssrc,"-").concat(e.uid),c)}static buildCommonVideoSendInfo(e,t,r,i){if(i){var n;const t=null===(n=r.publishInfo)||void 0===n?void 0:n.stream;e.image_width=(null==t?void 0:t.getScreenWidth())||0,e.image_height=(null==t?void 0:t.getScreenHeight())||0,e.frame_rate=(null==t?void 0:t.getScreenFrameRate())||0}else e.image_width=(null==r?void 0:r.width)||0,e.image_height=(null==r?void 0:r.height)||0,e.frame_rate=(null==r?void 0:r.frame)||0;e.image_width=t.frameWidth||0,e.image_height=t.frameHeight||0,e.frame_rate=Math.round(t.framesPerSecond||0),e.first_frame_count=t.firCount||0,e.frame_count=t.framesSent||0}async buildRtcStatsDebugInfo(e){this.rtcStatsInteval=e;const t={mediaStatsDebugInfo:null,mediaStatsSumDebugInfo:null};return this.connectionsManager.isConnectionsExist()?(await this.getSenderInfo(!0),await this.getReceiverInfo(!0),t.mediaStatsDebugInfo=this.mediaStatDebugInfo,t.mediaStatsSumDebugInfo=this.mediaStatSumDebugInfo,this.mediaStatDebugInfo=[],this.mediaStatSumDebugInfo=[],t):(this.logger.debug(this.module_,"peerConnection is undefined"),t)}}class MO{constructor(e,t){i(this,"eventInfoMap",new Map),i(this,"reqInfoMap",new Map),i(this,"sfuInfo",{ipAddress:"",videoPort:0,audioPort:0,auxPort:0}),i(this,"deviceInfo",{audioOutputId:void 0,audioInputId:void 0,videoInputId:void 0}),i(this,"mediaOpsData",[]),i(this,"signalSendMsgs",[]),i(this,"signalReceiveMsgs",[]),i(this,"parentSpanIdMap",new Map),i(this,"spanIdMap",new Map),this.logger=e,this.mediaStats=new PO(e),this.module_="RTCStat",this.commInfo={},this.commInfo.instance_id=XR.getDeviceID(),t&&(this.commInfo.appid=t.appId,this.commInfo.domain=t.domain),this.commInfo.sdk_name="hwwebrtc",this.commInfo.corp="",this.commInfo.service_name="rtc",this.commInfo.operator="",this.commInfo.sdk_version="web-".concat(uA,"-").concat(dA),this.signalSendMsgs.push("BYE"),this.signalSendMsgs.push("PUSH_STREAM_RES_ALL"),this.signalSendMsgs.push("APPLY_PUSH_STREAM"),this.signalSendMsgs.push("AUDIO_POLICY"),this.signalSendMsgs.push("SWITCH_ROLE"),this.signalSendMsgs.push("CHANGE_STREAM_STATUS"),this.signalSendMsgs.push("APP_DATA"),this.signalSendMsgs.push("ENABLE_AUDIO"),this.signalSendMsgs.push("DISABLE_AUDIO"),this.signalSendMsgs.push("ENABLE_VIDEO"),this.signalSendMsgs.push("DISABLE_VIDEO"),this.signalSendMsgs.push("JOIN_ROOM"),this.signalSendMsgs.push("EXIT_ROOM"),this.signalSendMsgs.push("PING"),this.signalSendMsgs.push("PUSH_STREAM_RESULT"),this.signalSendMsgs.push("GET_ROOM_USERINFO"),this.signalSendMsgs.push("QUERY_PUBLISH"),this.signalSendMsgs.push("START_PUBLISH"),this.signalSendMsgs.push("STOP_PUSH_STREAM"),this.signalSendMsgs.push("STOP_PUBLISH"),this.signalSendMsgs.push("CANCEL_SUBS_STREAM"),this.signalSendMsgs.push("SUBS_STREAM"),this.signalSendMsgs.push("UPDATE_PUBLISH"),this.signalReceiveMsgs.push("WATCH_STREAM_NOTIFY")}static isStatiscEnable(){return"off"!==SO.getParameter(uO)}addCommInfo(e){return e.timestamp=XR.getCurrentTimestamp(),e.trace_id=this.commInfo.trace_id||"",e.instance_id=this.commInfo.instance_id,e.room_uid=this.commInfo.room_uid||"",e.domain=this.commInfo.domain||"",e.event_name=(null==e?void 0:e.event_name)||"",e.appid=this.commInfo.appid||"",e.corp=this.commInfo.corp||"",e.room_id=this.commInfo.room_id||"",e.user_id=this.getMediaStat().getEncryInfo(this.commInfo.user_id)||XR.secretString(this.commInfo.user_id)||"",e.sdk_version=this.commInfo.sdk_version||"",e.sdk_name=this.commInfo.sdk_name||"",e.service_name=this.commInfo.service_name||"",e.operator=this.commInfo.operator||"",e.net_type=XR.getNetworkType()||"",e.country="",e.province="",e.city="",e}setRemoteUserManager(e){this.remoteUserManager=e,this.mediaStats.setRemoteUserManager(e)}clearMediaStatBytes(){this.mediaStats.clearMediaStatBytes()}async collectReceiverDecodedFrameMap(){return this.mediaStats.getVideoReceiverFrameDecodedMap()}setLocalUserInfo(e){this.commInfo.room_id=e.roomId,this.commInfo.user_id=e.userId,this.user=e}setTraceInfo(e){this.commInfo.trace_id=e}setRoomUid(e){this.commInfo.room_uid=e}setSFUAddress(e){this.sfuInfo=e,e.ipAddress&&this.mediaStats.setSFUAddr(e.ipAddress)}getMediaStat(){return this.mediaStats}leaveRoom(){this.mediaCollectionTimer&&clearTimeout(this.mediaCollectionTimer),this.mediaStats.leaveRoom()}startMediaCollector(){clearTimeout(this.mediaCollectionTimer),this.mediaCollectionTimer=setTimeout((async()=>{try{await this.mediaStats.dealStats(),this.setMediaStatInfo(),this.setMediaStatSumInfo(),this.setInBoundAudioSsrcInfos(),cO.addRecords(this.mediaOpsData),this.mediaOpsData.length=0}catch(jN){this.logger.error(this.module_,"startMediaCollector failed ".concat(jN))}finally{this.startMediaCollector()}}),5e3)}reportAudioMuteInfo(e,t){const r=t?1:3;let i;i=1===e?zC.INPUT_AUDIO:zC.OUTPUT_AUDIO,this.reportSwitchDevicesInfo(i,this.deviceInfo.audioInputId,0,r)}reportVideoMuteInfo(e,t){const r=t?4:5;this.reportSwitchDevicesInfo(zC.INPUT_VIDEO,this.deviceInfo.videoInputId,0,r)}async setDeviceStatusInfo(){(async function(){return new Promise(((e,t)=>{navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices||t(new qc(Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES)),navigator.mediaDevices.enumerateDevices().then((r=>{if(r&&0!==r.length){const t={};r.forEach((e=>{"default"!==e.deviceId&&"communications"!==e.deviceId&&(t[e.kind]=[...t[e.kind]||[],e])})),e(t)}else t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES))})).catch((e=>{t(e)}))}))})().then((e=>{this.setSpeakerDeviceInfo(e.audiooutput||[]),this.setCameraDeviceInfo(e.videoinput||[]),this.setMicrophoneDeviceInfo(e.audioinput||[])})).catch((e=>{this.logger.error(this.module_,"getRTCDeviceGroups failed ".concat(e))}))}recordUploadRequsetInfo(e){if(null!=e&&e.type&&"PING"!==e.type)switch(this.reqInfoMap.set(e.requestId,e),e.type){case"JOIN_ROOM":e.eventId=$C.EVENT_JOIN_ROOM,this.eventInfoMap.set(e.eventId,e);break;case"EXIT_ROOM":e.eventId=$C.EVENT_LEAVE_ROOM,this.eventInfoMap.set(e.eventId,e);break;case"SWITCH_ROLE":e.eventId=$C.EVENT_SWITCH_ROLE,this.eventInfoMap.set(e.eventId,e);break;case"PUSH_STREAM_RES_ALL":if(e.videoStreams&&e.videoStreams.length>0){e.videoStreams.find((e=>(null==e?void 0:e.content)===CC.desktop))&&(e.eventId=$C.EVENT_SEND_AUX_STREAM,this.eventInfoMap.set(e.eventId,e))}}}getDownloadRequestInfo(e){if(null==e||!e.requestId)return"";if("PONG"===e.resultMessage)return"PONG";const t=this.reqInfoMap.get(e.requestId);return t&&(null==t?void 0:t.type)||""}recordDownloadRequestInfo(e){if(null==e||!e.requestId)return;if("PONG"===e.resultMessage)return;const t=this.reqInfoMap.get(e.requestId);if(t){switch(this.reportSignalRepForServer2Web(t,e),t.type){case"SUBS_STREAM":t.videoUpstreams&&this.reportVideoSub(t.videoSubType,t.requestId,t.videoUpstreams,e.resultCode,e.resultMessage),t.audioUpstreams&&this.reportAudioSub(t.audioSubType,t.requestId,t.audioUpstreams,e.resultCode);break;case"PUSH_STREAM_RES_ALL":t.videoStreams&&t.videoStreams.length>0&&this.reportUpStreamVideoInfo(t.videoStreams,t.requestId,e.resultCode);break;case"AUDIO_POLICY":this.reportAudioPolicyInfo(t.audioPolicy,t.requestId,e.resultCode)}this.reqInfoMap.delete(e.requestId)}}setMediaStatInfo(){const e=this.mediaStats.getMediaStatInfo()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setMediaStatSumInfo(){const e=this.mediaStats.getMediaStatSum()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setInBoundAudioSsrcInfos(){const e=this.mediaStats.getInBoundAudioSsrc()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setRequestId(e){const t=this.eventInfoMap.get(e.event);return t&&(e.request_id=t.requestId),this}transformJoinInfoResult(e){if(!e&&0!==e)return cA.INTERNAL_ERROR;let t=cA.INTERNAL_ERROR;switch(e){case Gc.RTC_ERR_CODE_SUCCESS:t=cA.SUCCESS;break;case Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED:case Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED:case Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT:case Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT:case Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR:case Gc.RTC_ERR_CODE_STATUS_ERROR:t=cA.NETWORK_CONNECT_ERROR;break;case Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL:case Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN:t=cA.SERVER_ERROR;break;case Gc.RTC_ERR_CODE_INVALID_PARAMETER:t=cA.INTERNAL_ERROR}return t}reportJoinInfo(e,t,r,i,n){var o,s;this.getMediaStat().setACSAddr(t);const a={};a.event=$C.EVENT_JOIN_ROOM,a.access_addr=t,a.sfu_addr=this.sfuInfo.ipAddress,a.aport=this.sfuInfo.audioPort,a.vport=this.sfuInfo.videoPort,this.setRequestId(a),a.result=this.transformJoinInfoResult(e),a.platform="web-"+XR.getPlatform(),a.user_agent="web-"+XR.getUserAgent(),a.role=null===(o=this.user)||void 0===o?void 0:o.role,a.join_qos=JSON.stringify(i||{}),a.is_rejoin=r?1:0,a.nick_name=XR.shieldNickname((null===(s=this.user)||void 0===s?void 0:s.userName)||""),a.time_diff_server=0,a.failMessage="".concat(e||" ").concat(n||" "),this.addCommInfo(a),this.joinTime=a.timestamp,this.eventInfoMap.delete($C.EVENT_JOIN_ROOM),cO.reportRecords([a])}reportRelayJoinInfo(e){var t;const r={};r.event=$C.EVENT_JOIN_ROOM,r.access_addr=e.acsAddr,r.sfu_addr=this.sfuInfo.ipAddress,r.aport=this.sfuInfo.audioPort,r.vport=this.sfuInfo.videoPort,r.request_id=e.requestId,r.result=this.transformJoinInfoResult(e.code),r.platform="web-"+XR.getPlatform(),r.user_agent="web-"+XR.getUserAgent(),r.role=e.role,r.join_qos=JSON.stringify({}),r.is_rejoin=0,r.nick_name=XR.shieldNickname((null===(t=this.user)||void 0===t?void 0:t.userName)||""),r.time_diff_server=0,r.failMessage="".concat(e.code||" ").concat(e.failMessage||" "),this.addCommInfo(r),r.trace_id=e.traceId,r.room_id=e.roomId,r.room_uid=String(e.roomUid),cO.reportRecords([r])}reportRelayLeavInfo(e){const t={};t.event=$C.EVENT_LEAVE_ROOM,t.reason=0,t.result=e.code,t.a_snd_lost_mean=0,t.v_snd_lost_mean=0,t.a_snd_band_width_mean=0,t.v_snd_band_width_mean=0,t.a_snd_rtt_mean=0,t.a_recv_rtt_mean=0,t.v_snd_rtt_mean=0,t.v_recv_rtt_mean=0,t.a_recv_lost_mean=0,t.v_recv_lost_mean=0,t.a_recv_band_width_mean=0,t.v_recv_band_width_mean=0,t.freeze_200ms_cnt=0,t.freeze_600ms_cnt=0,t.freeze_1000ms_cnt=0,t.stut_time_mean=0,t.freeze_400ms_cnt=0,t.freeze_200ms_rate=0,t.freeze_400ms_rate=0,t.freeze_600ms_rate=0,t.freeze_1000ms_rate=0,t.v_snd_frame_rate=0,t.v_snd_pkt_rate=0,t.a_snd_pkt_rate=0,t.v_recv_frame_rate=0,t.v_recv_pkt_rate=0,t.a_recv_pkt_rate=0,t.v_snd_jitter=0,t.v_recv_jitter=0,this.addCommInfo(t),t.trace_id=e.traceId,t.room_id=e.roomId,t.room_uid=String(e.roomUid),t.request_id=e.requestId,t.elapsed=0,cO.reportRecords([t])}reportLeavInfo(e){const t={};t.event=$C.EVENT_LEAVE_ROOM,t.reason=0,t.result=e,t.a_snd_lost_mean=0,t.v_snd_lost_mean=0,t.a_snd_band_width_mean=0,t.v_snd_band_width_mean=0,t.a_snd_rtt_mean=0,t.a_recv_rtt_mean=0,t.v_snd_rtt_mean=0,t.v_recv_rtt_mean=0,t.a_recv_lost_mean=0,t.v_recv_lost_mean=0,t.a_recv_band_width_mean=0,t.v_recv_band_width_mean=0,t.freeze_200ms_cnt=0,t.freeze_600ms_cnt=0,t.freeze_1000ms_cnt=0,t.stut_time_mean=0,t.freeze_400ms_cnt=0,t.freeze_200ms_rate=0,t.freeze_400ms_rate=0,t.freeze_600ms_rate=0,t.freeze_1000ms_rate=0,t.v_snd_frame_rate=0,t.v_snd_pkt_rate=0,t.a_snd_pkt_rate=0,t.v_recv_frame_rate=0,t.v_recv_pkt_rate=0,t.a_recv_pkt_rate=0,t.v_snd_jitter=0,t.v_recv_jitter=0,t.elapsed=(XR.getCurrentTimestamp()-this.joinTime)/1e3,this.addCommInfo(t),this.setRequestId(t),this.eventInfoMap.delete($C.EVENT_LEAVE_ROOM),cO.reportRecords([t])}reportVideoSub(e,t,r,i,n){const o=[],s=[],a=[],c=[],u=[];null==r||r.forEach((e=>{const t=this.getMediaStat().getEncryInfo(e.pUserId)||XR.secretString(e.pUserId)||"";s.push(t),o.push(e.pSsrcId),u.push((null==e?void 0:e.code)||0);const r=this.remoteUserManager.getStreamInfoByPStreamUid(e.pStreamUid);if(r){const e=wO.getResolutionType(r.width,r.height);a.push(e&&e.toUpperCase().replace("-",""))}else this.logger.warn(this.module_,"Can not getStreamInfoByPStreamUid for reportVideoSub");c.push(String(e.pStreamUid))}));const d={event:$C.EVENT_WATCH,action:aA[e],request_id:t,ssrc_list:o.join(","),stream_uid_list:c.join(","),uid_list:s.join(","),img_list:a.join(","),reasonList:u.join(","),result:i,failMessage:0===i?"":n};this.addCommInfo(d),cO.reportRecords([d])}reportSwitchDevicesInfo(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:6;e===zC.OUTPUT_AUDIO?this.deviceInfo.audioOutputId=t:e==zC.INPUT_AUDIO?this.deviceInfo.audioInputId=t:e===zC.INPUT_VIDEO&&(this.deviceInfo.videoInputId=t);const n={event:$C.EVENT_SWITCH_DEVICE,type:e,name:t,result:r,opt:i};this.addCommInfo(n),cO.addRecord(n)}reportSwitchRoleInfo(e,t){const r={event:$C.EVENT_SWITCH_ROLE,role:e,result:t};this.setRequestId(r),this.addCommInfo(r),cO.addRecord(r)}reportStartSendMediaStream(e,t){const r={event:$C.EVENT_SEND_MEDIA,type:e,opt:t};this.addCommInfo(r),cO.reportRecords([r])}setMediaCaptureSucc(e,t){const r={event:$C.EVENT_START_MEDIA,type:e,dev_name:t};this.addCommInfo(r),cO.addRecord(r)}reportAuxiliaryStreamShareInfo(e,t){const r={event:$C.EVENT_SEND_AUX_STREAM,action:e,result:t};this.setRequestId(r),this.addCommInfo(r),cO.reportRecords([r])}setAudioSubscribeInfo(e,t,r){const i=[];let n;null==e||e.forEach((e=>{const t={uid:this.getMediaStat().getEncryInfo(null==e?void 0:e.userid)||XR.secretString(null==e?void 0:e.userid)||"",ssrc:(null==e?void 0:e.ssrc)||0};i.push(t),n=e.action-1}));const o={event:$C.EVENT_SUBSCIBE,request_id:t,policy:this.getMediaStat().getAudioPolicy(),streams:i,action:n,result:r};this.addCommInfo(o),cO.reportRecords([o])}reportAudioSub(e,t,r,i){const n=[];null==r||r.forEach((e=>{const t={uid:this.getMediaStat().getEncryInfo(null==e?void 0:e.pUserId)||XR.secretString(null==e?void 0:e.pUserId)||"",ssrc:(null==e?void 0:e.pSsrcId)||0,reason:(null==e?void 0:e.code)||0};n.push(t)}));const o={event:$C.EVENT_SUBSCIBE,request_id:t,policy:this.getMediaStat().getAudioPolicy(),streams:n,action:e,result:i};this.addCommInfo(o),cO.reportRecords([o])}setConnectionStatusInfo(e,t){const r={timestamp:0,event:$C.EVENT_CONNECTION_CHANNEL_STATUS,type:t,on:e};this.addCommInfo(r),cO.reportRecords([r])}reportUpStreamVideoInfo(e,t,r){const i=[],n=[];e.forEach((e=>{n.push(wO.getResolution(e.width,e.height)),i.push("".concat(e.width,"*").concat(e.height))}));const o={event:$C.EVENT_SET_UP_STREAM,request_id:t,resolution_name_list:n.join(","),width_height_list:i.join(","),result:0===r?GC.SUCCESS:GC.FAIL};this.addCommInfo(o),cO.addRecord(o)}reportAudioPolicyInfo(e,t,r){const i={event:$C.EVENT_SET_AUDIO_POLICY,request_id:t,policy:e,result:r,topn:e===IO.TOPN_AUDIOPOLICY?3:17};this.addCommInfo(i),cO.addRecord(i)}setSysBasicInfo(){const e={event:eA.DEVICE_RT_SYSTEM,device_cpu:0,app_cpu:0,mem_ratio:0};this.addCommInfo(e),cO.addRecord(e)}setCameraInfo(e,t){const r={event:eA.DEVICE_RT_CAMERA,cap_format:0,cap_width:(null==e?void 0:e.width)||0,cap_height:(null==e?void 0:e.height)||0,cap_frame_rate:(null==e?void 0:e.frameRate)||0,out_width:(null==t?void 0:t.width)||0,out_height:(null==t?void 0:t.height)||0,out_cap_frames:(null==t?void 0:t.frameRate)||0,cap_overtime_cnt:0,frame_capture_time:0,render_frame_rate:0,frame_render_time:0};this.addCommInfo(r),cO.addRecord(r)}setSpeakerInputInfo(){const e={event:eA.DEVICE_RT_SPEAKER,dst_down_vel:0,dst_down_nel:0,speaker_vol:0,speaker_play_err_num:0};this.addCommInfo(e),cO.addRecord(e)}setMicrophoneInfo(){const e={event:eA.DEVICE_RT_MICROPHONE,src_cap_vel:0,src_cap_nel:0,src_mic_vol_scale:0,capture_abnormal:0,mic_vol:0,mic_recoder_err_num:0};this.addCommInfo(e),cO.addRecord(e)}async setSpeakerDeviceInfo(e){const t=[];for(let i=0;i5?s-5:0),c=5;ct!==e)):this.clientEventEmitter=null}registerDeviceChangedNotify(){let e=!1;AC().then((e=>{(!e||e.length<=0)&&this.logger.info(xO,"no device available now"),e=e||[],this.preDevices=new Map;for(const t of e)iE.addPrivacyString(t.deviceId),t.deviceId&&"default"!==t.deviceId&&"communications"!==t.deviceId&&this.preDevices.set(t.deviceId,t.kind)})).finally((()=>{navigator.mediaDevices.ondevicechange=async t=>{if(t.isTrusted){if(this.deviceChangeCallBack.push(this.handleDeviceChangeEvent.bind(this)),!e)for(;this.deviceChangeCallBack.length>0;)e=!0,await this.deviceChangeCallBack.shift()(),this.deviceChangeCallBack.length<1&&(e=!1)}else this.logger.error(xO,"device change event trigger by script")}}))}async handleDeviceChangeEvent(){let e=await AC();e=e||[];const t=new Map;for(const i of e)i.deviceId&&"default"!==i.deviceId&&"communications"!==i.deviceId&&t.set(i.deviceId,i.kind);let r=this.internalEventEmitters;this.clientEventEmitter&&(r=[...this.internalEventEmitters,this.clientEventEmitter]),this.preDevices.forEach(((e,i)=>{t.has(i)||(this.logger.info(xO,"deviceType: ".concat(e," deviceId: ").concat(i," remove")),r.forEach((t=>{t.emit(UC[DO[e]],{deviceId:i,state:UO})})),this.stat.setDeviceChangedInfo(e,i,1))})),t.forEach(((e,t)=>{this.preDevices.has(t)||(this.logger.info(xO,"deviceType: ".concat(e," deviceId: ").concat(t," add")),r.forEach((r=>{r.emit(UC[DO[e]],{deviceId:t,state:NO})})),this.stat.setDeviceChangedInfo(e,t,0))})),this.preDevices=t}};function BO(){}function VO(){VO.init.call(this)}function YO(e){return void 0===e._maxListeners?VO.defaultMaxListeners:e._maxListeners}function jO(e,t,r,i){var n,o,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]):(o=e._events=new BO,e._eventsCount=0),s){if("function"==typeof s?s=o[t]=i?[r,s]:[s,r]:i?s.unshift(r):s.push(r),!s.warned&&(n=YO(e))&&n>0&&s.length>n){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=s.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(a)}}else s=o[t]=r,++e._eventsCount;return e}function FO(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function HO(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function KO(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}BO.prototype=Object.create(null),VO.EventEmitter=VO,VO.usingDomains=!1,VO.prototype.domain=void 0,VO.prototype._events=void 0,VO.prototype._maxListeners=void 0,VO.defaultMaxListeners=10,VO.init=function(){this.domain=null,VO.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new BO,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},VO.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},VO.prototype.getMaxListeners=function(){return YO(this)},VO.prototype.emit=function(e){var t,r,i,n,o,s,a,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=s[e]))return!1;var d="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=KO(e,i),o=0;o0;)if(r[o]===t||r[o].listener&&r[o].listener===t){s=r[o].listener,n=o;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new BO,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i0?Reflect.ownKeys(this._events):[]};const zO=new class{constructor(){i(this,"eventHandlers",{visibilitychange:()=>{let e="FOREGROUND";document.hidden&&(e="BACKGROUND");for(const t of this.eventBus.values())t.emit(e)}}),i(this,"eventListeners",{visibilitychange:e=>{"ADD"===e?document.addEventListener("visibilitychange",this.eventHandlers.visibilitychange):document.removeEventListener("visibilitychange",this.eventHandlers.visibilitychange)}}),this.eventBus=new Map,this.addListener("visibilitychange",XR.isMobileDevice.bind(XR))}register(e){const t=XR.generateRandomId(32);return this.eventBus.set(t,e),t}unregister(e){e&&this.eventBus.delete(e)}addListener(e,t){t&&!t()||this.eventListeners[e]&&this.eventListeners[e]("ADD")}removeListener(e){this.eventListeners[e]&&this.eventListeners[e]("REMOVE")}};class WO{constructor(){this.context_=new AudioContext,this.script_=this.context_.createScriptProcessor(2048,1,1),this.script_.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);let r=0,i=0;for(let n=0;n.99&&(i+=1);this.instant_=Math.sqrt(r/t.length),this.slow_=.95*this.slow_+.05*this.instant_,this.clip_=i/t.length},this.instant_=0,this.slow_=0,this.clip_=0}connectToSource(e){return new Promise(((t,r)=>{try{const r=new MediaStream;r.addTrack(e),this.mic_=this.context_.createMediaStreamSource(r),this.mic_.connect(this.script_),this.script_.connect(this.context_.destination),t()}catch(Dw){r(Dw)}}))}stop(){this.mic_.disconnect(),this.script_.disconnect(),this.context_.close()}getVolume(){return parseFloat(this.instant_.toFixed(2))}}class GO{constructor(e){this.module_="RTCPlayer",this.mediaStream_=new MediaStream,this.log_=e.logger,this.track_=e.track,this.playerDiv_=e.playerDiv,this.playerId_=e.playerId,this.playerElement_=null,this.state_="NONE",this.event_=new VO,this.pauseCount=0,this.listenHandlers={canPlayHandler:this.canPlayHandler.bind(this),playingHandler:this.playingHandler.bind(this),playerEndedHandler:this.playerEndedHandler.bind(this),playerPausedHandler:this.playerPausedHandler.bind(this),trackEndedHandler:this.trackEndedHandler.bind(this),trackMutedHandler:this.trackMutedHandler.bind(this),trackUnmutedHandler:this.trackUnmutedHandler.bind(this),playHandler:null,backgroundHandler:this.backgroundHandler.bind(this),foregroundHandler:this.foregroundHandler.bind(this)}}on(e,t){this.event_.on(e,t)}off(e,t){this.event_.removeListener(e,t)}foregroundHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, application is foreground"),this.module_.indexOf("Audio")>0&&this.track_&&this.trackEnable!==this.track_.enabled&&(this.track_.enabled=this.trackEnable),"PAUSED"===this.state_&&(this.module_.indexOf("Video")>0?this.event_.emit("videoCanPlay"):this.event_.emit("audioCanPlay"))}backgroundHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, application is background"),this.module_.indexOf("Audio")>0&&this.track_&&(this.trackEnable=this.track_.enabled,this.trackEnable&&(this.track_.enabled=!1))}canPlayHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is canplay status"),this.event_.emit(this.module_.indexOf("Video")>0?"videoCanPlay":"audioCanPlay"),this.event_.emit(iC,{event:"playerCanplay",type:"".concat(this.module_),streamId:this.playerId_})}playingHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is starting playing"),this.event_.emit(iC,{event:"playerPlaying",type:"".concat(this.module_),streamId:this.playerId_}),this.state_="PLAYING",this.event_.emit(Zb,{state:this.state_,reason:"playing"})}playerEndedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is ended"),this.event_.emit(iC,{event:"playerEnded",type:"".concat(this.module_),streamId:this.playerId_}),"STOPPED"!==this.state_&&(this.state_="STOPPED",this.event_.emit(Zb,{state:this.state_,reason:"ended"}))}playerPausedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is paused"),this.event_.emit(iC,{event:"playerPause",type:"".concat(this.module_),streamId:this.playerId_}),this.state_="PAUSED",this.event_.emit(Zb,{state:this.state_,reason:"pause"}),this.module_.indexOf("Video")>0?(this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"try to play again"),this.event_.emit("videoCanPlay")):(this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"try to play again"),this.event_.emit("audioCanPlay"))}trackEndedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player track is ended"),this.event_.emit(iC,{event:"trackEnded",type:"".concat(this.module_),streamId:this.playerId_}),"STOPPED"!==this.state_&&(this.state_="STOPPED",this.event_.emit(Zb,{state:this.state_,reason:"ended",trackEnded:!0}))}trackMutedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, track is muted"),this.event_.emit(iC,{event:"trackMute",type:"".concat(this.module_),streamId:this.playerId_}),"PAUSED"!==this.state_&&(this.state_="PAUSED",this.event_.emit(Zb,{state:this.state_,reason:"mute"}))}trackUnmutedHandler(){this.log_.debug("".concat(this.module_,"#[").concat(this.playerId_,"]"),"handleEvents, track is unmuted"),this.event_.emit(iC,{event:"trackUnmute",type:"".concat(this.module_),streamId:this.playerId_}),"PAUSED"===this.state_&&(this.state_="PLAYING",this.event_.emit(Zb,{state:this.state_,reason:"unmute"}))}closeAllEvents(){var e,t,r,i,n,o,s,a,c;null===(e=this.playerElement_)||void 0===e||e.removeEventListener("canplay",this.listenHandlers.canPlayHandler),null===(t=this.playerElement_)||void 0===t||t.removeEventListener("playing",this.listenHandlers.playingHandler),null===(r=this.playerElement_)||void 0===r||r.removeEventListener("ended",this.listenHandlers.playerEndedHandler),null===(i=this.playerElement_)||void 0===i||i.removeEventListener("pause",this.listenHandlers.playerPausedHandler),null===(n=this.track_)||void 0===n||n.removeEventListener("ended",this.listenHandlers.trackEndedHandler),null===(o=this.track_)||void 0===o||o.removeEventListener("mute",this.listenHandlers.trackMutedHandler),null===(s=this.track_)||void 0===s||s.removeEventListener("unmute",this.listenHandlers.trackUnmutedHandler),null===(a=this.event_)||void 0===a||a.removeListener("videoCanPlay",this.listenHandlers.playHandler),null===(c=this.event_)||void 0===c||c.removeListener("audioCanPlay",this.listenHandlers.playHandler),this.event_.removeListener("FOREGROUND",this.listenHandlers.foregroundHandler),this.event_.removeListener("BACKGROUND",this.listenHandlers.backgroundHandler),zO.unregister(this.sysEventRegisterUid)}handleEvents(){this.playerElement_.addEventListener("canplay",this.listenHandlers.canPlayHandler),this.playerElement_.addEventListener("playing",this.listenHandlers.playingHandler),this.playerElement_.addEventListener("ended",this.listenHandlers.playerEndedHandler),this.playerElement_.addEventListener("pause",this.listenHandlers.playerPausedHandler),this.track_.addEventListener("ended",this.listenHandlers.trackEndedHandler),this.track_.addEventListener("mute",this.listenHandlers.trackMutedHandler),this.track_.addEventListener("unmute",this.listenHandlers.trackUnmutedHandler),this.event_.on("FOREGROUND",this.listenHandlers.foregroundHandler),this.event_.on("BACKGROUND",this.listenHandlers.backgroundHandler),this.sysEventRegisterUid=zO.register(this.event_)}stop(){this.closeAllEvents(),this.playerElement_&&(this.playerElement_.srcObject=null),this.playerElement_=null,this.mediaStream_=new MediaStream,this.log_.info(this.module_,"stop success")}replaceTrack(e){this.log_.info(this.module_,"replaceTrack start");const t=this.module_.indexOf("Audio")>0?this.mediaStream_.getAudioTracks():this.mediaStream_.getVideoTracks(),r=t.length?t[0]:null;r!==e&&(r&&this.mediaStream_.removeTrack(r),this.mediaStream_.addTrack(e),this.track_=e)}async resume(e){return new Promise(((t,r)=>{this.playerElement_?this.playerElement_.play().then((()=>{this.log_.info(this.module_,"audio player resume success, streamId:".concat(this.playerId_,", playParameters: ").concat(JSON.stringify(e))),t(null)})).catch((t=>{this.log_.error(this.module_,"player resume failed, errmsg=".concat(t," , playParameters: ").concat(JSON.stringify(e))),"NotAllowedError"===t.name?r(new qc(Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW)):r(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,t.message))})):r(new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"resume failed, element is null"))}))}async multiPlatformAdapter(){return new Promise((e=>{if(XR.isWKWebview()){const t=window.WeixinJSBridge;t?(this.log_.info(this.module_,"multiPlatformAdapter handle begin"),t.invoke("getNetworkType",{},(()=>{e()}),!1)):document.addEventListener("WeixinJSBridgeReady",(()=>{this.log_.info(this.module_,"multiPlatformAdapter WeixinJSBridgeReady, handle begin"),t.invoke("getNetworkType",{},(()=>{e()}),!1)}))}else e()}))}async doPlay(e,t,r){let i;return await this.multiPlatformAdapter(),i=this.module_.indexOf("Video")>0?", screenFit:".concat(r.objectFit,", mirror:").concat(r.mirror):", deviceId:".concat(r.outputDeviceId,", volume:").concat(r.volume,", muted:").concat(r.muted),this.playerElement_.play().then((()=>{var t,r;this.log_.info(this.module_,"play success, parentDiv id:".concat(null===(t=this.playerDiv_)||void 0===t?void 0:t.id,", resolutionId or streamId:").concat(this.playerId_,", physical track id:").concat(null===(r=this.track_)||void 0===r?void 0:r.id).concat(i)),this.afterPlayStrategy(),e(null)})).catch((e=>{var r,n;this.log_.error(this.module_,"play failed, errmsg=".concat(e,",parentDiv id:").concat(null===(r=this.playerDiv_)||void 0===r?void 0:r.id,", resolutionId or streamId:").concat(this.playerId_,", physical track id:").concat(null===(n=this.track_)||void 0===n?void 0:n.id).concat(i)),"NotAllowedError"===e.name?t(new qc(Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW)):t(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,e.message))})).finally((()=>{clearTimeout(this.playTimeOutTimer)}))}afterPlayStrategy(){if(!this.pauseCount&&XR.getPlatform().indexOf("Ios15")>=0){this.log_.error(this.module_,XR.getPlatform());const e=setTimeout((()=>{clearTimeout(e),this.playerElement_.pause(),this.pauseCount++}),100)}}}class JO extends GO{constructor(e){super({logger:e.logger,track:e.track,playerDiv:e.playerDiv,playerId:e.playerId}),this.module_="RTCAudioPlayer",this.muted_=e.muted,this.outputDeviceId_="",this.volume_="number"==typeof(null==e?void 0:e.volume)?e.volume:.5,this.soundMeter_=null}async play(){return new Promise(((e,t)=>{let r,i=!0;var n;(r=this.playerDiv_?this.playerDiv_.querySelector("#audio_".concat(this.playerId_)):this.playerElement_,r)||(r=document.createElement("audio"),r.muted=this.muted_,r.setAttribute("id","audio_".concat(this.playerId_)),r.setAttribute("autoplay",""),r.setAttribute("playsinline",""),r.setAttribute("muted",""),null===(n=this.playerDiv_)||void 0===n||n.appendChild(r),i=!1);"sinkId"in HTMLMediaElement.prototype&&this.outputDeviceId_&&r.setSinkId(this.outputDeviceId_),0===this.mediaStream_.getAudioTracks().length&&this.mediaStream_.addTrack(this.track_),r.srcObject=this.mediaStream_,this.playerElement_=r,this.setVolume(this.volume_),this.handleEvents(),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"trigger audioCanPlay event by Timer"),this.event_.emit("audioCanPlay"),this.playTimeOutTimer&&(clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"audio playing timeout"),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=null,e(null)}),2e3))}),i?0:1e3),this.listenHandlers.playHandler&&this.event_.removeListener("audioCanPlay",this.listenHandlers.playHandler),this.listenHandlers.playHandler=this.doPlay.bind(this,e,t,{deviceId:this.outputDeviceId_,volume:this.volume_,muted:this.muted_}),this.event_.on("audioCanPlay",this.listenHandlers.playHandler)}))}async setSinkId(e){this.outputDeviceId_!==e&&(await this.playerElement_.setSinkId(e),this.outputDeviceId_=e)}setVolume(e){this.playerElement_.volume=e}getAudioLevel(){return this.soundMeter_||(this.soundMeter_=new WO,this.soundMeter_.connectToSource(this.track_)),this.soundMeter_.getVolume()}stop(){super.stop(),this.soundMeter_&&(this.soundMeter_.stop(),this.soundMeter_=null)}async resume(){return super.resume({streamId:this.playerId_,deviceId:this.outputDeviceId_,volume:this.volume_,muted:this.muted_})}replaceTrack(e){super.replaceTrack(e),this.soundMeter_&&(this.soundMeter_.stop(),this.soundMeter_=null)}}class qO extends GO{constructor(e){super({logger:e.logger,track:e.track,playerDiv:e.parentDiv,playerId:e.playerId}),this.module_="RTCVideoPlayer",this.objectFit_=e.objectFit,this.mirror_=e.mirror}async play(){return new Promise(((e,t)=>{let r=this.playerDiv_.querySelector("#video_".concat(this.playerId_)),i=!0;if(!r){r=document.createElement("video"),r.muted=!0;let e="0";this.mirror_&&(e="180deg"),r.setAttribute("id","video_".concat(this.playerId_)),r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.transform="rotateY(".concat(e,")"),r.style["object-fit"]=this.objectFit_,r.setAttribute("autoplay",""),r.setAttribute("playsinline",""),r.setAttribute("muted",""),this.playerDiv_.appendChild(r),i=!1}0===this.mediaStream_.getVideoTracks().length&&this.mediaStream_.addTrack(this.track_),r.srcObject=this.mediaStream_,this.playerElement_=r,this.handleEvents(),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"trigger videoCanPlay event by Timer"),this.event_.emit("videoCanPlay"),this.playTimeOutTimer&&(clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"video playing timeout"),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=null,e(null)}),2e3))}),i?0:1e3),this.listenHandlers.playHandler&&this.event_.removeListener("videoCanPlay",this.listenHandlers.playHandler),this.listenHandlers.playHandler=this.doPlay.bind(this,e,t,{objectFit:this.objectFit_,mirror:this.mirror_}),this.event_.on("videoCanPlay",this.listenHandlers.playHandler)}))}async resume(){return super.resume({streamId:this.playerId_,screentFit:this.objectFit_,mirror:this.mirror_})}getVideoFrame(){const e=document.createElement("canvas");return e.width=this.playerElement_.videoWidth,e.height=this.playerElement_.videoHeight,e.getContext("2d").drawImage(this.playerElement_,0,0),e.toDataURL("image/png")}}function XO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function QO(e){for(var t=1;tt.startsWith("".concat(e.height))&&cC[t].width===e.width||parseInt(t)>e.height));t&&(e.maxBitrate&&e.minBitrate||(e.maxBitrate=cC[t].maxBitrate,e.minBitrate=cC[t].minBitrate),e.frameRate||(e.frameRate=cC[t].frameRate))}class ZO{static getLocalProfileByTrack(e){const t={},r=e.getSettings();if(e.kind===vO.TRACK_TYPE_AUDIO)t.sampleRate=r.sampleRate,t.channelCount=1;else{var i,n,o,s;const a=e.getConstraints();t.width=("number"==typeof a.width?a.width:null===(i=a.width)||void 0===i?void 0:i.ideal)||r.width,t.height=("number"==typeof a.height?a.height:null===(n=a.height)||void 0===n?void 0:n.ideal)||r.height,t.frameRate=("number"==typeof a.frameRate?a.frameRate:null===(o=a.frameRate)||void 0===o?void 0:o.ideal)||parseInt(null===(s=r.frameRate)||void 0===s?void 0:s.toString()),t.minBitrate=null,t.maxBitrate=null,$O(t)}return t}static formatVideoProfile(e){let t={};if(!e){return t=QO({},cC["360p_2"]),t}if("string"==typeof e){if(uC.includes(e)){t=QO({},cC[e])}}else t.height=e.height,t.width=e.width,t.frameRate=e.frameRate,t.maxBitrate=e.maxBitrate,t.minBitrate=e.minBitrate,void 0!==t.width&&void 0!==t.height||(t.width=cC["360p_2"].width,t.height=cC["360p_2"].height),$O(t);return t}static formatAudioProfile(e){let t={};if(!e){return t=QO({},sC.standard),t}if("string"==typeof e){if(aC.includes(e)){t=QO({},sC[e])}}else t.bitrate=e.bitrate,t.channelCount=e.channelCount,t.sampleRate=e.sampleRate,t.sampleRate||(t.sampleRate=16e3),t.channelCount||(t.channelCount=1),t.bitrate||(t.bitrate=24e3);return t}static formatScreenProfile(e){let t={};if(!e){return t=QO({},dC["720p"]),t}if("string"==typeof e){if(lC.includes(e)){t=QO({},dC[e])}}else t.height=e.height,t.width=e.width,t.bitrate=e.bitrate,t.frameRate=e.frameRate,t.width&&t.height||(t.width=dC["720p"].width,t.height=dC["720p"].height),t.frameRate||(t.frameRate=15),t.bitrate||(t.bitrate=dC["720p"].bitrate);return t}}const eP=XR.isSafari(),tP=(e,t)=>{XR.isSupportConstraints("aspectRatio")&&!eP&&(e.aspectRatio={ideal:t.width/t.height}),e.width=eP?{min:cC["90p_2"].width}:{min:cC["90p_2"].width,ideal:t.width},e.height=eP?{min:cC["90p_2"].height}:{min:cC["90p_2"].height,ideal:t.height},e.frameRate=t.frameRate};class rP{static getOptimalVideoConstraint(e,t){const r={},i=[];["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e};const n=[{width:t.width,height:t.height},{aspectRatio:t.width/t.height}];i.push(...n),tP(r,t),r.advanced=i;const o={};return o.video=r,o}static getSuboptimalVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e},tP(r,t);const i={};return i.video=r,i}static getNextVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e},tP(r,t);const i={};return i.video=r,i}static getWorstVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={ideal:e}:r.deviceId={ideal:e},tP(r,t);const i={};return i.video=r,i}static getRecoveryVideoConstraint(){const e={video:!0};return e}static initScreenShareConstraint(e,t){const r={};if(eP?(r.video={frameRate:t.frameRate},t.width&&(r.video.width={max:t.width}),t.height&&(r.video.height={max:t.height})):r.video={width:t.width||void 0,height:t.height||void 0,frameRate:t.frameRate},e){const e={sampleRate:sC.high.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};Mw.isChrome()&&(e.googNoiseSuppression=!0,e.googAutoGainControl=!0,e.googAutoGainControl2=!0),r.audio=e}return r}static initAudioConstraint(e,t){const r={},i={sampleRate:t.sampleRate,channelCount:t.channelCount,deviceId:e,echoCancellation:!0};return Mw.isFirefox()&&e&&(i.deviceId={exact:e}),i.noiseSuppression=!0,i.autoGainControl=!0,Mw.isChrome()&&(i.googNoiseSuppression=!0,i.googAutoGainControl=!0,i.googAutoGainControl2=!0),r.audio=i,r}}var iP=function(e){return e[e.Stopped=0]="Stopped",e[e.Playing=1]="Playing",e[e.Closed=2]="Closed",e}(iP||{});const nP="HRTCTrack";class oP{constructor(e){this.log_=e.logger||iE.getLogger(),this.trackType_=e.trackType,this.streamType_=e.streamType,this.isRemote_=e.isRemote,this.resolutionId_=e.resolutionId,e.track?this.setLocalProfileByTrack(e.track):this.setTrackProfile(e.trackProfile),this.track_=e.track,this.playState_=iP.Closed,this.trackMuted_=!1,this.event_=e.event||new VO,this.trackType_===vO.TRACK_TYPE_AUDIO?this.statusChangeReporter_=e=>{this.event_.emit(Zb,{type:vO.TRACK_TYPE_AUDIO,id:this.getResolutionId(),state:e.state,reason:e.reason})}:this.statusChangeReporter_=e=>{this.event_.emit(Zb,{type:vO.TRACK_TYPE_VIDEO,id:this.getResolutionId(),state:e.state,reason:e.reason})},this.statusTraceReporter_=e=>{this.event_.emit(iC,e)}}async initScreenShare(e){const t=rP.initScreenShareConstraint(e,this.profile_);this.log_.info(nP,"initScreenShare, screen constraints: ".concat(JSON.stringify(t)));const r=[],i={type:vO.TRACK_TYPE_AUDIO},n={type:vO.TRACK_TYPE_VIDEO};return new Promise((o=>{navigator.mediaDevices.getDisplayMedia(t).then((t=>{const r=t.getVideoTracks()[0];this.track_&&(this.track_.stop(),this.player_&&this.player_.replaceTrack(r)),this.track_=r,n.track=r,this.content=CC.desktop,r.onended=()=>{this.event_.emit(eC,this.trackId_||this.resolutionId_)},e&&(0===(t.getAudioTracks()||[]).length?this.log_.info(nP,"initScreenShare, cannot capture system output audio, pls make sure checked the share Audio option in share page"):i.track=t.getAudioTracks()[0])})).catch((e=>{this.log_.error(nP,"initScreenShare, getDisplayMedia failed, errMsg= ".concat(e)),i.error=this.handleCaptureError(e),n.error=i.error})).finally((()=>{r.push(i),r.push(n),o(r)}))}))}async initAudioCapture(e){const t=rP.initAudioConstraint(e,this.profile_);return await this.getUserMedia(t,vO.TRACK_TYPE_AUDIO,CC.main)}async initVideoCapture(e,t){let r;return this.log_.info(nP,"initVideoCapture, try getOptimalVideoConstraint"),r=await this.getUserMedia(rP.getOptimalVideoConstraint(e,this.profile_),vO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getSuboptimalVideoConstraint"),r=await this.getUserMedia(rP.getSuboptimalVideoConstraint(e,this.profile_),vO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getNextVideoConstraint"),r=await this.getUserMedia(rP.getNextVideoConstraint(e,this.profile_),vO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getWorstVideoConstraint"),r=await this.getUserMedia(rP.getWorstVideoConstraint(e,this.profile_),vO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getRecoveryVideoConstraint"),await this.getUserMedia(rP.getRecoveryVideoConstraint(),vO.TRACK_TYPE_VIDEO,t)))))}async getUserMedia(e,t,r){const i={type:t};try{var n;null===(n=this.track_)||void 0===n||n.stop();const o=await navigator.mediaDevices.getUserMedia(e),s=t===vO.TRACK_TYPE_VIDEO?o.getVideoTracks()[0]:o.getAudioTracks()[0];return await this.replaceTrack(s),i.track=this.track_,this.content=r,i.type===vO.TRACK_TYPE_VIDEO&&this.setCameraCaptureReport(),i}catch(jN){return i.error=this.handleCaptureError(jN,t),i}}static isTrackAvailable(e){return!!e&&(e.enabled&&!e.muted&&"live"===e.readyState)}setCameraCaptureReport(){this.cameraCaptureHandleTimer&&clearInterval(this.cameraCaptureHandleTimer),this.cameraCaptureHandleTimer=setInterval((()=>{if(this.track_&&this.profile_){var e;const t=this.track_.getSettings(),r={width:this.profile_.width,height:this.profile_.height,frameRate:parseInt(null===(e=this.profile_.frameRate)||void 0===e?void 0:e.toString())||0};this.event_.emit(oC.CameraCapture,t,r)}}),2e3)}clearCameraCaptureReport(){this.cameraCaptureHandleTimer&&clearInterval(this.cameraCaptureHandleTimer)}handleCaptureError(e,t){if(/.*Malformed constraints.*/gi.test(e.message))return this.log_.warn(nP,"init ".concat(t||"screen","capture getUserMedia failed, handleCaptureError: ").concat(e)),null;const r=e.name||"";let i;return i=/.*NotAllowedError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED):/.*OverConstrainedError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED):/.*NotReadableError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE):/.*NotFoundError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND):new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,e.message),this.log_.error(nP,"init ".concat(t||"screen","capture getUserMedia failed, handleCaptureError: ").concat(i)),i}isClosed(){return this.playState_===iP.Closed}isPlaying(){return this.playState_===iP.Playing}getTrackType(){return this.trackType_}getResolutionId(){return this.resolutionId_}getTrackId(){return this.trackId_}getElementId(){return this.elementId_}getObjectFit(){return this.objectFit_}setTrackId(e){this.trackId_=e}getTrackProfile(){return this.profile_}setTrackContentType(e){this.content=e}getTrackContentType(){return this.content||CC.main}updateTrackProfile(e){this.trackType_===vO.TRACK_TYPE_VIDEO&&e&&(this.profile_.width=e.width,this.profile_.height=e.height)}setTrackProfile(e){this.log_.info(nP,"setTrackProfile begin,uniqueId_:".concat(this.resolutionId_,", ").concat(this.trackType_,",")+"".concat(this.streamType_,", profile:").concat(JSON.stringify(e))),this.trackType_!==vO.TRACK_TYPE_AUDIO?this.trackType_!==vO.TRACK_TYPE_VIDEO||this.streamType_!==yO.STREAM_TYPE_MAIN?this.trackType_===vO.TRACK_TYPE_VIDEO&&this.streamType_===yO.STREAM_TYPE_AUX&&(this.profile_=ZO.formatScreenProfile(e)):this.profile_=ZO.formatVideoProfile(e):this.profile_=ZO.formatAudioProfile(e)}getTrack(){return this.track_}async replaceTrack(e){var t;if(e){var r;if(null===(t=this.player_)||void 0===t||t.replaceTrack(e),!this.isRemote_)null===(r=this.track_)||void 0===r||r.stop();this.track_=e,this.track_.enabled=!this.trackMuted_,this.isRemote_||(this.setLocalProfileByTrack(e),this.playState_===iP.Playing&&await this.restart())}}setLocalProfileByTrack(e){this.profile_=ZO.getLocalProfileByTrack(e),this.log_.info(nP,"setLocalProfileByTrack, this.profile_:".concat(JSON.stringify(this.profile_)))}removeTrack(){var e;(this.player_&&this.player_.stop(),this.isRemote_)||(null===(e=this.track_)||void 0===e||e.stop());this.track_=null}async play(e,t,r){const i=this.getTrackType();if(this.log_.info(nP,"".concat(i," track begin play, elementId:").concat(t,", playerDiv.id:").concat(e.id,", options:").concat(JSON.stringify(r)," ")),this.playState_===iP.Playing)return this.log_.info(nP,"".concat(i," track is playing, return")),{trackType:i,error:null};if(!this.track_)return this.log_.error(nP,"".concat(i," track is empty")),{trackType:i,error:new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"".concat(i," track is empty"))};switch(this.elementId_=t,this.trackType_){case vO.TRACK_TYPE_AUDIO:this.player_||(this.log_.info(nP,"create AudioPlayer"),this.player_=new JO({logger:this.log_,playerDiv:e,playerId:this.getTrackId()||this.getResolutionId(),track:this.track_,muted:r.muted,volume:this.audioVolume_}));break;case vO.TRACK_TYPE_VIDEO:this.objectFit_=r.objectFit,this.player_||(this.log_.info(nP,"create VideoPlayer"),this.player_=new qO({logger:this.log_,parentDiv:e,playerId:this.getTrackId()||this.getResolutionId(),track:this.track_,objectFit:r.objectFit,mirror:r.mirror}))}this.player_.off(Zb,this.statusChangeReporter_),this.player_.on(Zb,this.statusChangeReporter_),this.player_.off(iC,this.statusTraceReporter_),this.player_.on(iC,this.statusTraceReporter_),this.log_.info(nP,"play ".concat(i," track start")),this.playState_=iP.Playing;try{return await this.player_.play(),{trackType:i,error:null}}catch(jN){const t=jN instanceof qc&&/.*timeout.*/i.test(jN.getMsg());return this.log_[t?"warn":"error"](nP,"play ".concat(i," failed: ").concat(jN)),this.playState_=iP.Stopped,{trackType:i,error:jN}}}async replay(){if(!this.player_)return this.log_.info(nP,"".concat(this.getTrackType()," player is null")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"".concat(this.getTrackType()," player is null"));this.player_.off(Zb,this.statusChangeReporter_),this.player_.on(Zb,this.statusChangeReporter_),this.player_.off(iC,this.statusTraceReporter_),this.player_.on(iC,this.statusTraceReporter_),this.log_.info(nP,"rePlay ".concat(this.getTrackType()," track start")),this.playState_=iP.Playing;try{return await this.player_.play(),null}catch(jN){return this.log_.error(nP,"replay".concat(this.getTrackType(),", replay failed: ").concat(jN)),this.playState_=iP.Stopped,jN}}stop(){this.player_?(this.player_.off(Zb,this.statusChangeReporter_),this.player_.stop(),this.player_=null,this.playState_=iP.Stopped,this.trackMuted_=!1,this.log_.info(nP,"".concat(this.getTrackType()," stop player success"))):this.log_.info(nP,"".concat(this.getTrackType()," player is null"))}close(){var e;(this.stop(),this.isRemote_)||(null===(e=this.track_)||void 0===e||e.stop());this.elementId_="",this.log_.info(nP,"".concat(this.getTrackType()," close success")),this.playState_=iP.Closed,this.clearCameraCaptureReport()}async resume(){if(!this.player_)return this.log_.info(nP,"".concat(this.getTrackType()," player is null")),null;try{return await this.player_.resume(),null}catch(jN){return this.log_.error(nP,"".concat(this.getTrackType()," resume failed: ").concat(jN)),jN}}async restart(){this.player_&&(this.player_.stop(),await this.player_.play(),this.log_.info(nP,"restart success"))}getTrackMuted(){return this.track_?!this.track_.enabled:this.trackMuted_}muteTrack(){this.track_&&(this.track_.enabled=!1),this.trackMuted_=!0}unmuteTrack(){this.track_&&(this.track_.enabled=!0),this.trackMuted_=!1}async setSinkId(e){this.trackType_===vO.TRACK_TYPE_AUDIO&&this.player_&&await this.player_.setSinkId(e)}setAudioVolume(e){this.trackType_===vO.TRACK_TYPE_AUDIO&&(this.audioVolume_=e/100,this.player_&&this.player_.setVolume(this.audioVolume_))}getAudioLevel(){return this.trackType_===vO.TRACK_TYPE_AUDIO&&this.player_?this.player_.getAudioLevel():0}getVideoFrame(){return this.trackType_===vO.TRACK_TYPE_VIDEO&&this.player_?this.player_.getVideoFrame():null}setAudioOutput(e){this.trackType_===vO.TRACK_TYPE_AUDIO&&this.player_&&this.player_.setSinkId(e)}}const sP="AsyncLock";class aP{constructor(){i(this,"callback_",[]),this.callback_=[],this.logger=iE.getLogger()}async lock(e){this.logger.info(sP,"".concat(e," try to get lock")),await new Promise((t=>{const r={callbackFunc:()=>t(),lockTrigger:"".concat(e)};this.callback_.push(r),1===this.callback_.length&&(this.callback_[0].callbackFunc(),this.logger.info(sP,"".concat(this.callback_[0].lockTrigger," got lock")))}))}unlock(e){if(this.logger.info(sP,"".concat(e," try to unlock")),this.callback_.length>0){const e=this.callback_.shift();this.logger.info(sP,"".concat(e.lockTrigger," unlocked")),this.callback_.length>0&&(this.callback_[0].callbackFunc(),this.logger.info(sP,"".concat(this.callback_[0].lockTrigger," got lock")))}else this.logger.error(sP,"unlock, but no lock exist")}clear(){for(;this.callback_.length>0;)this.unlock(this.callback_[0].lockTrigger)}}const cP=new aP;function uP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function dP(e){for(var t=1;t{const n=i.value;return dP(dP({},i),{},{async value(){const t=this.locker||cP;try{var i,o;null===(i=this.log)||void 0===i||i.info(e,"function ".concat(r," is wating for lock. ")),await t.lock(e),null===(o=this.log)||void 0===o||o.info(e,"function ".concat(r," get a lock. "));for(var s=arguments.length,a=new Array(s),c=0;c{const n=i.value,o=e.substr(0,e.indexOf("$"));return dP(dP({},i),{},{async value(){let t,r;const i=XR.getCurrentTimestamp();for(var s=arguments.length,a=new Array(s),c=0;c{const n=i.value,o=e.substr(0,e.indexOf("$"));return dP(dP({},i),{},{value(){let t,r;const i=XR.getCurrentTimestamp();for(var s=arguments.length,a=new Array(s),c=0;c["object","function"].includes(typeof e)?e.getStatInfo?e.getStatInfo():e.getInfo?e.getInfo():e:e))}catch(Dw){return e}}class mP{static async callAsyncApi(e,t,r,i){let n,o;const s=XR.getCurrentTimestamp(),a=r||[];try{return o=await t.call(e,...a),o}catch(jN){throw n=jN,jN}finally{const t=XR.getCurrentTimestamp(),r=mP.doFinalParam([o,...a,e]);e.stat.setApiCallInfo(i,s,t,n,...r)}}static doFinalParam(e){return e.map((e=>["object","function"].includes(typeof e)&&e.getStatInfo?e.getStatInfo():e))}static callApi(e,t,r,i){let n,o;const s=XR.getCurrentTimestamp(),a=r||[];try{return o=t.call(e,...a),o}catch(jN){throw n=jN,jN}finally{const t=XR.getCurrentTimestamp(),r=mP.doFinalParam([o,...a,e]);e.stat.setApiCallInfo(i,s,t,n,...r)}}static callWithTimeout(e,t){let r;const i=new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT),n=new Promise(((e,t)=>{r=t}));let o=null;return t&&(o=setTimeout((()=>{o&&clearTimeout(o),r(i)}),t)),Promise.race([e.finally((()=>{o&&clearTimeout(o)})),n])}static async callWithRetryTimes(e,t,r,i,n){let o=r>=0?r+1:-1,s=1,a=!1;for(;-1===o||o;){let c,u;try{u=await e(s)}catch(jN){c=jN,a=n&&n(c),console.warn("FunctionUtil","callWithRetryTimes, func:".concat(e.name,", isInterrupted:").concat(a,",")+"retryTimes:".concat(r,", left times:").concat(-1===o?-1:o-1,", tryNumber:").concat(s,", err: ").concat(c))}finally{if(!((c||!c&&t)&&!a&&(-1===o||--o>0))){if(!c)return u;throw c}{const e="number"==typeof i?i:i(c);await XR.sleep(e),s++}}}}}class gP{constructor(e){"boolean"!=typeof e?this.eventEmitter_=e:e&&(this.eventEmitter_=new VO)}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.removeListener(e,t):this.eventEmitter.removeAllListeners(e)}emit(e,t){this.eventEmitter.emit(e,t)}get eventEmitter(){return this.eventEmitter_}set eventEmitter(e){this.eventEmitter_=e}}class _P{constructor(e,t){"boolean"!=typeof e?this.logger_=e:e&&(this.logger_=iE.getLogger(t))}get logger(){return this.logger_}set logger(e){this.logger_=e}}class SP{constructor(e,t){"boolean"!=typeof e?this.stat_=e:e&&(this.stat_="boolean"!=typeof t?new MO(iE.getLogger(),t):new MO(iE.getLogger()))}set stat(e){this.stat_=e}get stat(){return this.stat_}}var vP,yP,IP,TP,RP,EP,bP,CP,AP,wP,kP,OP,PP,MP,DP,NP,UP,xP,LP,BP,VP,YP,jP,FP,HP,KP,zP,WP,GP,JP,qP,XP,QP=new class{constructor(){this.gen=(()=>{let e=0;return()=>e++})()}getSequence(){return this.gen()}};class $P{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{emitter:!1,logger:!1,stat:!1,config:!1},t=arguments.length>1?arguments[1]:void 0;i(this,"onCallbackMap_",new Map),this.identifiedID_=t||Symbol("identifiedID_".concat(QP.getSequence())),!1!==e.emitter&&(this.emitterAble_=new gP(e.emitter)),!1!==e.logger&&(this.loggerAble_=new _P(e.logger,this.identifiedID_)),!1!==e.stat&&(this.statisticAble_=new SP(e.stat,e.config))}on(e,t,r){var i;r?this.onWithTimeout(e,t):null===(i=this.emitterAble_)||void 0===i||i.on(e,t)}off(e,t,r){var i;r?this.offWithTimeout(e,t):null===(i=this.emitterAble_)||void 0===i||i.off(e,t)}emit(e,t){var r;null===(r=this.emitterAble_)||void 0===r||r.emit(e,t)}onWithTimeout(e,t){var r;const i=this.getOnCallback(e,t);null===(r=this.emitterAble_)||void 0===r||r.on(e,i)}offWithTimeout(e,t){var r;null===(r=this.emitterAble_)||void 0===r||r.off(e,this.getOffCallback(e,t)||t)}getOnCallback(e,t){const r=async r=>{const i=XR.getCurrentTimestamp();let n;try{await mP.callWithTimeout(Promise.resolve(await t&&t(r)),1e4),n=XR.getCurrentTimestamp()}catch(jN){n=i+5e3}finally{var o,s;null===(o=this.stat)||void 0===o||o.recordCallbackInfo(e.toString(),null===(s=this.getInfo())||void 0===s?void 0:s.moduleName,i,n,r,(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))}},i=this.onCallbackMap_.get(e)||[];return i.push({func:t,callbackFun:r}),this.onCallbackMap_.set(e,i),r}getOffCallback(e,t){const r=this.onCallbackMap_.get(e)||[],i=r.findIndex((e=>e.func===t));if(i>-1){var n;const e=null===(n=r[i])||void 0===n?void 0:n.callbackFun;return r.splice(i,1),e}return null}get stat(){var e;return null===(e=this.statisticAble_)||void 0===e?void 0:e.stat}get logger(){var e;return null===(e=this.loggerAble_)||void 0===e?void 0:e.logger}get eventEmitter(){if(!this.emitterAble_||!this.emitterAble_.eventEmitter)throw new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);return this.emitterAble_.eventEmitter}get identifiedID(){return this.identifiedID_}getStatInfo(){}}class ZP extends qc{constructor(e,t,r){super(e,t),this.captureResults=r}getMediaCaptureResult(){return this.captureResults}getMediaCaptureResultByType(e){var t;return null===(t=this.captureResults)||void 0===t?void 0:t.find((t=>t.type===e))}toString(){return'["code": '.concat(this.code,', "message": "').concat(this.message," : ").concat(JSON.stringify(this.captureResults),'"]')}}let eM=(vP=fP("Stream$getStreamInfo#StreamInfo"),yP=hP("Stream$play#Promise#string#{ objectFit?: string; muted: boolean; resolutionId?: string; playerElementHidden?: boolean }#string"),IP=fP("Stream$stop#void#StreamOption"),TP=hP("Stream$resume#Promise#StreamOption"),RP=fP("Stream$close#void#StreamOption"),EP=fP("Stream$muteAudio#boolean"),bP=fP("Stream$muteVideo#boolean"),CP=fP("Stream$unmuteAudio#boolean"),AP=fP("Stream$unmuteVideo#boolean"),wP=hP("Stream$setAudioOutput#Promise#string"),kP=fP("Stream$setAudioVolume#void#number"),OP=class extends $P{constructor(e){super({emitter:!0,logger:e.log||!0,stat:!0}),i(this,"module_","Stream"),this.isRemote_=e.isRemote,this.id_=XR.generateStreamId(),this.type_=e.type,this.isAuxiliary_="auxiliary"===e.type,this.tracks={video:new Map,audio:new Map},this.playDivContainers=new Map,this.traceHandler=this.playerStatusTrace.bind(this)}getStreamInfo(){return this.getStreamInfoImpl()}getStreamInfoImpl(){const e={videoProfiles:[]};for(const[r,i]of this.tracks[vO.TRACK_TYPE_VIDEO])if(i.getTrackType()===vO.TRACK_TYPE_VIDEO){const t={resolutionId:r,hasTrack:!!i.getTrack(),width:i.getTrackProfile().width,height:i.getTrackProfile().height,frameRate:i.getTrackProfile().frameRate,minBitrate:i.getTrackProfile().minBitrate,maxBitrate:i.getTrackProfile().maxBitrate};e.videoProfiles.push(t)}const t=this.getAnyAudioHRTCTrack();return t&&(e.audioProfile={sampleRate:t.getTrackProfile().sampleRate,channelCount:t.getTrackProfile().channelCount,bitrate:t.getTrackProfile().bitrate}),this.logger.info(this.module_,"getStreamInfoImpl success: ".concat(JSON.stringify(e))),e}getMaxResolutionHRTCTrack(e){let t;const r=Array.from(this.tracks[vO.TRACK_TYPE_VIDEO].values()),i=e?r:r.filter((e=>e.getTrack()));for(const n of i)t?t&&Math.max(n.getTrackProfile().width,n.getTrackProfile().height)-Math.max(t.getTrackProfile().width,t.getTrackProfile().height)>0&&(t=n):t=n;return t}getMaxResolutionProfile(e){if(0===e.size)return null;let t,r;for(const[i,n]of e)t?Math.max(n.width,n.height)-Math.max(t.width,t.height)>0&&(t=n,r=i):(t=n,r=i);return t?{resolutionId:r,width:t.width,height:t.height,frameRate:t.frameRate,minBitrate:t.minBitrate,maxBitrate:t.maxBitrate}:null}getHRTCTracks(e){const t=[],r=Array.from(this.tracks[vO.TRACK_TYPE_AUDIO].values()),i=Array.from(this.tracks[vO.TRACK_TYPE_VIDEO].values());if(!e)return[...r,...i];const n=void 0===e.hasTrack?r:r.filter((t=>!!t.getTrack()===e.hasTrack)),o=void 0===e.hasTrack?i:i.filter((t=>!!t.getTrack()===e.hasTrack));return e.mediaType?e.mediaType===vO.TRACK_TYPE_VIDEO?t.push(...o):t.push(...n):(t.push(...n),t.push(...o)),t}getHRTCTrackIds(e){const t=[];for(const r of this.getHRTCTracks(e))t.push(r.getTrackId());return t}getAnyVideoHRTCTrack(e){let t;return t=e?this.tracks[vO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(!0),t}getVideoHRTCTrack(e){var t;let r;return r=e?this.tracks[vO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(),null!==(t=r)&&void 0!==t&&t.getTrack()?r:null}getAnyAudioHRTCTrack(){return this.isAuxiliary_?this.tracks[vO.TRACK_TYPE_AUDIO].get("auxAudio"):this.tracks[vO.TRACK_TYPE_AUDIO].get("mainAudio")}getUninitializedAudioHRTCTrack(){const e=this.getAnyAudioHRTCTrack();return null!=e&&e.getTrack()?null:e}getUninitializedVideoHRTCTrack(e){var t;let r;return r=e?this.tracks[vO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(!0),null!==(t=r)&&void 0!==t&&t.getTrack()?null:r}getAudioHRTCTrack(){const e=this.getAnyAudioHRTCTrack();return null!=e&&e.getTrack()?e:null}getUniqueId(){return this.id_}getInfo(){return{moduleName:"Stream",appId:"",roomId:"",userName:"",userId:"",domain:""}}startupPlay(e,t){this.client_.forEach((r=>{r.startupQoSReportPlay(e,t)}))}async play(e,t){const r=XR.getCurrentTimestamp();this.startupPlay(this.getUniqueId(),r),await this.playImpl(e,t)}async playImpl(e,t){let r;if(null!=t&&t.objectFit){if(!/^cover|contain|fill$/.test(t.objectFit))throw this.logger.error(this.module_,"invalid play options.objectFit: ".concat(t.objectFit)),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid play options.objectFit: ".concat(t.objectFit));r=t.objectFit}else r=this.isRemote_&&"auxiliary"===this.getType()?"contain":"cover";const i=!(null==t||!t.muted);if(this.logger.info(this.module_,"stream start to play with elementId: ".concat(e,", options.objectFit: ").concat(r,",options.muted: ").concat(i," resolutionId:").concat(null==t?void 0:t.resolutionId)),!e)throw this.logger.error(this.module_,"elementId:".concat(e," not a invalid HTMLElement Id")),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"elementId:".concat(e," not a invalid HTMLElement Id"));const n=document.getElementById(e);if(!n)throw this.logger.error(this.module_,"document.getElementById by elementId:".concat(e," failed")),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"document.getElementById by elementId:".concat(e," failed"));let o;const s=null!=t&&t.resolutionId?this.getVideoHRTCTrack(t.resolutionId):this.getMaxResolutionHRTCTrack(),a=s?s.getResolutionId():this.id_,c=this.playDivContainers.get(e);if(c){var u;o=c.HTMLElement,n.querySelector("#".concat(o.id))||n.appendChild(o),this.logger.info(this.module_,"get exist player div, key:".concat(e,", div: ").concat(null===(u=c.HTMLElement)||void 0===u?void 0:u.id))}else{o=document.createElement("div"),o.setAttribute("id","player_".concat(a)),o.style.width="100%",o.style.height="100%",o.style.position="relative",o.style.overflow="hidden",o.style["background-color"]="#000",n.appendChild(o);const t={HTMLElement:o,hasVideoTrack:!1,hasAudioTrack:!1};this.playDivContainers.set(e,t),this.logger.info(this.module_,"new player div, key:".concat(e,", div: ").concat(o.id))}o.style.display=null!=t&&t.playerElementHidden?"none":"block",await this.playTracks(e,o,r,i,null==t?void 0:t.resolutionId)}reportCanPlay(e){this.client_.forEach((t=>{t.startupQoSReportCanPlay(e)}))}playerStatusTrace(e){this.logger.debug(this.module_,"playerStatusTrace, ".concat(JSON.stringify(e))),null!=e&&e.event&&"playerCanplay"===e.event&&(e.id=this.getUniqueId(),this.reportCanPlay(e))}async playTracks(e,t,r,i,n){const o=[],s=this.isAuxiliary_?null:this.getAudioHRTCTrack(),a=n?this.getVideoHRTCTrack(n):this.getMaxResolutionHRTCTrack();null!=a&&a.getTrack()&&o.push(a.play(t,e,{objectFit:r,mirror:this.mirror_})),null!=s&&s.getTrack()&&o.push(s.play(t,e,{muted:i})),0!==o.length?(this.off(iC,this.traceHandler),this.on(iC,this.traceHandler),await Promise.all(o).then((r=>{const i=r.filter((e=>null!==e.error));i.length===o.length&&t&&t.remove();const n=r.filter((e=>null===e.error)),s=null==n?void 0:n.some((e=>e.trackType===vO.TRACK_TYPE_AUDIO)),a=null==n?void 0:n.some((e=>e.trackType===vO.TRACK_TYPE_VIDEO));if(this.playDivContainers.has(e)&&this.playDivContainers.set(e,{HTMLElement:t,hasAudioTrack:s,hasVideoTrack:a}),i.length>0)throw i[0].error}))):this.logger.warn(this.module_,"no available track for play")}stop(e){this.stopImpl(e)}stopImpl(e){var t;this.logger.info(this.module_,"stopImpl begin, option:".concat(JSON.stringify(e)));const r=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}),i=[];var n;(!e||e.video&&!e.resolutionIds?i.push(...r):e.video&&null!==(t=e.resolutionIds)&&void 0!==t&&t.length&&e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&i.push(t)})),i.forEach((e=>{e.stop()})),!e||e.audio)&&(null===(n=this.getAudioHRTCTrack())||void 0===n||n.stop())}async resume(e){await this.resumeImpl(e)}async resumeImpl(e){var t;this.logger.info(this.module_,"resumeImpl begin, option:".concat(JSON.stringify(e)));const r=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}),i=[];!e||e.video&&!e.resolutionIds?i.push(...r):e.video&&null!==(t=e.resolutionIds)&&void 0!==t&&t.length&&e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&i.push(t)}));const n=[];if(i.forEach((e=>{n.push(e.resume())})),!e||e.audio){const e=this.getAudioHRTCTrack();e&&n.push(e.resume())}await Promise.all(n)}close(e){this.closeImpl(e)}closeImpl(e){if(this.logger.info(this.module_,"closeImpl begin, options:".concat(JSON.stringify(e))),!e||e.video&&!e.resolutionIds&&e.audio){for(const e of this.getHRTCTracks({hasTrack:!0}))e.close();for(const e of this.playDivContainers.values())e.HTMLElement&&e.HTMLElement.remove();return this.playDivContainers.clear(),void LO.removeEventEmitter(this.eventEmitter)}if(e.video){var t;const r=[];if(null!==(t=e.resolutionIds)&&void 0!==t&&t.length)e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&r.push(t)}));else{const e=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO});r.push(...e)}r.forEach((e=>{const t=null==e?void 0:e.getElementId();if(e.close(),t){const e=this.playDivContainers.get(t);var r,i,n;if(e)if(e.hasVideoTrack=!1,this.logger.debug(this.module_,"closeImpl, elementId:".concat(t,", divInfo: ").concat(null===(r=e.HTMLElement)||void 0===r?void 0:r.id,", hasAudioTrack: ").concat(e.hasAudioTrack,", hasVideoTrack: ").concat(e.hasVideoTrack,"}")),!e.hasAudioTrack)null===(i=this.playDivContainers.get(t))||void 0===i||null===(n=i.HTMLElement)||void 0===n||n.remove(),this.playDivContainers.delete(t),this.logger.info(this.module_,"closeImpl, release elementId: ".concat(t))}}))}e.audio&&this.closeAudio();this.getHRTCTracks({hasTrack:!0}).every((e=>e.isClosed()))&&(LO.removeEventEmitter(this.eventEmitter),this.mediaStream=null)}closeAudio(){const e=this.getAudioHRTCTrack();if(e){const n=e.getElementId();if(e.close(),n){const e=this.playDivContainers.get(n);var t,r,i;if(e)if(e.hasAudioTrack=!1,this.logger.debug(this.module_,"closeAudio, elementId:".concat(n,", divInfo: ").concat(null===(t=e.HTMLElement)||void 0===t?void 0:t.id,", hasAudioTrack: ").concat(e.hasAudioTrack,", hasVideoTrack: ").concat(e.hasVideoTrack,"}")),!e.hasVideoTrack)null===(r=this.playDivContainers.get(n))||void 0===r||null===(i=r.HTMLElement)||void 0===i||i.remove(),this.playDivContainers.delete(n),this.logger.info(this.module_,"closeAudio, release elementId: ".concat(n))}}}muteAudio(){return this.muteAudioImpl()}muteAudioImpl(){try{const e=this.getAudioHRTCTrack();return!!e&&(e.muteTrack(),!0)}catch(jN){return this.logger.error(this.module_,"muteAudio failed: ".concat(jN)),!1}}muteVideo(){return this.muteVideoImpl()}muteVideoImpl(){try{if(!this.hasVideoTrack())return!1;for(const e of this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}))e.muteTrack();return!0}catch(jN){return this.logger.error(this.module_,"muteVideo failed: ".concat(jN)),!1}}unmuteAudio(){return this.unmuteAudioImpl()}unmuteAudioImpl(){try{const e=this.getAudioHRTCTrack();return!!e&&(e.unmuteTrack(),!0)}catch(jN){return this.logger.error(this.module_,"unmuteAudio failed: ".concat(jN)),!1}}unmuteVideo(){return this.unmuteVideoImpl()}unmuteVideoImpl(){try{if(!this.hasVideoTrack())return!1;for(const e of this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}))e.unmuteTrack();return!0}catch(jN){return this.logger.error(this.module_,"unmuteVideo failed: ".concat(jN)),!1}}getId(){var e;return null===(e=this.getMaxResolutionHRTCTrack(!0))||void 0===e?void 0:e.getTrackId()}getUserId(){return this.userId_}getType(){return this.type_}async setAudioOutput(e){return this.setAudioOutputImpl(e)}async setAudioOutputImpl(e){try{const t=this.getAudioHRTCTrack();t&&await t.setSinkId(e),this.stat.reportSwitchDevicesInfo(zC.OUTPUT_AUDIO,e,sA.SUCCESS)}catch(jN){throw this.stat.reportSwitchDevicesInfo(zC.OUTPUT_AUDIO,e,sA.FAIL),jN}}setAudioVolume(e){this.setAudioVolumeImpl(e)}setAudioVolumeImpl(e){const t=this.getAudioHRTCTrack();t&&t.setAudioVolume(e)}getAudioLevel(){const e=this.getAudioHRTCTrack();return e?e.getAudioLevel():0}hasAudioTrack(){return!!this.getAudioHRTCTrack()}hasVideoTrack(){return Array.from(this.tracks[vO.TRACK_TYPE_VIDEO].values()).filter((e=>e.getTrack())).length>0}isAuxiliary(){return this.isAuxiliary_}getAudioTrack(){const e=this.getAudioHRTCTrack();return e?e.getTrack():null}getVideoTrack(e){const t=this.getVideoHRTCTrack(e);return t?t.getTrack():null}getVideoFrame(e){const t=this.getVideoHRTCTrack(e);return t?t.getVideoFrame():null}on(e,t){super.on(e,t,-1===nC.indexOf(e.toString()))}off(e,t){super.off(e,t,-1===nC.indexOf(e.toString()))}async restart(e){var t;if(e)return void(await(null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.restart()));const r=[];for(const i of this.getHRTCTracks({hasTrack:!0}))r.push(i.restart());await Promise.all(r)}async rePlayAudio(){const e=this.getAudioHRTCTrack();e&&!e.isPlaying()&&await e.replay()}getStatInfo(){return{isRemote_:this.isRemote_,type_:this.type_,userId_:this.userId_,id_:this.id_,isAuxiliary_:this.isAuxiliary_}}getStatExtraInfo(){return{isRemote:this.isRemote_,id:this.id_,userId:this.userId_}}hasAudio(){var e;const t=!!(null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack());return this.logger.debug(this.module_,"hasAudio: ".concat(t)),t}hasVideo(){const e=this.hasVideoTrack();return this.logger.debug(this.module_,"hasVideo: ".concat(e)),e}},n(OP.prototype,"getStreamInfo",[vP],Object.getOwnPropertyDescriptor(OP.prototype,"getStreamInfo"),OP.prototype),n(OP.prototype,"play",[yP],Object.getOwnPropertyDescriptor(OP.prototype,"play"),OP.prototype),n(OP.prototype,"stop",[IP],Object.getOwnPropertyDescriptor(OP.prototype,"stop"),OP.prototype),n(OP.prototype,"resume",[TP],Object.getOwnPropertyDescriptor(OP.prototype,"resume"),OP.prototype),n(OP.prototype,"close",[RP],Object.getOwnPropertyDescriptor(OP.prototype,"close"),OP.prototype),n(OP.prototype,"muteAudio",[EP],Object.getOwnPropertyDescriptor(OP.prototype,"muteAudio"),OP.prototype),n(OP.prototype,"muteVideo",[bP],Object.getOwnPropertyDescriptor(OP.prototype,"muteVideo"),OP.prototype),n(OP.prototype,"unmuteAudio",[CP],Object.getOwnPropertyDescriptor(OP.prototype,"unmuteAudio"),OP.prototype),n(OP.prototype,"unmuteVideo",[AP],Object.getOwnPropertyDescriptor(OP.prototype,"unmuteVideo"),OP.prototype),n(OP.prototype,"setAudioOutput",[wP],Object.getOwnPropertyDescriptor(OP.prototype,"setAudioOutput"),OP.prototype),n(OP.prototype,"setAudioVolume",[kP],Object.getOwnPropertyDescriptor(OP.prototype,"setAudioVolume"),OP.prototype),OP),tM=(PP=hP("LocalStream$initialize#Promise"),MP=hP("LocalStream$addAudioTrackCapture#Promise#string"),DP=hP("LocalStream$addVideoTrackCapture#Promise#VideoCaptureOption"),NP=fP("LocalStream$setAudioProfile#void#string|RTCAudioProfile"),UP=hP("LocalStream$setVideoProfile#void#string|RTCVideoProfile"),xP=hP("LocalStream$addResolution#Promise#string|RTCVideoProfile#boolean"),LP=hP("LocalStream$removeResolution#Promise#string"),BP=fP("LocalStream$setScreenProfile#void#string|RTCScreenProfile"),VP=hP("LocalStream$switchDevice#Promise#string#string"),YP=hP("LocalStream$addTrack#Promise#MediaStreamTrack#string"),jP=hP("LocalStream$removeTrack#Promise#MediaStreamTrack#string"),FP=hP("LocalStream$replaceTrack#Promise#MediaStreamTrack#string#string"),HP=fP("LocalStream$bindScreenAudio2RelatedStream#void#LocalStream#boolean"),KP=hP("LocalStream$startAudioMixing#Promise#AudioMixOption"),zP=hP("LocalStream$stopAudioMixing#Promise"),WP=fP("LocalStream$pauseAudioMixing#void"),GP=fP("LocalStream$resumeAudioMixing#void"),JP=fP("LocalStream$setAudioMixingVolume#void#number"),qP=fP("LocalStream$setAudioMixingPosition#void#number"),XP=class extends eM{constructor(e){super({isRemote:!1,type:"local",log:null}),this.module_="LocalStream",this.userId_=e.userId,this.audio_=e.audio,this.microphoneId_=e.microphoneId,this.video_=e.video,this.cameraId_=e.cameraId,this.facingMode_=e.facingMode,this.screen_=e.screen,this.isAuxiliary_=!!this.screen_,this.screenAudio_=e.screenAudio,this.audioSource_=e.audioSource,this.videoSource_=e.videoSource,this.mirror_=e.mirror,this.client_=[],this.audioMixOption_={filePath:null,startTime:0,replace:!1,loop:!1,repeatCount:1},this.audioMixInfo_={audioMixState:SC.IDLE,audioCtx:null,mediaNode:null,sourceNode:null,buffer:null,destNode:null,gainNode:null,gainValue:.5,startAt:0,pauseAt:0,pauseDur:0,playAutoEnded:!1,totalDur:0},this.mutePackageData=new Uint8Array([255,241,80,128,3,223,252,222,2,0,76,97,118,99,53,56,46,55,53,46,49,48,48,0,66,32,8,193,24,56,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28]).buffer,this.muteSendInfo={audioMixState:SC.IDLE,audioCtx:null,mediaNode:null,sourceNode:null,destNode:null},this.screenShareMixInfo={bindStream:null,screenShareAudioNode:null,destNode:null,gainNode:null,gainValue:.5,status:SC.INIT,muteMainAudio:!1},this.videoProfiles_=new Map,this.videoContents=new Map,this.logger.info(this.module_,"new local stream, stream config: ".concat(JSON.stringify(e)))}setMediaStream(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaStream.addTrack(e)}getMediaStream(){return this.mediaStream}getLocalId(){return this.id_}async initialize(){return await this.initializeImpl()}setVideoContentHint(e){if("detail"!==e&&"motion"!==e&&"text"!==e){const e=new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid input parameter type");throw this.logger.error(this.module_,"setVideoContentHint fail, errMsg: ".concat(e)),e}const t=this.getVideoTrack();t&&"contentHint"in t?(t.contentHint=e,this.logger.info(this.module_,"set video track contentHint to: ".concat(e))):this.logger.info(this.module_,"no video track or no video contentHint in track")}async reset(){this.closeImpl();for(const e of this.getHRTCTracks({hasTrack:!0})){const t=e.getTrack();t&&await this.removeTrack(t)}this.tracks[vO.TRACK_TYPE_VIDEO].clear(),this.tracks[vO.TRACK_TYPE_AUDIO].clear()}initAuxStreamWithTrack(e,t){const r=[];if(e){const t=new oP({streamType:yO.STREAM_TYPE_AUX,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:e,event:this.eventEmitter});this.tracks[vO.TRACK_TYPE_AUDIO].set("auxAudio",t),r.push({type:vO.TRACK_TYPE_AUDIO,track:e})}if(t){const e=new oP({streamType:yO.STREAM_TYPE_AUX,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});this.tracks[vO.TRACK_TYPE_VIDEO].set(e.getResolutionId(),e),r.push({type:vO.TRACK_TYPE_VIDEO,track:t})}return this.appendDefaultLocalTrack(this.getMaxResolutionProfile(this.videoProfiles_),this.audioProfile_),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",r)}async initAuxStream(){if(this.audioSource_||this.videoSource_)return this.initAuxStreamWithTrack(this.audioSource_,this.videoSource_);{var e,t,r,i;const n=new oP({streamType:yO.STREAM_TYPE_AUX,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:this.screenProfile_,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o=await n.initScreenShare(this.screenAudio_),s=null===(e=o.find((e=>e.error)))||void 0===e?void 0:e.error;if(s)throw this.logger.error(this.module_,"initAuxStream, fail, errMsg = ".concat(s)),s instanceof qc?new ZP(s.getCode(),s.getMsg(),o):s;this.stat.setMediaCaptureSucc(WC.AUX,null===(t=n.getTrack())||void 0===t?void 0:t.label),this.tracks[vO.TRACK_TYPE_VIDEO].set(n.getResolutionId(),n),this.setMediaStream(null===(r=o.find((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.track)))||void 0===r?void 0:r.track),this.setVideoContentHint("detail");const a=null===(i=o.find((e=>e.type===vO.TRACK_TYPE_AUDIO&&e.track)))||void 0===i?void 0:i.track;return a&&this.tracks[vO.TRACK_TYPE_AUDIO].set("auxAudio",new oP({streamType:yO.STREAM_TYPE_AUX,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:a,event:this.eventEmitter})),this.auxStreamStopByNativeHandler=()=>{this.close(),this.eventEmitter.removeListener(eC,this.auxStreamStopByNativeHandler)},this.eventEmitter.on(eC,this.auxStreamStopByNativeHandler),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",o)}}async initMainStreamWithCfg(){const e=this.getMaxResolutionProfile(this.videoProfiles_);return await this.addCaptureWithCfg(this.video_,this.audio_,e,this.audioProfile_,CC.main)}async initMainStream(){return LO.initDeviceChangedNotify(this.eventEmitter,!0),this.on(UC.CameraChanged,(e=>{"REMOVE"===e.state&&this.clearEffectiveDeviceId(e.deviceId,"videoInput")})),this.on(UC.RecordingDeviceChanged,(e=>{"REMOVE"===e.state&&this.client_.length>0&&this.client_[0].getPublishAudioSender()&&(this.startSendMutePackage(),this.clearEffectiveDeviceId(e.deviceId,"audioInput"))})),this.on(oC.CameraCapture,((e,t)=>{this.setCameraCaptureReport(e,t)})),this.audioSource_||this.videoSource_?this.initMainStreamWithTrack(this.audioSource_,this.videoSource_):await this.initMainStreamWithCfg()}async initializeImpl(){this.logger.info(this.module_,"initializeImpl begin");try{return await this.reset(),this.screen_?await this.initAuxStream():await this.initMainStream()}catch(jN){throw this.logger.error(this.module_,"initializeImpl fail, errMsg:".concat(jN)),"function"!=typeof jN.getMediaCaptureResult&&"function"==typeof jN.getCode?new ZP(jN.getCode(),jN.getMsg(),null):jN}}setCameraCaptureReport(e,t){this.client_.forEach((r=>{r.setCameraCaptureReport(e,t)}))}async addCaptureWithCfg(e,t,r,i,n){this.logger.info(this.module_,"addCaptureWithCfg begin, video:".concat(e,", audio:").concat(t,",")+"camera:".concat(this.getCurrentCameraId(),", microphone:").concat(this.getCurrentMicrophoneId(),",")+"videoProfileInfo:".concat(JSON.stringify(r),", audioProfile:").concat(JSON.stringify(i)));if((this.tracks&&this.tracks[vO.TRACK_TYPE_VIDEO].size)>=2){const e=new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"resolution count can not be greater than ".concat(2));throw this.logger.error(this.module_,"addCaptureWithCfg fail, errMsg is=".concat(e)),e}const o=[];let s,a;e&&(s=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:r,logger:this.logger,resolutionId:r?r.resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o.push(s.initVideoCapture(this.getCurrentCameraId()||this.facingMode_,n))),t&&(a=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:i,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o.push(a.initAudioCapture(this.getCurrentMicrophoneId())));const c=await Promise.all(o);let u=null;for(const l of c)if(l.error)u="".concat(u).concat(u?"":";").concat(l.error.getMsg());else{var d;if(l.type===vO.TRACK_TYPE_AUDIO)this.tracks[vO.TRACK_TYPE_AUDIO].set("mainAudio",a),this.stat.setMediaCaptureSucc(WC.AUDIO,a.getTrack().label);else Array.from(Array.from(this.tracks[vO.TRACK_TYPE_VIDEO].values()).values()).some((e=>e.getTrackMuted()))&&s.muteTrack(),this.tracks[vO.TRACK_TYPE_VIDEO].set(s.getResolutionId(),s),this.stat.setMediaCaptureSucc(WC.VIDEO,null===(d=s.getTrack())||void 0===d?void 0:d.label),r&&this.videoProfiles_.set(s.getResolutionId(),r),this.videoContents.set(s.getResolutionId(),n);this.setMediaStream(l.track),this.appendDefaultLocalTrack(r,i),this.updateEffectiveDeviceInfo(l)}if(u){const e=new ZP(Gc.RTC_ERR_CODE_INVALID_OPERATION,"browser initialize capture fail, ".concat(u),c);throw this.logger.error(this.module_,"addCaptureWithCfg fail, errMsg= ".concat(e)),e}return this.logger.info(this.module_,"addCaptureWithCfg success, camera:".concat(this.getCurrentCameraId(),", microphone:").concat(this.getCurrentMicrophoneId())),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",c)}appendDefaultLocalTrack(e,t){if(!this.getAnyAudioHRTCTrack()){const e=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:t,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter});e.setTrackContentType(CC.main),this.tracks[vO.TRACK_TYPE_AUDIO].set("mainAudio",e),this.logger.info(this.module_,"addDefaultEmptyTrack success, audioTrack:".concat(e.getResolutionId(),",")+"track profile:".concat(JSON.stringify(e.getTrackProfile())))}if(!this.getAnyVideoHRTCTrack(null==e?void 0:e.resolutionId)){const t=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:e,logger:this.logger,resolutionId:e?e.resolutionId:this.generateResolutionId(),event:this.eventEmitter});t.setTrackContentType(CC.main),this.tracks[vO.TRACK_TYPE_VIDEO].set(t.getResolutionId(),t),this.logger.info(this.module_,"addDefaultEmptyTrack success, videoTrack:".concat(t.getResolutionId(),",")+"track profile:".concat(JSON.stringify(t.getTrackProfile())))}}generateResolutionId(){return this.id_+"-"+XR.generateRandomId(8,16)}initMainStreamWithTrack(e,t){const r=[];if(e){const t=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:e,event:this.eventEmitter});this.tracks[vO.TRACK_TYPE_AUDIO].set("mainAudio",t),r.push({type:vO.TRACK_TYPE_AUDIO,track:e})}if(t){const e=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});this.tracks[vO.TRACK_TYPE_VIDEO].set(e.getResolutionId(),e),r.push({type:vO.TRACK_TYPE_VIDEO,track:t})}return this.appendDefaultLocalTrack(this.getMaxResolutionProfile(this.videoProfiles_),this.audioProfile_),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",r)}async addAudioTrackCapture(e){return await this.addAudioTrackCaptureImpl(e)}async addAudioTrackCaptureImpl(e){var t;this.logger.info(this.module_,"addAudioTrackCaptureImpl, microphoneId: ".concat(e));const r=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:this.audioProfile_,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),i=await r.initAudioCapture(e||this.microphoneId_);if(i.error)throw this.logger.error(this.module_,"addAudioTrackCaptureImpl fail, errMsg: ".concat(i.error)),i.error;return this.stat.setMediaCaptureSucc(WC.AUDIO,null===(t=i.track)||void 0===t?void 0:t.label),this.updateEffectiveDeviceInfo(i),await this.addTrackImpl(i.track),i.track}async addVideoTrackCapture(e){return await this.addVideoTrackCaptureImpl(e)}async addVideoTrackCaptureImpl(e){var t;this.logger.info(this.module_,"addVideoTrackCaptureImpl, option: ".concat(JSON.stringify(e)));const r=null==e?void 0:e.resolutionId,i=r?this.videoProfiles_.get(r):this.getMaxResolutionProfile(this.videoProfiles_),n=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:i,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o=(null==e?void 0:e.cameraId)||this.cameraId_||this.facingMode_,s=await n.initVideoCapture(o,r?this.videoContents.get(r):CC.main);if(s.error)throw this.logger.error(this.module_,"addVideoTrackCaptureImpl fail, errMsg: ".concat(s.error)),s.error;return this.updateEffectiveDeviceInfo(s),this.stat.setMediaCaptureSucc(WC.AUDIO,null===(t=s.track)||void 0===t?void 0:t.label),await this.addTrackImpl(s.track,r),s.track}updateEffectiveDeviceInfo(e){e.type===vO.TRACK_TYPE_VIDEO?(this.effectiveCameraId_=e.track.getSettings().deviceId,this.logger.info(this.module_,"updateEffectiveDeviceInfo, effectiveCameraId_: ".concat(this.effectiveCameraId_))):e.type===vO.TRACK_TYPE_AUDIO&&(this.effectiveMicrophoneId_=e.track.getSettings().deviceId,this.logger.info(this.module_,"updateEffectiveDeviceInfo, effectiveMicrophoneId_: ".concat(this.effectiveMicrophoneId_)))}getCurrentCameraId(){return this.cameraId_||this.effectiveCameraId_}getCurrentMicrophoneId(){return this.microphoneId_||this.effectiveMicrophoneId_}getAudioSendBitrate(){const e=this.getAudioHRTCTrack();return e?e.getTrackProfile().bitrate:0}isAudioMuted(){const e=this.getAudioHRTCTrack();return!e||e.getTrackMuted()}isVideoMuted(e){const t=this.getVideoHRTCTrack(e);return!t||t.getTrackMuted()}setAudioProfile(e){this.setAudioProfileImpl(e)}setAudioProfileImpl(e){const t=this.getAudioHRTCTrack();this.audioProfile_=e,null==t||t.setTrackProfile(e)}getVideoMaxBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.maxBitrate:0}getVideoMaxSendBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.maxBitrate<35e4?r.maxBitrate-2e4:r.maxBitrate:0}getVideoMiniBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.minBitrate:0}getVideoWidth(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.width:0}getVideoHeight(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.height:0}getVideoFrameRate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.frameRate:0}getVideoProfile(e){var t;return null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile()}async setVideoProfile(e,t){await this.setVideoProfileImpl(e,t)}async addResolution(e,t){return await this.addResolutionImpl(e,t)}async addResolutionImpl(e,t){try{if(this.videoSource_||this.audioSource_)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"localStream created by videoSource or audioSource");const r=ZO.formatVideoProfile(e),i={resolutionId:this.generateResolutionId(),width:r.width,height:r.height,frameRate:r.frameRate,minBitrate:r.minBitrate,maxBitrate:r.maxBitrate};this.logger.info(this.module_,"addResolutionImpl begin, profile:".concat(JSON.stringify(i)," ")),await this.addCaptureWithCfg(!0,t,i,this.audioProfile_,CC.slides);for(const e of this.client_)await e.publish(this);return this.logger.info(this.module_,"addResolutionImpl success"),i}catch(jN){throw this.logger.error(this.module_,"addResolutionImpl fail, errMsg:".concat(jN)),"function"!=typeof jN.getMediaCaptureResult?new ZP(jN.getCode(),jN.getMsg(),null):jN}}async removeResolution(e){return this.removeResolutionImpl(e)}async removeResolutionImpl(e){this.logger.info(this.module_,"removeResolutionImpl begin, resolutionId:".concat(e));const t=this.getVideoHRTCTrack(e);if(!t)throw this.logger.error(this.module_,"removeResolutionImpl, resolutionId:".concat(e," not found ")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"resolutionId:".concat(e," not found"));this.tracks[vO.TRACK_TYPE_VIDEO].delete(e),t.removeTrack();const r=this.getHRTCTracks({mediaType:vO.TRACK_TYPE_VIDEO});r&&0!==r.length||this.tracks[vO.TRACK_TYPE_AUDIO].delete("mainAudio");for(const i of this.client_)await i.publish(this);this.logger.info(this.module_,"removeResolutionImpl success, resolutionId:".concat(e))}async setVideoProfileImpl(e,t){var r;this.logger.info(this.module_,"setVideoProfile begin, profile: ".concat(JSON.stringify(e)));const i=this.getVideoHRTCTrack(t),n=ZO.formatVideoProfile(e);if(!i){const e=this.generateResolutionId();return void this.videoProfiles_.set(e,n)}const o={};XR.isSupportConstraints("aspectRatio")&&(o.aspectRatio={ideal:n.width/n.height}),o.width={ideal:n.width},o.height={ideal:n.height},o.frameRate={ideal:n.frameRate},await(null===(r=i.getTrack())||void 0===r?void 0:r.applyConstraints(o).then((()=>{this.logger.info(this.module_,"setVideoProfile, constraint: ".concat(JSON.stringify(i.getTrack().getConstraints()))),i.setLocalProfileByTrack(i.getTrack()),this.videoProfiles_.set(i.getResolutionId(),n),this.client_.forEach((async e=>{if(e){const t=e.getMainStreamSenderByTrack(i.getTrackId());await e.setSendBitrate(t,this.getVideoMaxSendBitrate(i.getResolutionId()),this.isAuxiliary()?"auxVideo":"mainVideo"),await e.publish(this)}}))})))}getScreenSendBitrate(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().bitrate:0}getScreenWidth(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().width:0}getScreenHeight(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().height:0}getScreenFrameRate(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().frameRate:0}setScreenProfile(e){this.setScreenProfileImpl(e)}setScreenProfileImpl(e){const t=this.getVideoHRTCTrack();this.screenProfile_=e,t&&t.setTrackProfile(e)}async switchVideoDevice(e){var t;this.logger.info(this.module_,"switchVideoDevice begin, cameraId is ".concat(e));const r=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO});if(0===r.length)return void this.logger.error(this.module_,"switchVideoDevice failed, no video tracks");const i=[];for(const d of r){var n;null===(n=this.mediaStream)||void 0===n||n.removeTrack(d.getTrack()),d.setTrackProfile(this.videoProfiles_.get(d.getResolutionId())),i.push(d.initVideoCapture(e,d.getTrackContentType()))}const o=await Promise.all(i),s=[];for(const d of o){var a,c,u;if(d.error)throw d.error;null===(a=this.mediaStream)||void 0===a||a.addTrack(d.track);const e=d.track.getConstraints(),t=d.track.getSettings(),i="number"==typeof e.width?e.width:(null===(c=e.width)||void 0===c?void 0:c.ideal)||t.width,n="number"==typeof e.height?e.height:(null===(u=e.height)||void 0===u?void 0:u.ideal)||t.height,o=r.find((e=>{const t=e.getTrackProfile();return t.width===i&&t.height===n}));for(const r of this.client_){const e=r.getMainStreamSenderByTrack(null==o?void 0:o.getTrackId());e&&s.push(e.replaceTrack(d.track))}}if(o.length&&(this.cameraId_=e,this.effectiveCameraId_=e),0!==s.length){this.stat.setMediaCaptureSucc(WC.VIDEO,null===(t=o[0].track)||void 0===t?void 0:t.label),await Promise.all(s);for(const e of this.client_)await e.publish(this);this.logger.info(this.module_,"switchVideoDevice success")}else this.logger.debug(this.module_,"switchVideoDevice, no need replace sender track")}async switchAudioDevice(e){var t,r,i;this.logger.info(this.module_,"switchAudioDevice begin, microphoneId is ".concat(e));const n=this.getAudioHRTCTrack();if(!n)return void this.logger.error(this.module_,"switchAudioDevice failed, no audio tracks");null===(t=this.mediaStream)||void 0===t||t.removeTrack(n.getTrack());const o=await n.initAudioCapture(e);if(o.error)throw o.error;this.stat.setMediaCaptureSucc(WC.AUDIO,null===(r=o.track)||void 0===r?void 0:r.label),this.replaceMixAudioTrack(o.track),null===(i=this.mediaStream)||void 0===i||i.addTrack(o.track);const s=[];this.client_.forEach((e=>{const t=e.getPublishAudioSender();t&&s.push(t.replaceTrack(this.getPublishAudioTrack()))})),0===s.length&&this.logger.info(this.module_,"switchAudioDevice, no need replace sender track"),this.microphoneId_=e,this.effectiveMicrophoneId_=e,await Promise.all(s)}async switchDevice(e,t){return await this.switchDeviceImpl(e,t)}async switchDeviceImpl(e,t){return new Promise(((r,i)=>{if(this.logger.info(this.module_,"switchDeviceImpl begin, type:".concat(e,", deviceId:").concat(t)),e===vO.TRACK_TYPE_AUDIO){if("default"!==t&&(this.effectiveMicrophoneId_===t||this.audioSource_))return void r();this.switchAudioDevice(t).then((()=>{this.stopSendMutePackage(),this.stat.reportSwitchDevicesInfo(zC.INPUT_AUDIO,t,sA.SUCCESS),r()})).catch((e=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_AUDIO,t,sA.FAIL),this.logger.error(this.module_,"switchDevice failed, errmsg= ".concat(e)),i(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR))}))}else if(e===vO.TRACK_TYPE_VIDEO){if(this.effectiveCameraId_===t||this.videoSource_)return void r();this.switchVideoDevice(t).then((()=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_VIDEO,t,sA.SUCCESS),r()})).catch((e=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_VIDEO,t,sA.FAIL),this.logger.error(this.module_,"switchDevice failed, errmsg= ".concat(e)),i(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR))}))}else i(new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"invalid media type:".concat(e)))}))}async addTrack(e,t){return await this.addTrackImpl(e,t)}async addTrackImpl(e,t){var r;if(!e)throw this.logger.error(this.module_,"addTrack, track is null"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"track is null");if(this.logger.info(this.module_,"addTrackImpl begin, resolutionId:".concat(t,", physical track id:").concat(e.id)),e.kind===vO.TRACK_TYPE_AUDIO){const r=this.getUninitializedAudioHRTCTrack();if(!r)throw this.logger.error(this.module_,"addTrackImpl failed, audio track already exist"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"audio track already exist");{await r.replaceTrack(e),this.replaceMixAudioTrack(e);const i=this.getAnyVideoHRTCTrack(t),n=null!=i&&i.isPlaying()?i:null;n&&await this.play(n.getElementId(),{objectFit:n.getObjectFit(),muted:n.getTrackMuted(),resolutionId:n.getResolutionId()}),this.logger.info(this.module_,"addTrackImpl success , track type is audio,"+"physical track id:".concat(e.id))}}else{const r=this.getUninitializedVideoHRTCTrack(t);if(!r)throw this.logger.error(this.module_,"addTrackImpl failed, video track already exist"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"video track already exist");{await r.replaceTrack(e);const t=this.getAnyAudioHRTCTrack(),i=null!=t&&t.isPlaying()?t:null;i&&await this.play(i.getElementId(),{objectFit:i.getObjectFit(),muted:i.getTrackMuted(),resolutionId:null}),this.logger.info(this.module_,"addTrackImpl success , track type is video,"+"physical track id:".concat(e.id))}}null===(r=this.mediaStream)||void 0===r||r.addTrack(e);for(const i of this.client_)i&&await i.publish(this)}async removeTrack(e){return await this.removeTrackImpl(e)}async removeTrackImpl(e){var t;if(!e)throw this.logger.error(this.module_,"removeTrack, track is null"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"track is null");if(e.kind===vO.TRACK_TYPE_AUDIO)for(const[n,o]of this.tracks[vO.TRACK_TYPE_AUDIO]){var r;e.id===(null==o||null===(r=o.getTrack())||void 0===r?void 0:r.id)&&(o.removeTrack(),this.tracks[vO.TRACK_TYPE_AUDIO].set(n,o),this.logger.info(this.module_,"removeTrackImpl success , track type is ".concat(o.getTrackType(),",")+"physical track id:".concat(e.id)))}else for(const[n,o]of this.tracks[vO.TRACK_TYPE_VIDEO]){var i;e.id===(null==o||null===(i=o.getTrack())||void 0===i?void 0:i.id)&&(o.removeTrack(),this.tracks[vO.TRACK_TYPE_VIDEO].set(n,o),this.logger.info(this.module_,"removeTrackImpl success , track type is ".concat(o.getTrackType(),",")+"physical track id:".concat(e.id)))}null===(t=this.mediaStream)||void 0===t||t.removeTrack(e);for(const n of this.client_)n&&await n.publish(this)}async replaceTrack(e,t,r){return await this.replaceTrackImpl(e,t,r)}async replaceTrackImpl(e,t,r){var i,n,o;if(!e)throw this.logger.error(this.module_,"replaceTrack, track is null"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);let s;t===vO.TRACK_TYPE_AUDIO?(s=this.getAudioHRTCTrack(),this.replaceMixAudioTrack(e)):t===vO.TRACK_TYPE_VIDEO&&(s=this.getVideoHRTCTrack(r)),null===(i=this.mediaStream)||void 0===i||i.removeTrack(s.getTrack()),null===(n=this.mediaStream)||void 0===n||n.addTrack(e),await(null===(o=s)||void 0===o?void 0:o.replaceTrack(e));for(const a of this.client_)a&&await a.publish(this)}addClient(e){this.client_=this.client_.filter((t=>t&&t.getSymbol()!==e.getSymbol())),e&&this.client_.push(e)}removeClient(e){e&&-1!==this.client_.indexOf(e)&&this.client_.splice(this.client_.indexOf(e),1)}muteAudio(){return!!super.muteAudio()&&(this.stat.reportAudioMuteInfo(1,!0),this.client_.forEach((e=>{e.changeStreamMuteStatusNotify(!0,vO.TRACK_TYPE_AUDIO),e.reportAudioMuteInfo(1,!0)})),!0)}muteVideo(){return!!super.muteVideo()&&(this.stat.reportVideoMuteInfo(this.userId_,!0),this.client_.forEach((e=>{var t;const r=(null===(t=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}))||void 0===t?void 0:t.length)>1;e.changeStreamMuteStatusNotify(!0,vO.TRACK_TYPE_VIDEO,this.isAuxiliary_?CC.desktop:CC.main,r),e.reportVideoMuteInfo(this.userId_,!0)})),!0)}unmuteAudio(){return!!super.unmuteAudio()&&(this.stat.reportAudioMuteInfo(1,!1),this.client_.forEach((e=>{e.changeStreamMuteStatusNotify(!1,vO.TRACK_TYPE_AUDIO),e.reportAudioMuteInfo(1,!1)})),!0)}unmuteVideo(){return!!super.unmuteVideo()&&(this.stat.reportVideoMuteInfo(this.userId_,!1),this.client_.forEach((e=>{var t;const r=(null===(t=this.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}))||void 0===t?void 0:t.length)>1;e.changeStreamMuteStatusNotify(!1,vO.TRACK_TYPE_VIDEO,this.isAuxiliary_?CC.desktop:CC.main,r),e.reportVideoMuteInfo(this.userId_,!1)})),!0)}closeImpl(e){!1!==(null==e?void 0:e.audio)&&(this.closeScreenShareAudio(),this.isAuxiliary()||this.audioMixInfo_.playAutoEnded||this.audioMixInfo_.audioMixState===SC.IDLE||this.audioMixInfo_.audioMixState===SC.INIT||this.stopAudioMixing()),super.closeImpl(e)}clearEffectiveDeviceId(e,t){this.logger.info(this.module_,"clearEffectiveDeviceId, Input:".concat(e,", type:").concat(t)),"audioInput"===t?this.effectiveMicrophoneId_===e&&(this.effectiveMicrophoneId_="",this.logger.info(this.module_,"clearEffectiveDeviceId, audioInput:".concat(e))):"videoInput"===t&&this.effectiveCameraId_===e&&(this.effectiveCameraId_="",this.logger.info(this.module_,"clearEffectiveDeviceId, videoInput:".concat(e)))}startSendMutePackage(){var e;this.logger.debug(this.module_,"start SendMutePackage");const t=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();if(!t||"ended"!==t.readyState)return void this.logger.info(this.module_,"removed device is not in use, startSendMutePackage end");if(this.muteSendInfo.audioMixState!=SC.IDLE||!this.client_[0].getPublishAudioSender())return void this.logger.info(this.module_,"the condition is not met, startSendMutePackage end");this.muteSendInfo.audioCtx||(this.muteSendInfo.audioCtx=new AudioContext);let r=this.mutePackageData.slice(0);this.muteSendInfo.audioCtx.decodeAudioData(r,(e=>{var t;this.muteSendInfo.destNode=this.muteSendInfo.audioCtx.createMediaStreamDestination(),this.muteSendInfo.sourceNode=this.muteSendInfo.audioCtx.createBufferSource(),this.muteSendInfo.sourceNode.buffer=e,this.muteSendInfo.sourceNode.connect(this.muteSendInfo.destNode),this.muteSendInfo.sourceNode.loop=!0,this.muteSendInfo.sourceNode.start(0,0),this.muteSendInfo.audioMixState=SC.PLAY,null===(t=this.client_[0].getPublishAudioSender())||void 0===t||t.replaceTrack(this.muteSendInfo.destNode.stream.getAudioTracks()[0]),this.logger.info(this.module_,"startSendMutePackage success"),r=null}),(()=>{this.muteSendInfo.audioMixState=SC.IDLE,this.logger.info(this.module_,"startSendMutePackage failed"),r=null}))}stopSendMutePackage(){var e,t,r;this.logger.info(this.module_,"stopSendMutePackage begin"),this.muteSendInfo.audioMixState===SC.PLAY?(null===(e=this.muteSendInfo.mediaNode)||void 0===e||e.connect(this.muteSendInfo.destNode),null===(t=this.muteSendInfo.sourceNode)||void 0===t||t.stop(),null===(r=this.muteSendInfo.sourceNode)||void 0===r||r.disconnect(),this.muteSendInfo.sourceNode=null,this.muteSendInfo.audioMixState=SC.IDLE):this.logger.info(this.module_,"stopSendMutePackage end")}bindScreenAudio2RelatedStream(e,t){this.bindScreenAudio2RelatedStreamImpl(e,t)}bindScreenAudio2RelatedStreamImpl(e,t){if(this.logger.info(this.module_,"bindScreenAudio2RelatedStreamImpl, streamId: ".concat(e.getId())),t&&!e.hasAudioTrack()){const t=this.getAudioTrack();if(t){const r=new oP({streamType:yO.STREAM_TYPE_MAIN,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});e.tracks[vO.TRACK_TYPE_AUDIO].set("mainAudio",r)}}this.screenShareMixInfo.bindStream=e,e.screenShareMixInfo.bindStream=this;this.mixScreenAudio(t)||(this.screenShareMixInfo.bindStream=null,e.screenShareMixInfo.bindStream=null)}mixScreenAudio(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const r=this.screenShareMixInfo.bindStream;if(!this.isAuxiliary()||null==r||!r.getAudioHRTCTrack()||!this.getAudioHRTCTrack())return this.logger.error(this.module_,"mixScreenAudio2MainStreamAudio failed, isAuxiliary: ".concat(this.isAuxiliary()," ,main stream or audio track is null")),!1;if(this.screenShareMixInfo.status=SC.PLAY,!r.audioMixInfo_.audioCtx){var i;r.audioMixInfo_.audioCtx=new AudioContext,r.audioMixInfo_.destNode=r.audioMixInfo_.audioCtx.createMediaStreamDestination();const e=null===(i=r.getAudioHRTCTrack())||void 0===i?void 0:i.getTrack();e&&(r.audioMixInfo_.mediaNode=r.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),r.audioMixInfo_.mediaNode.connect(r.audioMixInfo_.destNode))}t&&(r.audioMixInfo_.mediaNode.disconnect(r.screenShareMixInfo.destNode),this.logger.info(this.module_,"mixScreenAudio2MainStreamAudio, only play screen share audio stream"));const n=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();return this.screenShareMixInfo.screenShareAudioNode=r.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([n])),this.screenShareMixInfo.destNode=r.audioMixInfo_.destNode,this.screenShareMixInfo.gainNode=r.audioMixInfo_.audioCtx.createGain(),this.screenShareMixInfo.gainNode.gain.value=this.screenShareMixInfo.gainValue,this.screenShareMixInfo.screenShareAudioNode.connect(this.screenShareMixInfo.gainNode),this.screenShareMixInfo.gainNode.connect(this.screenShareMixInfo.destNode),this.screenShareMixInfo.muteMainAudio=t,!0}getPublishAudioTrack(){var e;if(this.isAuxiliary()){if(this.screenShareMixInfo.destNode&&this.screenShareMixInfo.destNode.stream){const e=this.screenShareMixInfo.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}else{const e=this.screenShareMixInfo.bindStream;if(e){const t=e.client_.length>0&&e.client_[0].getPublishVideoSender(yO.STREAM_TYPE_AUX).length,r=this.audioMixInfo_.audioMixState===SC.PAUSE||this.audioMixInfo_.audioMixState===SC.PLAY;if((t||r)&&this.audioMixInfo_.destNode&&this.audioMixInfo_.destNode.stream){const e=this.audioMixInfo_.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}else if(this.audioMixInfo_.destNode&&this.audioMixInfo_.destNode.stream){const e=this.audioMixInfo_.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}return null===(e=super.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack()}async resumeMixScreenAudio(){const e=this.screenShareMixInfo.bindStream;if(!(this.isAuxiliary()&&e&&this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.destNode))return void this.logger.info(this.module_,"cannot resumeMixScreenAudio, isAuxiliary: ".concat(this.isAuxiliary()));this.screenShareMixInfo.gainNode.connect(this.screenShareMixInfo.destNode);const t=e.client_.length>0&&e.client_[0].getPublishAudioSender(),r=this.client_.length>0&&this.client_[0].getPublishVideoSender(yO.STREAM_TYPE_AUX).length;t&&r&&await e.client_[0].getPublishAudioSender().replaceTrack(this.getPublishAudioTrack())}async stopMixScreenAudio(){this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.destNode?this.screenShareMixInfo.gainNode.disconnect(this.screenShareMixInfo.destNode):this.logger.info(this.module_,"stopScreenAudio gainNode or destNode is null")}setAudioVolume(e){if(this.isAuxiliary()){if(!this.screenShareMixInfo.bindStream||this.screenShareMixInfo.status!==SC.PLAY)return void this.logger.error(this.module_,"setScreenAudioVolume failed for play status error");const t=e/100;this.logger.info(this.module_,"setScreenAudioVolume: "+t),this.screenShareMixInfo.gainNode.gain.value=t,this.screenShareMixInfo.gainValue=t}else super.setAudioVolume(e)}closeScreenShareAudio(){if(this.isAuxiliary())this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.gainNode.disconnect(),this.screenShareMixInfo.screenShareAudioNode&&this.screenShareMixInfo.screenShareAudioNode.disconnect(),this.screenShareMixInfo.gainNode=null,this.screenShareMixInfo.gainValue=.5,this.screenShareMixInfo.screenShareAudioNode=null,this.screenShareMixInfo.bindStream=null,this.screenShareMixInfo.status=SC.INIT;else{const e=this.screenShareMixInfo.bindStream;if(!e)return void this.logger.debug(this.module_,"closeScreenShareAudio, no need closeScreenShareAudio, aux stream is null");e.closeScreenShareAudio(),this.screenShareMixInfo.bindStream=null}}async startAudioMixing(e){await this.startAudioMixingImpl(e),this.eventEmitter.emit(rC),this.logger.info(this.module_,"emit ".concat(rC," at startAudioMixing"))}async startAudioMixingImpl(e){var t,r;if(this.logger.info(this.module_,"startAudioMixing start at: "+e.startTime),this.checkAudioMixingParameter(),this.audioMixInfo_.audioMixState===SC.IDLE&&this.initIdleAudioMixInfo(),this.audioMixInfo_.audioMixState!==SC.INIT)throw this.logger.error(this.module_,"startAudioMixing status: ".concat(this.audioMixInfo_.audioMixState)),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"startAudioMixing status: ".concat(this.audioMixInfo_.audioMixState));(this.setAudioMixOption(e),this.audioMixOption_.replace)?this.logger.info(this.module_,"startAudioMixing: replace"):null===(r=this.audioMixInfo_.mediaNode)||void 0===r||r.connect(this.audioMixInfo_.destNode);await(null===(t=this.client_[0].getPublishAudioSender())||void 0===t?void 0:t.replaceTrack(this.audioMixInfo_.destNode.stream.getAudioTracks()[0]));try{const e=await AA.fetch(this.audioMixOption_.filePath);await this.audioMixInfo_.audioCtx.decodeAudioData(e.data,(e=>{this.audioMixInfo_.startAt=XR.getCurrentTimestamp(),this.audioMixInfo_.pauseAt=0,this.audioMixInfo_.pauseDur=0,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.totalDur=0,this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at startAudioMixingImpl")))},this.audioMixInfo_.sourceNode.buffer=e,this.audioMixInfo_.buffer=e,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode),this.audioMixInfo_.audioMixState=SC.PLAY,this.logger.info(this.module_,"startAudioMixing, duration: ".concat(this.getAudioMixingDuration())),this.doAudioMixing(),this.logger.info(this.module_,"startAudioMixing end")}),(e=>{throw this.logger.error(this.module_,"startAudioMixing, decode audio failed"),e}))}catch(jN){var i,n,o;if(this.logger.error(this.module_,"startAudioMixing failed: ".concat(jN)),this.audioMixInfo_.audioMixState=SC.INIT,!this.audioMixOption_.replace)null===(o=this.audioMixInfo_.mediaNode)||void 0===o||o.disconnect(this.audioMixInfo_.destNode);throw null===(i=this.client_[0].getPublishAudioSender())||void 0===i||i.replaceTrack(null===(n=this.getAudioHRTCTrack())||void 0===n?void 0:n.getTrack()),jN}}doAudioMixing(){if(this.audioMixOption_.repeatCount>1){if(this.audioMixOption_.startTime>=this.getAudioMixingDuration())throw this.logger.error(this.module_,"startAudioMixing: ".concat(this.audioMixInfo_.audioMixState)),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"startAudioMixing: not valid startTime");this.audioMixInfo_.sourceNode.loop=!0;const e=this.audioMixOption_.repeatCount*this.getAudioMixingDuration()-this.audioMixOption_.startTime;this.audioMixInfo_.totalDur=e,this.audioMixInfo_.sourceNode.start(0,this.audioMixOption_.startTime/1e3,e/1e3)}else this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixOption_.loop?this.audioMixInfo_.totalDur=1/0:(this.getAudioMixingDuration()<=this.audioMixOption_.startTime&&(this.logger.info(this.module_,"startAudioMixing, bookmark: ".concat(this.audioMixOption_.startTime," invalid and reset to begin.")),this.audioMixOption_.startTime=0),this.audioMixInfo_.totalDur=this.getAudioMixingDuration()-this.audioMixOption_.startTime),this.audioMixInfo_.sourceNode.start(0,this.audioMixOption_.startTime/1e3)}setAudioMixOption(e){e.replace||(e.replace=!1),e.startTime||(e.startTime=0),e.loop||(e.loop=!1),e.repeatCount&&!e.loop||(e.repeatCount=0),this.audioMixOption_=e}initIdleAudioMixInfo(){if(!this.audioMixInfo_.audioCtx){var e;this.audioMixInfo_.audioCtx=new AudioContext,this.audioMixInfo_.destNode=this.audioMixInfo_.audioCtx.createMediaStreamDestination();const t=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();t&&(this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([t])))}this.audioMixInfo_.gainNode=this.audioMixInfo_.audioCtx.createGain(),this.audioMixInfo_.gainNode.gain.value=this.audioMixInfo_.gainValue,this.audioMixInfo_.audioMixState=SC.INIT}checkAudioMixingParameter(){if(!this.client_||this.client_.length<1||!this.client_[0].getPublishAudioSender())throw this.logger.error(this.module_,"startAudioMixing failed"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"no mediaStream or no client or no audio!")}replaceMixAudioTrack(e){if(this.audioMixInfo_.audioMixState!==SC.IDLE&&this.audioMixInfo_.audioMixState!==SC.INIT&&this.audioMixInfo_.mediaNode&&this.audioMixInfo_.destNode){if(this.audioMixOption_.replace)return;return this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode),this.audioMixInfo_.mediaNode=null,this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),void this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode)}if(!this.isAuxiliary_){var t;const r=null===(t=this.screenShareMixInfo.bindStream)||void 0===t?void 0:t.screenShareMixInfo;r&&!r.muteMainAudio&&this.audioMixInfo_.audioCtx&&this.audioMixInfo_.destNode&&(this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode))}}async stopAudioMixing(){await this.stopAudioMixingImpl()}async stopAudioMixingImpl(){if(!this.audioMixInfo_.playAutoEnded)if(this.audioMixInfo_.audioMixState!==SC.IDLE&&this.audioMixInfo_.audioMixState!==SC.INIT){try{var e,t;await(null===(e=this.client_[0].getPublishAudioSender())||void 0===e?void 0:e.replaceTrack(null===(t=this.getAudioHRTCTrack())||void 0===t?void 0:t.getTrack()))}catch(Dw){throw this.logger.error(this.module_,"stopAudioMixing: ".concat(this.audioMixInfo_.audioMixState,", errMsg = ").concat(Dw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}var r;if(this.logger.info(this.module_,"stopAudioMixing"),!this.audioMixOption_.replace&&this.audioMixInfo_.audioMixState!==SC.PAUSE)null===(r=this.audioMixInfo_.mediaNode)||void 0===r||r.disconnect(this.audioMixInfo_.destNode);this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.buffer=null,this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.gainValue=.5,this.audioMixInfo_.sourceNode=null,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.audioMixState=SC.INIT}else this.logger.info(this.module_,"stopAudioMixing: ".concat(this.audioMixInfo_.audioMixState))}pauseAudioMixing(){this.pauseAudioMixingImpl()}pauseAudioMixingImpl(){if(this.audioMixInfo_.audioMixState===SC.PLAY){this.logger.info(this.module_,"pauseAudioMixing"),this.audioMixOption_.replace||this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode);try{var e,t;null===(e=this.client_[0].getPublishAudioSender())||void 0===e||e.replaceTrack(null===(t=this.getAudioHRTCTrack())||void 0===t?void 0:t.getTrack())}catch(Dw){throw this.logger.error(this.module_,"pauseAudioMixing, errMsg = ".concat(Dw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.pauseAt=XR.getCurrentTimestamp(),this.audioMixInfo_.audioMixState=SC.PAUSE}else this.logger.error(this.module_,"pauseAudioMixing: ".concat(this.audioMixInfo_.audioMixState))}resumeAudioMixing(){this.resumeAudioMixingImpl(),this.eventEmitter.emit(rC),this.logger.info(this.module_,"emit ".concat(rC," at resumeAudioMixing"))}resumeAudioMixingImpl(){if(this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"resumeAudioMixing: ".concat(this.audioMixInfo_.audioMixState));this.logger.info(this.module_,"resumeAudioMixing"),this.audioMixOption_.replace||this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode);try{var e;null===(e=this.client_[0].getPublishAudioSender())||void 0===e||e.replaceTrack(this.audioMixInfo_.destNode.stream.getAudioTracks()[0])}catch(Dw){throw this.logger.error(this.module_,"pauseAudioMixing, errMsg = ".concat(Dw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at resumeAudioMixingImpl")))},this.audioMixInfo_.sourceNode.buffer=this.audioMixInfo_.buffer,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode);const t=this.audioMixInfo_.pauseAt-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur,r=t+this.audioMixOption_.startTime;if(this.audioMixOption_.repeatCount>1){this.audioMixInfo_.sourceNode.loop=!0;const e=this.audioMixOption_.repeatCount*this.getAudioMixingDuration()-this.audioMixOption_.startTime-t;this.audioMixInfo_.sourceNode.start(0,r%this.getAudioMixingDuration()/1e3,e/1e3)}else this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixInfo_.sourceNode.start(0,r%this.getAudioMixingDuration()/1e3);this.audioMixInfo_.pauseDur=this.audioMixInfo_.pauseDur+XR.getCurrentTimestamp()-this.audioMixInfo_.pauseAt,this.audioMixInfo_.audioMixState=SC.PLAY}getAudioMixingCurrentPosition(){let e=0;if(this.audioMixInfo_.audioMixState===SC.PAUSE)e=this.audioMixInfo_.pauseAt;else{if(this.audioMixInfo_.audioMixState!==SC.PLAY)return 0;e=XR.getCurrentTimestamp()}const t=this.getAudioMixingDuration();let r=(e-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur+this.audioMixOption_.startTime)%t;return r=Math.min(Math.round(r),t),this.logger.debug(this.module_,"getAudioMixingDuration: ".concat(r)),r}getAudioMixingDuration(){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return this.logger.error(this.module_,"getAudioMixingDuration failed for play status error"),0;const e=1e3*this.audioMixInfo_.sourceNode.buffer.duration;return this.logger.debug(this.module_,"getAudioMixingDuration: ".concat(e)),e}setAudioMixingVolume(e){this.setAudioMixingVolumeImpl(e)}setAudioMixingVolumeImpl(e){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"setAudioMixingVolume failed for play status error");const t=e/100;this.logger.debug(this.module_,"setAudioMixingVolume: "+t),this.audioMixInfo_.gainValue=t,this.audioMixInfo_.gainNode.gain.value=t}setAudioMixingPosition(e){this.setAudioMixingPositionImpl(e)}setAudioMixingPositionImpl(e){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"setAudioMixingPosition failed for play status error");const t=this.getAudioMixingDuration();if(e<0||e>t)return void this.logger.error(this.module_,"setAudioMixingPosition failed for params error");let r;this.logger.debug(this.module_,"setAudioMixingPosition: ".concat(e)),this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode),this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.sourceNode=null,r=this.audioMixInfo_.audioMixState===SC.PAUSE?this.audioMixInfo_.pauseAt:XR.getCurrentTimestamp();const i=r-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur+this.audioMixOption_.startTime;if(this.audioMixOption_.replace&&(this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode),this.logger.info(this.module_,"resumeAudioMixing: replace")),this.audioMixInfo_.startAt=XR.getCurrentTimestamp(),this.audioMixInfo_.pauseAt=0,this.audioMixInfo_.pauseDur=0,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at setAudioMixingPositionImpl")))},this.audioMixInfo_.sourceNode.buffer=this.audioMixInfo_.buffer,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode),i>=t&&this.audioMixOption_.repeatCount>1&&(this.audioMixOption_.repeatCount=Math.max(0,this.audioMixOption_.repeatCount-Math.floor(i/t))),this.audioMixOption_.repeatCount>1){this.audioMixInfo_.sourceNode.loop=!0;const r=this.audioMixOption_.repeatCount*t-e;this.audioMixInfo_.totalDur=r,this.audioMixInfo_.sourceNode.start(0,e/1e3,r/1e3)}else this.audioMixOption_.loop?this.audioMixInfo_.totalDur=1/0:this.audioMixInfo_.totalDur=t-e,this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixInfo_.sourceNode.start(0,e/1e3);this.audioMixOption_.startTime=e,this.audioMixInfo_.audioMixState===SC.PAUSE&&this.pauseAudioMixing()}getStatInfo(){return{audioProfile_:this.audioProfile_,videoProfile_:this.videoProfiles_,screenProfile_:this.screenProfile_,audio_:this.audio_,video_:this.video_,cameraId_:this.getCurrentCameraId(),facingMode_:this.facingMode_,microphoneId_:this.getCurrentMicrophoneId(),screen_:this.screen_,screenAudio_:this.screenAudio_}}},n(XP.prototype,"initialize",[PP],Object.getOwnPropertyDescriptor(XP.prototype,"initialize"),XP.prototype),n(XP.prototype,"addAudioTrackCapture",[MP],Object.getOwnPropertyDescriptor(XP.prototype,"addAudioTrackCapture"),XP.prototype),n(XP.prototype,"addVideoTrackCapture",[DP],Object.getOwnPropertyDescriptor(XP.prototype,"addVideoTrackCapture"),XP.prototype),n(XP.prototype,"setAudioProfile",[NP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioProfile"),XP.prototype),n(XP.prototype,"setVideoProfile",[UP],Object.getOwnPropertyDescriptor(XP.prototype,"setVideoProfile"),XP.prototype),n(XP.prototype,"addResolution",[xP],Object.getOwnPropertyDescriptor(XP.prototype,"addResolution"),XP.prototype),n(XP.prototype,"removeResolution",[LP],Object.getOwnPropertyDescriptor(XP.prototype,"removeResolution"),XP.prototype),n(XP.prototype,"setScreenProfile",[BP],Object.getOwnPropertyDescriptor(XP.prototype,"setScreenProfile"),XP.prototype),n(XP.prototype,"switchDevice",[VP],Object.getOwnPropertyDescriptor(XP.prototype,"switchDevice"),XP.prototype),n(XP.prototype,"addTrack",[YP],Object.getOwnPropertyDescriptor(XP.prototype,"addTrack"),XP.prototype),n(XP.prototype,"removeTrack",[jP],Object.getOwnPropertyDescriptor(XP.prototype,"removeTrack"),XP.prototype),n(XP.prototype,"replaceTrack",[FP],Object.getOwnPropertyDescriptor(XP.prototype,"replaceTrack"),XP.prototype),n(XP.prototype,"bindScreenAudio2RelatedStream",[HP],Object.getOwnPropertyDescriptor(XP.prototype,"bindScreenAudio2RelatedStream"),XP.prototype),n(XP.prototype,"startAudioMixing",[KP],Object.getOwnPropertyDescriptor(XP.prototype,"startAudioMixing"),XP.prototype),n(XP.prototype,"stopAudioMixing",[zP],Object.getOwnPropertyDescriptor(XP.prototype,"stopAudioMixing"),XP.prototype),n(XP.prototype,"pauseAudioMixing",[WP],Object.getOwnPropertyDescriptor(XP.prototype,"pauseAudioMixing"),XP.prototype),n(XP.prototype,"resumeAudioMixing",[GP],Object.getOwnPropertyDescriptor(XP.prototype,"resumeAudioMixing"),XP.prototype),n(XP.prototype,"setAudioMixingVolume",[JP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioMixingVolume"),XP.prototype),n(XP.prototype,"setAudioMixingPosition",[qP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioMixingPosition"),XP.prototype),XP);class rM extends eM{constructor(e){super({isRemote:!0,type:e.type,log:e.log}),this.userId_=e.userId,this.client_=[],this.client_.push(e.client),this.module_="RemoteStream",this.roomId_=e.roomId}muteAudio(){return!!super.muteAudio()&&(this.stat.reportAudioMuteInfo(2,!0),!0)}unmuteAudio(){return!!super.unmuteAudio()&&(this.stat.reportAudioMuteInfo(2,!1),!0)}getVideoHRTCTrackByTrackId(e){let t;for(const r of this.tracks[vO.TRACK_TYPE_VIDEO].values())if(r.getTrackId()===e){t=r;break}return t}updateRemoteResolutions(e,t,r){if(!t)return;const i=this.getHRTCTrackIds({mediaType:vO.TRACK_TYPE_VIDEO}),n=t.map((e=>e.streamId));for(const a of i)if(null==n||!n.includes(a))for(const t of this.getHRTCTracks({mediaType:vO.TRACK_TYPE_VIDEO}))if((null==t?void 0:t.getTrackId())===a){this.logger.info(this.module_,"updateRemoteResolutions, streamType:".concat(e,",delete track:").concat(a)),this.stop({audio:!1,video:!0,resolutionIds:[a]}),this.removeRemoteVideoTrack(a),this.tracks[vO.TRACK_TYPE_VIDEO].delete(t.getResolutionId());break}for(const a of t){if(i.includes(a.streamId)){var o;null===(o=this.getVideoHRTCTrackByTrackId(a.streamId))||void 0===o||o.updateTrackProfile(a);continue}const t=new oP({streamType:e,trackType:vO.TRACK_TYPE_VIDEO,isRemote:!0,trackProfile:{width:a.width,height:a.height},logger:this.logger,resolutionId:a.streamId,event:this.eventEmitter});t.setTrackId(a.streamId||t.getResolutionId()),this.tracks[vO.TRACK_TYPE_VIDEO].set(a.streamId,t)}const s=this.getAnyAudioHRTCTrack();if(r){if(!s){const t=new oP({streamType:e,trackType:vO.TRACK_TYPE_AUDIO,isRemote:!0,logger:this.logger,resolutionId:this.id_,event:this.eventEmitter});this.tracks[vO.TRACK_TYPE_AUDIO].set("mainAudio",t)}}else s&&(this.logger.info(this.module_,"updateRemoteResolutions, streamType:".concat(e,",delete audio track")),this.stop({audio:!0,video:!1}),this.removeRemoteAudioTrack(),this.tracks[vO.TRACK_TYPE_AUDIO].delete("mainAudio"));this.logger.info(this.module_,"updateResolutions success,userId:".concat(this.getUserId(),", streamType:").concat(e,",")+"new resolution is ".concat(this.getHRTCTracksProfileString()," hasAudio: ").concat(this.hasAudioTrack()))}getHRTCTracksProfileString(){const e=this.getHRTCTracks();let t="";return e.forEach((e=>{t=t+e.getTrackId()+":"+JSON.stringify(e.getTrackProfile())+","})),t}addRemoteTrack(e,t){if(e.kind===vO.TRACK_TYPE_AUDIO){const t=this.getAnyAudioHRTCTrack();null==t||t.replaceTrack(e)}else{const r=Array.from(this.tracks[vO.TRACK_TYPE_VIDEO].values()).find((e=>e.getTrackId()===t));null==r||r.replaceTrack(e)}this.logger.info(this.module_,"addRemoteTrack MediaStreamTrack for trackId:".concat(t," success,userId:").concat(this.getUserId(),", type:").concat(this.getType(),",")+"new resolution is ".concat(this.getHRTCTracksProfileString(),", hasAudio: ").concat(this.hasAudioTrack()))}isTracksReady(e,t){if(this.isRemote_){let r=!0;if(null!=e&&e.length){const t=this.getHRTCTrackIds();for(const i of e)if(!t.includes(i)||!this.getVideoHRTCTrackByTrackId(i).getTrack()){r=!1;break}}const i=this.getAudioHRTCTrack(),n=i&&!!i.getTrack(),o=r&&(!t||n);return this.logger.debug(this.module_,"isTracksReady userId:".concat(this.getUserId(),", type:").concat(this.getType(),",")+"result: ".concat(o,",videoTrackIds: ").concat(e,", isVideoReady:").concat(r,", isAudioReady:").concat(n)),o}return!0}isTrackReady(e,t){if(this.isRemote_){var r;if(e===vO.TRACK_TYPE_VIDEO)return!(null===(r=this.getVideoHRTCTrackByTrackId(t))||void 0===r||!r.getTrack());return!!this.getAudioHRTCTrack()}return!1}removeRemoteAudioTrack(){const e=this.getAnyAudioHRTCTrack();e&&e.removeTrack()}removeRemoteVideoTrack(e){const t=this.tracks[vO.TRACK_TYPE_VIDEO].get(e);t&&t.removeTrack()}}const iM=0,nM=2;let oM=function(e){return e.JOINER="anchor",e.PLAYER="audience",e}({}),sM=function(e){return e[e.JOINER=0]="JOINER",e[e.PLAYER=2]="PLAYER",e}({});class aM{get identifiedID(){return this.identifiedID_}set identifiedID(e){this.identifiedID_=e}get roomId(){return this.roomId_}set roomId(e){this.roomId_=e}get signature(){return this.signature_}set signature(e){this.signature_=e}get ctime(){return this.ctime_}set ctime(e){this.ctime_=e}get userId(){return this.userId_}set userId(e){this.userId_=e}get encUserId(){return this.encUserId_}set encUserId(e){this.encUserId_=e}get userName(){return this.userName_}set userName(e){this.userName_=e}get role(){return this.role_}set role(e){this.role_=e}get roleSignalType(){return nM===this.role_?oM.PLAYER:oM.JOINER}get appData(){return this.appData_}set appData(e){this.appData_=e}removeRelayInfo(e){this.relayInfos_=this.relayInfos_.filter((t=>t.roomId!==e))}addRelayInfo(e,t){this.relayInfos_||(this.relayInfos_=[]),this.relayInfos_.push({roomId:e,role:t})}getRelayInfos(){return this.relayInfos_}}const cM=new Map;class uM{static get(e){return cM.get(e)}static delete(e){cM.delete(e)}static init(e,t,r){const i=new aM;return i.identifiedID=e,i.userId=r.userId,i.userName=r.userName,i.role=r.role,i.signature=r.signature,i.ctime=r.ctime,i.appData={},r.userName&&(i.appData.nickname=r.userName),r.optionInfo&&[!0,!1].includes(r.optionInfo.recordPlaceholder)&&(i.appData.show_window=r.optionInfo.recordPlaceholder),i.roomId=t,cM.set(e,i),i}static transLocalUserToJoinConfig(e){var t;return{userId:e.userId,userName:e.userName,signature:e.signature,ctime:e.ctime,role:e.role,optionInfo:{recordPlaceholder:null===(t=e.appData)||void 0===t?void 0:t.show_window}}}static renewSignature(e,t,r){if(cM.has(e)){const i=cM.get(e);return i.ctime=t,i.signature=r,i}return null}}let dM=function(e){return e.ReceiveData="ReceiveData",e.ConnectionQuality="ConnectionQuality",e.Reconnected="Reconnected",e.SessionUnavailable="SessionUnavailable",e.ConnectionUnavailable="ConnectionUnavailable",e.ConnectionStateChanged="ConnectionStateChanged",e.AuthenticateFail="AuthenticateFail",e.SignatureExpired="SignatureExpired",e.ClientBanned="ClientBanned",e}({});class lM{constructor(){i(this,"state_",[])}default(e){return this.defaultVal_=e,this}get(){return 0!=this.state_.length?this.state_[this.state_.length-1]:null}set(e){return 2==this.state_.length&&this.state_.unshift(),this.state_.push(e),this}pre(){return this.state_.length>=2?this.state_[this.state_.length-2]:null}reset(){return this.state_=[],this.state_[0]=this.defaultVal_,this}get state(){return this.state_}}class hM extends lM{isChanged(){return this.state.length>1&&this.get()!==this.pre()}getDiffInfo(){return this.isChanged()?{updated:this.state[1]}:{}}}let fM=function(e){return e[e.Health=1]="Health",e[e.SubHealth=4]="SubHealth",e[e.Unavailable=6]="Unavailable",e}({});const pM="HealthMonitor";class mM extends $P{constructor(e){super({emitter:!0,logger:e.logger}),this.client=e,this.reset()}reset(){this.streamDetectTimer&&(clearInterval(this.streamDetectTimer),this.streamDetectTimer=null),this.streamStats={mainStream:{bytesIn:(new hM).default(0).set(0).set(0),bytesOut:(new hM).default(0).set(0).set(0)},auxStream:{bytesIn:(new hM).default(0).set(0).set(0),bytesOut:(new hM).default(0).set(0).set(0)},upQuality:(new hM).default(EO.NETWORK_QUALITY_UNKNOW).set(EO.NETWORK_QUALITY_UNKNOW).set(EO.NETWORK_QUALITY_UNKNOW),downQuality:(new hM).default(EO.NETWORK_QUALITY_UNKNOW).set(EO.NETWORK_QUALITY_UNKNOW).set(EO.NETWORK_QUALITY_UNKNOW)}}isStreamAvailable(){if(!this.client)return!1;const e=this.isAvailableStreamIncoming(yO.STREAM_TYPE_MAIN),t=this.isAvailableStreamIncoming(yO.STREAM_TYPE_AUX),r=this.isAvailableStreamOutgoing(yO.STREAM_TYPE_MAIN),i=this.isAvailableStreamOutgoing(yO.STREAM_TYPE_AUX);return e||t||r||i}getWsConnectionHealthStatus(){return this.streamDetectTimer?this.isStreamAvailable()?fM.SubHealth:fM.Unavailable:fM.Health}startStreamStateDetection(){this.streamDetectTimer||(this.streamDetectTimer=setInterval((async()=>{if(this.client){const e=this.client.getICETransportStat(yO.STREAM_TYPE_MAIN);e&&this.updateStreamStat(e,yO.STREAM_TYPE_MAIN);const t=this.client.getICETransportStat(yO.STREAM_TYPE_AUX);t&&this.updateStreamStat(t,yO.STREAM_TYPE_AUX),this.updateConnectionQuality(this.getWsConnectionHealthStatus())}}),3e3))}stopStreamStateDetection(){this.streamDetectTimer&&(clearInterval(this.streamDetectTimer),this.streamDetectTimer=null,this.updateConnectionQuality(this.getWsConnectionHealthStatus()))}updateConnectionQuality(e){if(!this.client)return;const t=this.client.isSendingStream()?e:EO.NETWORK_QUALITY_UNKNOW,r=this.client.isReceivingStream()?e:EO.NETWORK_QUALITY_UNKNOW;this.updateSignalQuality(t,r)}isAvailableStreamIncoming(e){const t=e===yO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;return t.bytesIn.get()-t.bytesIn.pre()>mM.getMinAvailableBytes()}static getMinAvailableBytes(){return sC.low.bitrate/8*3}isAvailableStreamOutgoing(e){const t=e===yO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;return t.bytesOut.get()-t.bytesOut.pre()>mM.getMinAvailableBytes()}updateStreamStat(e,t){const r=t===yO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;this.logger.info(pM,"".concat(t," : bytesIn:").concat(e.bytesReceived," ,bytesOut:").concat(e.bytesSent)),r.bytesIn.set(e.bytesReceived),r.bytesOut.set(e.bytesSent)}updateSignalQuality(e,t){if(this.streamStats.upQuality.set(e),this.streamStats.downQuality.set(t),this.logger.info(pM,"upQuality:".concat(this.streamStats.upQuality.pre(),",").concat("".concat(e)," ,downQuality:").concat(this.streamStats.downQuality.pre(),",").concat("".concat(t))),this.streamStats.upQuality.isChanged()||this.streamStats.downQuality.isChanged()){const r={uplinkNetworkQuality:e,downlinkNetworkQuality:t};this.logger.info(pM,"emit network-quality:".concat(JSON.stringify(r))),this.eventEmitter.emit(dM.ConnectionQuality,r)}}getInfo(){return{moduleName:"HealthMonitor"}}}function gM(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const _M="Socket",SM="heartbeat",vM="reconnectingEnd";var yM=function(e){return e[e.normal=1e3]="normal",e[e.multiKickoff=4e3]="multiKickoff",e[e.authenticateFail=4001]="authenticateFail",e[e.kickoff=4002]="kickoff",e[e.releaseRoom=4003]="releaseRoom",e[e.heartbeatTimeout=4004]="heartbeatTimeout",e[e.serverReconnectReq=4005]="serverReconnectReq",e[e.serveReconnectReqWithoutSfu=4006]="serveReconnectReqWithoutSfu",e[e.signatureFail=4009]="signatureFail",e}(yM||{});let IM=0;class TM extends $P{constructor(e,t,r){super({emitter:!0,logger:r.logger,stat:r.stat}),i(this,"callbacks",new Map),this.taskId=1e3,this.appId=e,this.edgeNodeDomains=t,this.clientConfig=r.clientConfig;const n=new hM;n.default(yC.IDLE).reset().set(yC.IDLE),this.wsStatus={state:n,isHeartbeat:!1,isWsReconnecting:!1,hasEverConnected:!1},this.healthMonitor=new mM(r),this.healthMonitor.on(dM.ConnectionQuality,this.getConnectionQualityListener()),this.wsReset()}setKeepAliveParams(e){this.heartBeatConfig=e}setTraceId(e){this.traceId=e}wsReset(){var e;this.closeConnection(),this.traceId="",this.connectId="",this.wsUrl="",this.acsIP="",this.wsStatus.state.reset(),this.wsStatus.hasEverConnected=!1,this.userInfo=void 0,null===(e=this.healthMonitor)||void 0===e||e.reset()}wsDisconnect(){this.healthMonitor.off(dM.ConnectionQuality),this.wsReset(),this.healthMonitor=void 0}getConnectionQualityListener(){return e=>{this.emit(dM.ConnectionQuality,e)}}async wsConnect(e,t,r,i,n,o,s){this.logger.info(_M,"wsConnect, acsIP:".concat(t,", firstTimeout:").concat(n,", retryTimeout:").concat(o,", retryCount:").concat(i,",retryInterval:").concat(s)),this.wsStatus.isWsReconnecting&&(this.logger.info(_M,"wsConnect, waiting for reconnecting ending"),await this.stopReconnecting(),this.logger.info(_M,"wsConnect, reconnecting end")),this.acsIP=t,this.userInfo=e,this.wsStatus.state.set(yC.DISCONNECTED),await this.doConnect(t,r,i,n,o,s,!1)}refreshUserInfo(e){this.userInfo=e}async startHeartbeat(){try{if(this.wsStatus.isHeartbeat)return void this.logger.warn(_M,"startHeartbeat, isHeartbeat so return");this.wsStatus.isHeartbeat=!0;const e=async e=>await this.sendHeartbeat(e);return await mP.callWithRetryTimes(e,!0,-1,this.getAsyncInterval(1e3*this.heartBeatConfig.heartBeatPeriod),this.needInterrupted())}catch(jN){this.logger.warn(_M,"startHeartbeat, error:".concat(jN))}finally{this.wsStatus.isHeartbeat=!1}}async wsSendRequest(e,t,r,i,n){this.logger.debug(_M,"wsSendRequest: ".concat(e.type," - ").concat(e.requestId));return await mP.callWithRetryTimes((async i=>await this.wsSendReqOnce(e.requestId,e,t,r,i)),!1,i,this.getAsyncInterval(n),this.needInterrupted())}wsSendResponse(e){this.ws.send(e)}generateRequestId(){return this.traceId,this.traceId+"Web"+(this.taskId++).toString()}async doConnect(e,t,r,i,n,o,s){return await mP.callWithRetryTimes((async r=>await this.wsConnectOnce(e,t,i,n,r,s)),!1,r,this.getAsyncInterval(o),this.needInterrupted())}async wsConnectOnce(e,t,r,i,n,o){if([yC.IDLE,yC.CONNECTING].includes(this.wsStatus.state.get())||!this.userInfo)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(this.wsStatus.state.get()!==yC.DISCONNECTED)return this.logger.error(_M,"wsConnectOnce, cusState:".concat(this.wsStatus.state.get(),", not DISCONNECTED, return")),null;this.connectId=this.taskId.toString(),this.wsUrl=this.getWsUrl(e,o);const s=XR.getCurrentTimestamp();this.ws=new WebSocket(this.wsUrl),this.logger.info(_M,"wsConnectOnce, url:".concat(XR.shieldUrlParameters(this.wsUrl),", connectId:").concat(this.connectId,", begin create websocket connection with server ")),1!==n||o?this.triggerConnectStatesChangeEvent(yC.RECONNECTING):this.triggerConnectStatesChangeEvent(yC.CONNECTING),this.ws.onopen=this.onopen.bind(this),this.ws.onerror=this.onerror.bind(this),this.ws.onmessage=this.onmessage.bind(this),this.ws.onclose=this.onclose.bind(this);const a={id:((null==t?void 0:t.length)||0)+1,domain:this.edgeNodeDomains.get(e),start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"wsConnect",rspCode:"",errMsg:""};try{const e=1===n?r:i;await this.getConnectionResp(e),a.delay_ms=XR.getCurrentTimestamp()-a.start_ms,a.rspCode="101"}catch(jN){throw this.logger.error(_M,"wsConnectOnce, connect occur exception, connectId:".concat(this.connectId,", error: ").concat(jN)),a.delay_ms=XR.getCurrentTimestamp()-a.start_ms,"function"==typeof jN.getCode&&(a.rspCode="".concat(jN.getCode()),a.errMsg=jN.getMsg()),jN}finally{null==t||t.push(a);const e=XR.getCurrentTimestamp(),r={version:"v1",startTimestamp:s,traceId:this.xNuwaTraceId,spanId:this.xNuwaSpanId,parentSpanId:"0000000000000000",ip:"",source:"SDK",target:"WiseCloudRtcAccessService",spanName:"connect",status:"0",endTimestamp:e,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(r)}}async stopReconnecting(){let e=null;this.wsStatus.state.set(yC.IDLE);const t=[new Promise((t=>{this.callbacks.set(vM,(r=>{e&&clearTimeout(e),t(r)}))})),new Promise(((t,r)=>{e=setTimeout((()=>{r(new qc(Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT))}),3e4)}))];return await Promise.race(t).then((e=>e)).finally((()=>{this.callbacks.delete(vM)}))}async getConnectionResp(e){const t=this.connectId;await mP.callWithTimeout(new Promise(((e,r)=>{this.callbacks.set(t,(i=>{if(i.isSuccess)this.logger.info(_M,"getConnectionResp, connectId:".concat(t,", connect success")),this.triggerConnectStatesChangeEvent(yC.CONNECTED),e();else{const e=TM.newSocketException(i);this.logger.info(_M,"getConnectionResp, connectId:".concat(t,", connect fail, errMsg=").concat(e)),r(e)}}))})),e).catch((r=>{if(this.triggerConnectStatesChangeEvent(yC.DISCONNECTED),r.getCode()!==Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT)throw r;throw this.logger.error(_M,"getConnectionResp, connectId:".concat(t,", websocket connect timeout after ").concat(e," ms")),this.ws&&this.ws.readyState===this.ws.CONNECTING&&(this.logger.info(_M,"getConnectionResp, connectId:".concat(t,",websocket connect timeout, close webSocket manual")),this.ws.close()),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT)})).finally((()=>{this.callbacks.delete(t)}))}static newSocketException(e){if(e.isSuccess)return null;const t=Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR,r=e.code,i="".concat(r||""," websocket connect error");return new qc(t,i)}getWsUrl(e,t){let r,i;this.xNuwaTraceId=XR.generateRandomId(32,16),this.xNuwaSpanId=XR.generateRandomId(16,16);let n,o="443";const s=/ws(?:s)?:\/\/([^/]+)(.*)/.exec(this.edgeNodeDomains.get(e));if(s&&3===s.length){const e=s[1].split(":");i=e[0],o=e[1]||"443",n=s[2]}else i=this.edgeNodeDomains.get(e),n="/websocket";const a=RA.getProxyServer();return r=a?/^http.*/.test(a)?a.replace("http","ws"):a.replace("https","wss"):"".concat("wss","://").concat(i,":").concat(o),r="".concat(r).concat(n,"?appId=").concat(escape(this.appId),"&roomId=").concat(escape(this.userInfo.roomId))+"&userId=".concat(escape(this.userInfo.userId),"&role=").concat(this.userInfo.roleSignalType,"&Authorization=").concat(escape(this.userInfo.signature))+"&ctime=".concat(this.userInfo.ctime,"&clientVersion=").concat(uA,"&clientType=").concat(XR.getSystemType())+"&romVersion=".concat(XR.getRomVersion(),"&agentType=").concat(2,"&netType=").concat(XR.getNetworkType())+"&traceId=".concat(this.traceId,"&x-nuwa-trace-id=").concat(this.xNuwaTraceId,"&x-nuwa-span-id=").concat(this.xNuwaSpanId)+"&HoldTime=".concat(120).concat(t?"&reconnect=true":"")+"&instanceId=".concat(XR.getDeviceID().replace(/[-]/g,"")).concat(this.clientConfig.countryCode?"&clientCountryCode=".concat(this.clientConfig.countryCode):""),a&&(r="".concat(r,"&org_domain=").concat(i,"&org_port=").concat(o)),r}cancelWsCloseCallBack(){this.ws&&(this.ws.onclose=e=>{this.logger.info(_M,"cancelWsCloseCallBack, connect close,code:".concat(e.code,", reason:").concat(e.reason))})}closeConnection(){this.ws&&(this.logger.info(_M,"close ws when reset"),this.cancelWsCloseCallBack(),this.ws.close(),this.ws=null)}triggerConnectStatesChangeEvent(e,t){this.wsStatus.state.set(e);const r=function(e){for(var t=1;t"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}getAsyncInterval(e){return t=>"function"==typeof(null==t?void 0:t.getCode)&&t.getCode()===Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT?0:e}async wsSendReqOnce(e,t,r,i,n){const o=TM.removeWatchType(t),s=XR.getCurrentTimestamp();try{if(this.wsStatus.state.get()===yC.IDLE)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(!this.ws||this.ws.readyState!==this.ws.OPEN)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN);n>1&&this.logger.debug(_M,"wsSendReq: ".concat(e,", retry send message"));const s=JSON.stringify(o);this.ws.send(s),this.stat&&(this.stat.reportSignalReqForWeb2Server(o),this.stat.recordUploadRequsetInfo(t));const a=1===n?r:i;return await this.getResponse(o,a)}catch(jN){throw this.logger.error(_M,"wsSendReq: ".concat(e,", type: ").concat(o.type,", tryNumber: ").concat(n,",error: ").concat(jN)),"PING"===t.type&&this.healthMonitor.startStreamStateDetection(),this.recordWsException(t,jN,s),jN}finally{const e=this.stat.checkSignalSendMsgs((null==o?void 0:o.type)||""),t=o["x-nuwa-span-id"],r=XR.getCurrentTimestamp(),i={version:"v1",startTimestamp:s,traceId:o["x-nuwa-trace-id"],spanId:t,parentSpanId:e?"0000000000000000":this.stat.getParentSpanId(o["x-nuwa-span-id"]),ip:"",source:"SDK",target:"WiseCloudRtcAccessService",spanName:(null==o?void 0:o.type)||"",status:"0",endTimestamp:r,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(i)}}recordWsException(e,t,r){if("PING"!==e.type)switch(e.type){case"SUBS_STREAM":{const r=t.getCode(),i=t.getMsg();e.videoUpstreams&&this.stat.reportVideoSub(e.videoSubType,e.requestId,e.videoUpstreams,r,i),e.audioUpstreams&&this.stat.reportAudioSub(e.audioSubType,e.requestId,e.audioUpstreams,r);break}}else this.stat.reportSignalReqForHeartBeatLost(e,r)}async getResponse(e,t){let r=null;const i=[new Promise((t=>{const i="PING"===e.type?SM:e.requestId;this.callbacks.set(i,(e=>{r&&clearTimeout(r),t(e)}))})),new Promise(((e,i)=>{r=setTimeout((()=>{i(new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT))}),t)}))];return await Promise.race(i).finally((()=>{const t="PING"===e.type?SM:e.requestId;this.callbacks.delete(t)}))}onopen(e){this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!0}),this.logger.info(_M,"onopen, wss[".concat(XR.shieldUrlParameters(this.wsUrl),"], connectId:").concat(this.connectId,", connect success, ").concat(JSON.stringify(e))),this.stat.setConnectionStatusInfo(QC.CONNECTED,XC.SIGNAL)}onerror(e){this.logger.error(_M,"onerror, connectId:".concat(this.connectId,", websocket occur error:").concat(JSON.stringify(e))),this.stat.setConnectionStatusInfo(QC.CLOSED,XC.SIGNAL),this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!1})}onmessage(e){if(null==e||!e.data)return;const t=JSON.parse(e.data);this.wsStatus.hasEverConnected=!0,IM=0;const r=this.callbacks.get(SM);if(r&&r(t),t.type)this.emit(dM.ReceiveData,t);else{const e=this.callbacks.get(t.requestId);e&&e(t)}this.stat.reportSignalReqForServer2Web(t);const i=this.stat.getDownloadRequestInfo(t);this.stat.recordDownloadRequestInfo(t);const n=this.stat.checkSignalReceiveMsgs((null==t?void 0:t.type)||""),o=XR.generateRandomId(16,16),s=t["x-nuwa-span-id"];n&&this.stat.setSpanId(s,o);const a=XR.getCurrentTimestamp(),c={version:"v1",startTimestamp:a,traceId:t["x-nuwa-trace-id"],spanId:o,parentSpanId:s,ip:"",source:"WiseCloudRtcAccessService",target:"SDK",spanName:(null==t?void 0:t.type)||i,status:"0",endTimestamp:a,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(c)}async onclose(e){const t=e.code,r=e.reason;if(this.logger.warn(_M,"onclose,connectId:".concat(this.connectId,", code:").concat(t,", reason:").concat(r)),this.stat.setConnectionStatusInfo(QC.CLOSED,XC.SIGNAL),this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!1,code:t,reason:r}),this.triggerConnectStatesChangeEvent(yC.DISCONNECTED,{code:t,reason:r}),TM.isServerAuthFail(t))this.handleServerAuthFail();else{if(!TM.isSignatureFail(t))return TM.isKickedOff(t)?(this.logger.warn(_M,"handleKickedOff, emit:".concat(dM.ClientBanned)),void this.emit(dM.ClientBanned)):TM.isServerSessionValidateFail(t)?(this.logger.warn(_M,"onclose, emit:".concat(dM.SessionUnavailable)),void this.emit(dM.SessionUnavailable)):void(t===yM.heartbeatTimeout||t===yM.serveReconnectReqWithoutSfu||t>1e3&&t<4e3?await this.reconnect():this.logger.error(_M,"onclose, no handler"));this.handleSignatureFail()}}handleServerAuthFail(){this.logger.error(_M,"handleServerAuthFail, auth failed to leave room"),this.logger.warn(_M,"handleServerAuthFail, emit:".concat(dM.AuthenticateFail," ")),this.emit(dM.AuthenticateFail)}async handleSignatureFail(){this.logger.warn(_M,"handle signature fail, emit:".concat(dM.SignatureExpired)),this.wsStatus.hasEverConnected?(this.emit(dM.SignatureExpired,{type:"reconnect"}),IM<5?(this.logger.warn(_M,"signature expired, try reconnect: retry times: ".concat(IM+1)),await this.reconnect(),IM++):this.emit(dM.SessionUnavailable)):this.emit(dM.SignatureExpired,{type:"join"})}async reconnect(){if(this.logger.info(_M,"reconnect, not user call leave, network error, go ws reconnecting"),!this.wsStatus.hasEverConnected)return this.logger.info(_M,"reconnect, haven't connect yet, so return"),null;if(this.wsStatus.isWsReconnecting)return this.logger.info(_M,"reconnect, isWsReConnecting so return"),null;try{this.wsStatus.isWsReconnecting=!0;const e=12e3,t=1e3;await this.doConnect(this.acsIP,null,-1,e,e,t,!0),this.logger.info(_M,"wsReconnect, success");const r=this.callbacks.get(vM);r&&r("success"),this.logger.warn(_M,"emit:".concat(dM.Reconnected)),this.emit(dM.Reconnected)}catch(jN){this.logger.error(_M,"wsReconnect, errMsg:".concat(jN));const t=this.callbacks.get(vM);t&&t(jN)}finally{this.wsStatus.isWsReconnecting=!1}}static isServerAuthFail(e){return[yM.authenticateFail,yM.releaseRoom].includes(e)}static isSignatureFail(e){return[yM.signatureFail].includes(e)}static isKickedOff(e){return[yM.multiKickoff,yM.kickoff].includes(e)}static isServerSessionValidateFail(e){return[yM.serverReconnectReq].includes(e)}async sendHeartbeat(e){try{if([yC.IDLE,yC.CONNECTING].includes(this.wsStatus.state.get()))throw this.logger.info(_M,"sendHeartbeat, but wsStatus is IDLE or CONNECTING, interrupted"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(!this.traceId)throw this.logger.error(_M,"sendHeartbeat, traceId is null"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);const e={type:"PING",traceId:this.traceId,requestId:this.generateRequestId(),version:lA,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};await this.wsSendRequest(e,1e3*this.heartBeatConfig.heartBeatPeriod,1e3*this.heartBeatConfig.heartBeatPeriod,this.heartBeatConfig.heartBeatRetryTimes,1e3*this.heartBeatConfig.heartBeatPeriod),this.healthMonitor.stopStreamStateDetection()}catch(jN){this.logger.info(_M,"sendHeartbeat,father tryNumber:".concat(e,",child heartbeat retry out of limit:").concat(this.heartBeatConfig.heartBeatRetryTimes," and fail, error:").concat(jN)),this.handleHeartbeatFail(jN)}}handleHeartbeatFail(e){if("function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED)throw this.logger.warn(_M,"handleHeartbeatFail, ErrorCode.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED"),e;const t=this.healthMonitor.getWsConnectionHealthStatus();this.logger.warn(_M,"handleHeartbeatFail, healthStatus:".concat(t)),t===fM.Unavailable&&(this.logger.info(_M,"handleHeartbeatFail, connection unavailable when error:".concat(e)),this.logger.warn(_M,"emit:".concat(dM.ConnectionUnavailable)),this.emit(dM.ConnectionUnavailable))}getInfo(){return{moduleName:"Socket"}}}let RM=function(e){return e[e.MAIN=0]="MAIN",e[e.DESKTOP=1]="DESKTOP",e}({}),EM=function(e){return e.SEND_RECV="sendrecv",e.SEND_ONLY="sendonly",e.RECV_ONLY="recvonly",e.INACTIVE="inactive",e}({}),bM=function(e){return e[e.cmdPayload=99]="cmdPayload",e}({}),CM=function(e){return e[e.opusPayload=112]="opusPayload",e}({}),AM=function(e){return e[e.rtxPayLoad=107]="rtxPayLoad",e[e.h264PayLoad=122]="h264PayLoad",e[e.redPayLoad=110]="redPayLoad",e[e.ulpfecPayLoad=127]="ulpfecPayLoad",e}({}),wM=function(e){return e.H264="H264",e.H265="H265",e.H264H265="H264H265",e.OPUS="opus",e}({});const kM="signal",OM=5e3;class PM extends $P{constructor(e,t,r){super({emitter:!0,logger:r.logger,stat:r.stat},r.getSymbol()),this.edgeNodeDomains=t,this.socket=new TM(e,t,r),this.onSocketEvent(),this.reset()}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}reset(){var e;this.traceId="",this.isConnecting=!1,null===(e=this.socket)||void 0===e||e.wsReset()}disconnect(){var e;this.offSocketEvent(),this.reset(),null===(e=this.socket)||void 0===e||e.wsDisconnect(),this.socket=void 0}getConnectionQualityListener(){return e=>{this.emit(UC.NetworkQuality,e)}}getConnectionStateChangedListener(){return e=>{this.emit(UC.ConnectionStateChanged,e)}}getSignatureExpiredListener(){return e=>{this.emit(dM.SignatureExpired,e)}}getReceiveDataListener(){return e=>{this.receiveMsg(e)}}getSessionUnavailableListener(){return e=>{this.emit(dM.SessionUnavailable,e)}}getConnectionUnavailableListener(){return e=>{this.emit(dM.ConnectionUnavailable,e)}}getReconnectedListener(){return e=>{this.emit(dM.Reconnected,e)}}getAuthenticateFailListener(){return e=>{this.emit(dM.AuthenticateFail,e)}}getKickedOffListener(){return e=>{this.emit(dM.ClientBanned,e)}}onSocketEvent(){this.socket&&(this.socket.on(dM.ConnectionQuality,this.getConnectionQualityListener()),this.socket.on(dM.ConnectionStateChanged,this.getConnectionStateChangedListener()),this.socket.on(dM.SignatureExpired,this.getSignatureExpiredListener()),this.socket.on(dM.ReceiveData,this.getReceiveDataListener()),this.socket.on(dM.SessionUnavailable,this.getSessionUnavailableListener()),this.socket.on(dM.ConnectionUnavailable,this.getConnectionUnavailableListener()),this.socket.on(dM.Reconnected,this.getReconnectedListener()),this.socket.on(dM.AuthenticateFail,this.getAuthenticateFailListener()),this.socket.on(dM.ClientBanned,this.getKickedOffListener()))}offSocketEvent(){this.socket&&(this.socket.off(dM.ConnectionQuality),this.socket.off(dM.ConnectionStateChanged),this.socket.off(dM.SignatureExpired),this.socket.off(dM.ReceiveData),this.socket.off(dM.SessionUnavailable),this.socket.off(dM.ConnectionUnavailable),this.socket.off(dM.Reconnected),this.socket.off(dM.AuthenticateFail),this.socket.off(dM.ClientBanned))}getRandomAcsIp(){let e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(1===this.edgeNodeDomains.size||t)return this.selectedAcsIp="default",this.selectedAcsIp;let r=0;return this.selectedAcsIp?(e=[...this.edgeNodeDomains.keys()].filter((e=>"default"!==e&&e!==this.selectedAcsIp)),e.length<1||(r=Math.round(XR.getRandom()*(e.length-1)),this.selectedAcsIp=e[r]),this.selectedAcsIp):(e=[...this.edgeNodeDomains.keys()].filter((e=>"default"!==e)),r=Math.round(XR.getRandom()*(e.length-1)),this.selectedAcsIp=e[r],this.selectedAcsIp)}async connect(e,t){if(this.isConnecting)return this.logger.info(kM,"connect, isConnecting so return"),null;this.traceId=XR.generateStandardUuid(),this.socket.setTraceId(this.traceId);try{this.isConnecting=!0;const r=async r=>await this.connectOnce(e,t,r);return await mP.callWithRetryTimes(r,!1,2,this.getAsyncInterval(),this.needInterrupted())}finally{this.isConnecting=!1}}refreshUserInfo(e){this.socket.refreshUserInfo(e)}needInterrupted(){return e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}getAsyncInterval(){return()=>Math.round(500*XR.getRandom()+500)}async connectOnce(e,t,r){const i=this.getRandomAcsIp(PM.isLastTry(2,r));if(!i)throw this.logger.error(kM,"selectedAcsIP is null"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED,"no available servers to connect");return await this.socket.wsConnect(e,i,t,0,1e4,0,0),"default"===i?this.edgeNodeDomains.get("default"):i}static isLastTry(e,t){return t===e+1}async join(e,t,r,i,n,o,s,a){return new Promise(((c,u)=>{const d=PM.setJoinRequest(e,t,r,i,n,o,s,a);this.sendRequest(d).then((e=>{var t;0!==e.resultCode?(this.logger.error(kM,"join code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),u(new qc(Number(e.resultCode),e.resultMessage))):(null===(t=e.userInfos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),c(e))})).catch((e=>{u(e)}))}))}async subscribe(e,t,r){const i={type:"SUBS_STREAM",videoUpstreams:e,audioUpstreams:t,videoSubType:1,audioSubType:1,watchType:r,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)},n=await this.sendRequest(i);if(0!==n.resultCode){const e=JSON.stringify(i);throw this.logger.error(kM,"subscribe fail,err_code:".concat(n.resultCode,",")+"error_msg:".concat(n.resultMessage,",request ").concat(e)),new qc(Number(n.resultCode),n.resultMessage)}return this.logger.info(kM,"subscribe send msg result:".concat(n.resultMessage)),n}async queryRoomUsers(e){var t;const r={type:"GET_ROOM_USERINFO","x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};null!=e&&e.length&&(r.userIds=e);const i=await this.sendRequest(r);if(0!==i.resultCode)throw this.logger.error(kM,"queryRoomUsers fail,err_code:".concat(i.resultCode,",error_msg:").concat(i.resultMessage)),new qc(Number(i.resultCode),i.resultMessage);return null===(t=i.userInfos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),this.logger.info(kM,"queryRoomUsers send msg result:".concat(i.resultMessage)),i}async leave(){try{const e=await this.sendRequest({type:"EXIT_ROOM"});if(0!==e.resultCode)throw this.logger.error(kM,"leave, exit room, err_code:".concat(e.resultCode,",error_msg:").concat(e.resultMessage)),new qc(Number(e.resultCode),e.resultMessage);const t=await this.sendRequest({type:"BYE"});if(0!==t.resultCode)throw this.logger.error(kM,"leave, exit room, err_code:".concat(t.resultCode,",error_msg:").concat(t.resultMessage)),new qc(Number(t.resultCode),t.resultMessage)}catch(jN){throw new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}}async changeStreamStatus(e){try{return e.type="CHANGE_STREAM_STATUS",await this.sendRequest(e)}catch(jN){throw this.logger.error(kM,"changeStreamStatus fail, error:".concat(jN)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}}static setJoinRequest(e,t,r,i,n,o,s,a){const c={type:"JOIN_ROOM",sdp:{secCap:"sec3.0",sfuType:SO.getParameter(dO)||RO.COMMON_SFU_RESOURCE,crypto:{type:1},frameType:SO.getParameter(hO)||xC.NON_ENCRYPTION,audios:[{content:CC.main,codecs:[{codec:wM.OPUS,pt:CM.opusPayload,ability:2}],audioLevel:3}],videos:[{content:CC.main,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]},{content:CC.slides,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]}],desktopVideos:[{content:CC.desktop,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]}],audioPolicy:i,bandwidths:n},negSdp:[{type:RM.MAIN,sdp:t},{type:RM.DESKTOP,sdp:r}],scenario:1,relayMode:0,agentType:2,appData:e.appData,mediaData:{portType:o},"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)},u=SO.getParameter(lO);return u&&(c.sdp.resourceTags=u),s&&(c.sdp.command={codecs:[{codec:wM.OPUS,pt:bM.cmdPayload}],content:"cmd=1"}),Object.assign(c.mediaData,a||{}),c}async switchRole(e,t){const r=PM.setSwitchRoleRequest(e,t),i=await this.sendRequest(r);if(0!==i.resultCode)throw this.logger.error(kM,"switch user role fail,err_code:".concat(i.resultCode,",error_msg:").concat(i.resultMessage)),new qc(Number(i.resultCode),i.resultMessage);return i}static setSwitchRoleRequest(e,t){return{type:"SWITCH_ROLE",role:e===iM?oM.JOINER:oM.PLAYER,authorization:t.signature,ctime:parseInt(t.ctime),"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)}}async pushStreamResponse(e){this.logger.info(kM,"pushStreamRep send msg start:");try{await this.socket.wsSendResponse(JSON.stringify(e)),this.logger.info(kM,"pushStreamRep send response")}catch(Dw){throw this.logger.error(kM,"pushStreamRep send response fail, errMsg = ".concat(Dw)),new qc(Gc.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL)}}keepAlive(){this.logger.info(kM,"keepAlive"),this.socket.startHeartbeat()}async sendRequest(e){return this.assignCommonMsgInfo(e),await this.socket.wsSendRequest(e,OM,OM,2,OM)}assignCommonMsgInfo(e){Object.assign(e,{traceId:this.traceId,requestId:this.socket.generateRequestId(),version:lA,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)})}async publish(e){return new Promise(((t,r)=>{const i=[],n=[];e.forEach((e=>{e.codec===wM.H264?i.push({content:e.content,mute:e.mute,width:e.width,height:e.height,fps:e.fps,maxFs:e.maxFs,maxMbps:e.maxMbps,codec:e.codec,pt:e.pt,streamData:e.streamData,streamUid:e.streamUid,ssrc:e.ssrc,createDate:e.createDate}):e.codec===wM.OPUS&&n.push({content:e.content,mute:e.mute,channels:e.channels,sampleRate:e.sampleRate,maxMbps:e.maxMbps,codec:e.codec,pt:e.pt,streamData:e.streamData,streamUid:e.streamUid,ssrc:e.ssrc,createDate:e.createDate})}));const o={type:"PUSH_STREAM_RES_ALL",pushStreamType:0,videoStreams:i,audioStreams:n,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(o).then((e=>{0!==e.resultCode?(this.logger.error(kM,"publish resp code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),r(new qc(Number(e.resultCode),e.resultMessage))):t(e)})).catch((e=>{r(e)}))}))}async appData(e,t,r){return new Promise(((i,n)=>{const o={};Object.assign(o,e),o[t]=r;const s={type:"APP_DATA",appData:o};this.sendRequest(s).then((e=>{0!==e.resultCode?(this.logger.error(kM,"appset code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),n(new qc(Number(e.resultCode),e.resultMessage))):i(e)})).catch((e=>{n(e)}))}))}async changeAudioPolicy(e){return new Promise(((t,r)=>{const i={type:"AUDIO_POLICY",audioPolicy:e,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(i).then((n=>{if(0!==n.resultCode){const t=JSON.stringify(i);this.logger.error(kM,"change audioPolicy code:".concat(n.resultCode,",audioPolicy:").concat(e,",msg:").concat(n.resultMessage," request ").concat(t)),r(new qc(Number(n.resultCode),n.resultMessage))}else this.logger.info(kM,"change audioPolicy ".concat(e," success")),t(n)})).catch((t=>{this.logger.info(kM,"change audioPolicy ".concat(e," exception")),r(t)}))}))}async updateLiveStreaming(e,t,r){return new Promise(((i,n)=>{const o={type:"UPDATE_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,config:t,userInfos:r,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(o).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(o);this.logger.error(kM,"updateLiveStreaming code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),n(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"updateLiveStreaming success"),i(e)})).catch((e=>{this.logger.info(kM,"updateLiveStreaming failed: ".concat(e)),n(e)}))}))}async startLiveStreaming(e,t,r,i){return new Promise(((n,o)=>{const s={type:"START_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,config:r,userInfos:i,urls:t,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(s).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(s);this.logger.error(kM,"startLiveStreamRequest code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),o(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"startLiveStreamRequest success"),n(e)})).catch((e=>{this.logger.info(kM,"startLiveStreamRequest failed: ".concat(e)),o(e)}))}))}async stopLiveStreaming(e){return new Promise(((t,r)=>{const i={type:"STOP_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(i).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(i);this.logger.error(kM,"stopLiveStreaming code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),r(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"stopLiveStreaming success"),t(e)})).catch((e=>{this.logger.info(kM,"stopLiveStreaming failed: ".concat(e)),r(e)}))}))}receiveMsg(e){if(e.type)switch(EC.has("".concat(e.type))||this.logger.info(kM,"message type: ".concat(e.type)),e.type){case bC.statusChangeNotify:var t;null===(t=e.infos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),this.emit(bC.statusChangeNotify,e);break;case bC.uploadLogNotify:this.emit(bC.uploadLogNotify,e);break;case bC.pushStreamNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.pushStreamNotify,e);break}case bC.stopPushStreamNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.stopPushStreamNotify,e);break}case bC.watchStreamNotify:this.emit(bC.watchStreamNotify,e);break;case bC.changeStreamStatusNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.changeStreamStatusNotify,e);break}case bC.disconnectNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.disconnectNotify,e);break}case bC.reconnectNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.reconnectNotify,e);break}case bC.configNotify:this.emit(bC.configNotify,e);break;case bC.appDataChangeNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.appDataChangeNotify,e);break}case bC.top3AudioVolumeNotify:var r;null===(r=e.topUserAudios)||void 0===r||r.forEach((e=>{iE.addPrivacyString(e.userId)})),this.emit(bC.top3AudioVolumeNotify,e);break;case bC.publishStatusNotify:this.emit(bC.publishStatusNotify,e);break;case bC.roomStreamStatusNotify:this.emit(bC.roomStreamStatusNotify,e);break;default:this.logger.error(kM,"unknown message type ".concat(e.type))}else this.logger.error(kM,"unknown message:".concat(e))}setConfigParams(e){this.socket.setKeepAliveParams(e)}getInfo(){return{traceId:this.traceId}}mediaRelay(e,t,r){return new Promise(((i,n)=>{var o,s,a;const c={type:"ROOM_MEDIA_RELAY",srcRoomToken:{roomId:r.roomId,userId:(null===(o=e.srcRoomRelayInfo)||void 0===o?void 0:o.userId)||"0",role:0===r.role?oM.JOINER:oM.PLAYER,ctime:null===(s=e.srcRoomRelayInfo)||void 0===s?void 0:s.ctime,token:null===(a=e.srcRoomRelayInfo)||void 0===a?void 0:a.authorization}};c[t?"addDstRoomInfo":"removeDstRoomInfo"]=e.dstRoomRelayInfo.map((e=>({roomId:e.roomId,userId:r.userId,role:0===e.role?oM.JOINER:oM.PLAYER,ctime:e.ctime,token:e.authorization}))),this.sendRequest(c).then((e=>{0!==e.resultCode?n(new qc(Number(e.resultCode),e.resultMessage)):(this.logger.info(kM,"mediaRelay success"),i(e))})).catch((e=>{this.logger.info(kM,"mediaRelay failed: ".concat(e)),n(e)}))}))}}class MM{constructor(){this.audioStreams=new Map,this.logger=iE.getLogger()}getAudioStreams(){return[...this.audioStreams.values()]}getAudioStream(e){return this.audioStreams.get(e)}addAudioStream(e,t){const r={audioPlayer:null,audioMediaTrack:null,streamId:e,ssrc:t,playStatus:"init"};this.audioStreams.set(e,r)}updateAudioStream(e,t){const r=this.audioStreams.get(e);r.audioMediaTrack=t,r.audioPlayer=new JO({logger:this.logger,playerId:e,track:t})}getAudioLevel(){const e=[];for(const r of this.audioStreams.values()){var t;e.push({streamId:r.streamId,ssrc:r.ssrc,level:null===(t=r.audioPlayer)||void 0===t?void 0:t.getAudioLevel()})}return e}async setAudioOutput(e){if("sinkId"in HTMLMediaElement.prototype&&e)for(const t of this.audioStreams.values())await t.audioPlayer.setSinkId(e)}setAudioVolume(e){const t=e/100;for(const i of this.audioStreams.values()){var r;if("notAllow"===i.playStatus)this.resume(i.streamId).then((()=>{var e;null===(e=i.audioPlayer)||void 0===e||e.setVolume(t)}));else null===(r=i.audioPlayer)||void 0===r||r.setVolume(t)}}muteAudio(e){for(const t of this.audioStreams.values())e||"notAllow"!==t.playStatus?t.audioMediaTrack.enabled=!e:this.resume(t.streamId).then((()=>{t.audioMediaTrack.enabled=!e}))}isAudioMuted(){const e=Array.from(this.audioStreams.values());return!e.every((e=>"normal"===e.playStatus))||!e.every((e=>e.audioMediaTrack.enabled))}async play(e){for(const i of this.audioStreams.values())try{var t;if(e){if(i.streamId===e){var r;await(null===(r=i.audioPlayer)||void 0===r?void 0:r.play()),i.playStatus="normal";break}}else await(null===(t=i.audioPlayer)||void 0===t?void 0:t.play()),i.playStatus="normal"}catch(jN){this.logger.error("RemoteTopNAudioStreams","resume failed, error: ".concat(jN)),i.playStatus="notAllow"}}async resume(e){for(const i of this.audioStreams.values())try{var t;if(e){if(i.streamId===e){var r;await(null===(r=i.audioPlayer)||void 0===r?void 0:r.resume()),i.playStatus="normal";break}}else await(null===(t=i.audioPlayer)||void 0===t?void 0:t.resume()),i.playStatus="normal"}catch(jN){this.logger.error("RemoteTopNAudioStreams","resume failed, error: ".concat(jN)),i.playStatus="notAllow"}}setAudioVolume4Id(e,t){for(const r of this.audioStreams.values())if(r.streamId===e&&r.audioPlayer){"notAllow"===r.playStatus?this.resume(e).then((()=>{r.audioPlayer.setVolume(t/100)})):r.audioPlayer.setVolume(t/100);break}}close(e){if(e&&this.audioStreams.has(e)){const t=this.audioStreams.get(e);return t.audioPlayer.stop(),t.audioMediaTrack=null,t.audioPlayer=null,t.playStatus="init",void this.audioStreams.delete(e)}for(const t of this.audioStreams.values())t.audioPlayer.stop(),t.audioMediaTrack=null,t.audioPlayer=null,t.playStatus="init";this.audioStreams.clear()}}const DM="LocalStreamPublishManager";class NM{constructor(){this.logger=iE.getLogger(),this.localStreams=new Map,this.sdpRepInfo=null}reset(){Array.from(this.localStreams.values()).forEach((e=>{e.localTrackPublishInfos.clear()})),this.logger.info(DM,"reset successfully")}getStreamTrackInfo(e){const t=[];let r;return e.getHRTCTracks({hasTrack:!0}).forEach((i=>{const n=i.getTrackProfile();if(i.getTrackType()===vO.TRACK_TYPE_AUDIO)i.setTrackId(this.sdpRepInfo.audio.streamCodecs[0].streamUid.toString()),r={type:vO.TRACK_TYPE_AUDIO,resolutionId:i.getResolutionId(),upstream:{content:CC.main,mute:i.getTrackMuted(),maxMbps:Math.round((n.bitrate||0)/1e3),sampleRate:n.sampleRate,channels:n.channelCount,codec:wM.OPUS,pt:CM.opusPayload,streamUid:this.sdpRepInfo.audio.streamCodecs[0].streamUid,ssrc:this.sdpRepInfo.audio.sendSsrcBegin}};else{let t;if(e.isAuxiliary())i.setTrackId(this.sdpRepInfo.desktopVideo.streamCodecs[0].streamUid.toString()),t={content:CC.desktop,mute:i.getTrackMuted(),width:n.width,height:n.height,fps:n.frameRate,maxMbps:Math.round((n.maxBitrate||0)/1e3),maxFs:n.frameRate,codec:wM.H264,pt:AM.h264PayLoad,streamUid:this.sdpRepInfo.desktopVideo.streamCodecs[0].streamUid,ssrc:this.sdpRepInfo.desktopVideo.sendSsrcBegin};else{const e=i.getTrackContentType(),r=this.sdpRepInfo.video.streamCodecs.find((t=>t.content===e)).streamUid;i.setTrackId(r.toString()),t={content:e,mute:i.getTrackMuted(),width:n.width,height:n.height,fps:n.frameRate,maxMbps:Math.round((n.maxBitrate||0)/1e3),maxFs:n.frameRate,codec:wM.H264,pt:AM.h264PayLoad,streamUid:r,ssrc:e===CC.main?this.sdpRepInfo.video.sendSsrcBegin:this.sdpRepInfo.video.sendSsrcEnd}}r={type:vO.TRACK_TYPE_VIDEO,resolutionId:i.getResolutionId(),upstream:t}}t.push(r)})),this.logger.debug(DM,"getStreamTrackInfo, get trackInfos: ".concat(JSON.stringify(t))),t}getLocalStream(e){const t=this.localStreams.get(e);return t?t.localStream:null}generatePubInfoWhenPublish(e,t){const r={allTracks2Publish:[],tracks2NewPublish:[],tracks2KeepPublish:[],tracks2UnPublish:[]},i=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,n=this.localStreams.get(i);return n&&0!==n.localTrackPublishInfos.size?this.isSameStreamId(e)?this.updateStream(e,r):this.replaceStream(e,r):this.addStream(e,r,t),this.buildAll2PublishTrackInfo(r.allTracks2Publish,e.isAuxiliary(),!0),this.logger.info(DM,"generatePubInfoWhenPublish tracks2Update input: ".concat(JSON.stringify(r))),r}setSdpRepInfo(e){this.sdpRepInfo=e}buildAll2PublishTrackInfo(e,t,r){t?(this.buildMediaPubInfo(e,vO.TRACK_TYPE_VIDEO,yO.STREAM_TYPE_MAIN),this.buildMediaPubInfo(e,vO.TRACK_TYPE_AUDIO,yO.STREAM_TYPE_MAIN),r&&this.buildMediaPubInfo(e,vO.TRACK_TYPE_VIDEO,yO.STREAM_TYPE_AUX)):(this.buildMediaPubInfo(e,vO.TRACK_TYPE_VIDEO,yO.STREAM_TYPE_AUX),r&&(this.buildMediaPubInfo(e,vO.TRACK_TYPE_VIDEO,yO.STREAM_TYPE_MAIN),this.buildMediaPubInfo(e,vO.TRACK_TYPE_AUDIO,yO.STREAM_TYPE_MAIN)))}buildMediaPubInfo(e,t,r){var i;const n=null===(i=this.localStreams.get(r))||void 0===i?void 0:i.localTrackPublishInfos;n&&Array.from(n.values()).filter((e=>e.type===t)).forEach((t=>{t.sender&&(t.upstream.mute=!t.sender.track.enabled),e.push(t)}))}isSameStreamId(e){const t=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN;return this.localStreams.get(t).streamId===e.getLocalId()}static getString4TrackPublishInfos(e){let t;for(const r of e.entries())t="".concat(t||""," resolutionId: ").concat(r[0],", track type: ").concat(r[1].type,", watched: ").concat(r[1].watched,", published: ").concat(r[1].published);return t}updateStream(e,t){this.logger.info(DM,"updateStream, update stream begin");const r=[],i=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,n=this.getStreamTrackInfo(e),o=this.localStreams.get(i);n.forEach((e=>{const n=o.localTrackPublishInfos.get(e.resolutionId);r.push(e),n?(n.upstream.mute=e.upstream.mute,n.published&&t.tracks2KeepPublish.push(n),n.watched&&!n.published&&t.tracks2NewPublish.push(n)):this.addTrack(i,e,t,o)}));const s=[];Array.from(o.localTrackPublishInfos.values()).forEach((e=>{const i=r.find((t=>t.resolutionId===e.resolutionId));if(i){if(!NM.isSameResolution(i,e)){const t={type:i.type,resolutionId:i.resolutionId,upstream:i.upstream,published:e.published,watched:e.watched,ssrc:e.ssrc,sender:e.sender};o.localTrackPublishInfos.set(i.resolutionId,t)}}else e.published&&t.tracks2UnPublish.push(e),s.push(e.resolutionId)})),s.forEach((e=>{o.localTrackPublishInfos.delete(e)})),this.logger.info(DM,"updateStream, update stream ".concat(e.getLocalId()," successfully\n ").concat(NM.getString4TrackPublishInfos(o.localTrackPublishInfos)))}static isSameResolution(e,t){return e.upstream.height===t.upstream.height&&e.upstream.width===t.upstream.width}replaceStream(e,t){return this.logger.info(DM,"replaceStream begin"),this.addStream(e,t)}addStream(e,t,r){const i=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,n=this.getStreamTrackInfo(e),o={localStream:e,streamId:e.getLocalId(),localTrackPublishInfos:new Map};n.forEach((e=>{this.addTrack(i,e,t,o,r)})),this.localStreams.set(i,o),this.logger.info(DM,"addStream, add stream ".concat(e.getLocalId()," successfully ,\n ").concat(NM.getString4TrackPublishInfos(o.localTrackPublishInfos)))}generatePubInfoWhenUnPublish(e){const t=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,r={allTracks2Publish:[],tracks2KeepPublish:[],tracks2NewPublish:[],tracks2UnPublish:[]},i=this.localStreams.get(t);return i?(Array.from(i.localTrackPublishInfos.values()).filter((e=>e.published)).forEach((e=>{r.tracks2UnPublish.push(e)})),this.buildAll2PublishTrackInfo(r.allTracks2Publish,e.isAuxiliary(),!1),r):(this.logger.warn(DM,"stream not publish"),r.allTracks2Publish=null,r)}removeStream(e){const t=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN;if(!this.localStreams.has(t))throw this.logger.error(DM,"removeStream, stream not exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.localStreams.delete(t)}generatePubInfoWhenWatch(e,t,r,i){if(this.logger.info(DM,"generatePubInfoWhenWatch watch ".concat(e," streams")),!t||!r)return null;const n={allTracks2Publish:null,tracks2KeepPublish:[],tracks2NewPublish:[],tracks2UnPublish:[]},o=this.localStreams.get(e);if(!o)return this.logger.info(DM,"generatePubInfoWhenWatch, stream not exist"),null;const s=Array.from(o.localTrackPublishInfos.values());return 0===t.length&&0===r.length?s.forEach((e=>{this.renewTrack2Update(!1,e,n)})):i===vO.TRACK_TYPE_VIDEO&&0===t.length&&r.length>0&&s.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).forEach((e=>{this.renewTrack2Update(!1,e,n)})),s.forEach((e=>{if(t.length>0&&e.type===vO.TRACK_TYPE_VIDEO){const r=t.find((t=>t===e.upstream.ssrc));this.renewTrack2Update(!!r,e,n)}if(r.length>0&&e.type===vO.TRACK_TYPE_AUDIO){const t=r.find((t=>t===e.upstream.ssrc));this.renewTrack2Update(!!t,e,n)}})),t.forEach((e=>{s.some((t=>e===t.upstream.ssrc))||this.logger.error(DM,"generatePubInfoWhenWatch, watch video ssrc:".concat(e," is not exist"))})),r.forEach((e=>{s.some((t=>e===t.upstream.ssrc))||this.logger.error(DM,"generatePubInfoWhenWatch, watch audio ssrc:".concat(e," is not exist"))})),n}renewTrack2Update(e,t,r){e?t.published?(r.tracks2KeepPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, keep ".concat(t.type," ssrc:").concat(t.ssrc))):(t.watched=!0,r.tracks2NewPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, new publish ".concat(t.type," ssrc:").concat(t.ssrc))):t.published&&(t.watched=!1,r.tracks2UnPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, new unpublish ".concat(t.type," ssrc:").concat(t.ssrc)))}addTrack(e,t,r,i,n){const o=NM.getDefaultWatchFlag(e,t.type,n),s={type:t.type,resolutionId:t.resolutionId,published:!1,watched:o,upstream:t.upstream,ssrc:t.upstream.ssrc,sender:null};s.watched&&r.tracks2NewPublish.push(s),i.localTrackPublishInfos.set(t.resolutionId,s),this.logger.info(DM,"addTrack, add track for resolutionId ".concat(t.resolutionId," successfully"))}static getDefaultWatchFlag(e,t,r){return e===yO.STREAM_TYPE_MAIN&&t===vO.TRACK_TYPE_AUDIO||(null==r?void 0:r.autoPushVideo)&&t===vO.TRACK_TYPE_VIDEO}publishAuxVideoTrackOK(e,t){this.publishTrackSuccess(yO.STREAM_TYPE_AUX,vO.TRACK_TYPE_VIDEO,e,t)}publishMainVideoTrackOK(e,t,r){this.publishTrackSuccess(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO,e,t,r)}publishMainAudioTrackOK(e,t){this.publishTrackSuccess(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO,e,t)}publishTrackSuccess(e,t,r,i,n){const o=this.localStreams.get(e);if(!o)throw this.logger.error(DM,"stream is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const s=this.getTrackInfo(o,t,n);if(!s)throw this.logger.error(DM,"getTrackInfo return empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);s.published&&this.logger.info(DM,"stream already published"),s.published=!0,s.sender=r,this.logger.info(DM,"publish track for trackId: ".concat(n," successfully"))}unPublishTrackSuccess(e,t,r){const i=this.localStreams.get(e);if(!i)throw this.logger.error(DM,"stream is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(t===vO.TRACK_TYPE_VIDEO&&!r)throw this.logger.error(DM,"video trackId is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=this.getTrackInfo(i,t,r);n?(n.published||this.logger.info(DM,"stream already unPublished"),n.published=!1,n.sender=null,this.logger.info(DM,"unPublish track for trackId: ".concat(r," successfully"))):this.logger.info(DM,"getTrackInfo return empty")}getMainStreamVideoPublishInfo(){return this.getTrackPublishInfos(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO)}getPublishedMainVideoTrackInfo(e){const t=this.getTrackPublishInfo(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO,e);return null!=t&&t.published&&t.sender?t:null}getPublishedMainAudioTrackInfo(){const e=this.getTrackPublishInfo(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO);return null!=e&&e.published&&e.sender?e:null}getPublishedAuxVideoTrackInfo(){const e=this.getTrackPublishInfo(yO.STREAM_TYPE_AUX,vO.TRACK_TYPE_VIDEO);return null!=e&&e.published&&e.sender?e:null}getPublishedMainVideoTrackInfos(){const e=this.getTrackPublishInfos(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO);return(null==e?void 0:e.length)>0?e.filter((e=>e.published&&e.sender)):null}getPublishedMainStreamInfos(){const e=this.getTrackPublishInfos(yO.STREAM_TYPE_MAIN);return(null==e?void 0:e.length)>0?e.filter((e=>e.published&&e.sender)):null}getPublishedAuxStreamInfo(){const e=this.localStreams.get(yO.STREAM_TYPE_AUX);if(!e)return null;return Array.from(e.localTrackPublishInfos.values()).find((e=>e.published&&e.sender))?e:null}getTrackPublishInfos(e,t){const r=this.localStreams.get(e);return r?t?Array.from(r.localTrackPublishInfos.values()).filter((e=>e.type===t)):Array.from(r.localTrackPublishInfos.values()):(this.logger.info(DM,"getTrackPublishInfos, not found"),null)}getTrackPublishInfo(e,t,r){const i=this.localStreams.get(e);return i?this.getTrackInfo(i,t,r):null}isAuxVideoTrackPublished(){const e=this.isTrackPublished(yO.STREAM_TYPE_AUX,vO.TRACK_TYPE_VIDEO);return this.logger.info(DM,"isAuxVideoTrackPublished: ".concat(e)),e}isMainStreamPublished(){const e=this.isTrackPublished(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO)||this.isTrackPublished(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO);return this.logger.info(DM,"isMainVideoTrackPublished: ".concat(e)),e}isTrackPublished(e,t,r){const i=this.localStreams.get(e);if(!i)return this.logger.info(DM,"isTrackPublished, not found"),!1;const n=this.getTrackInfo(i,t,r);return n?n.published&&!!n.sender:(this.logger.info(DM,"isTrackPublished, not found"),!1)}getTrackInfo(e,t,r){if(!e||0===e.localTrackPublishInfos.size)return null;if(t===vO.TRACK_TYPE_AUDIO)return Array.from(e.localTrackPublishInfos.values()).find((e=>e.type===vO.TRACK_TYPE_AUDIO));if(r)return Array.from(e.localTrackPublishInfos.values()).find((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.upstream.streamUid.toString()===r));const i=NM.getMaxResolutionId(e);return i?e.localTrackPublishInfos.get(i):null}static getMaxResolutionId(e){var t,r;return null==e||null===(t=e.localStream)||void 0===t||null===(r=t.getMaxResolutionHRTCTrack())||void 0===r?void 0:r.getResolutionId()}unPublishAuxStreamOK(){this.unPublishStreamSuccess(yO.STREAM_TYPE_AUX)}unPublishMainStreamOK(){this.unPublishStreamSuccess(yO.STREAM_TYPE_MAIN)}unPublishStreamSuccess(e){var t;const r=this.localStreams.get(e);r?(null===(t=r.localStream)||void 0===t||t.getHRTCTracks({hasTrack:!0,mediaType:vO.TRACK_TYPE_VIDEO}).forEach((e=>e&&e.setTrackId(""))),this.removeStream(r.localStream),this.logger.info(DM,"unPublishStreamSuccess, ".concat(e))):this.logger.warn(DM,"stream not publish")}isAuxVideoTrackValid(e){return this.isTrackValid(yO.STREAM_TYPE_AUX,vO.TRACK_TYPE_VIDEO,e)}isTrackValid(e,t,r){const i=this.localStreams.get(e);return i?Array.from(i.localTrackPublishInfos.values()).some((e=>e.type===t&&e.upstream.streamUid.toString()===r)):(this.logger.info(DM,"isTrackValid, not found"),!1)}generateOptTags(e,t){const r=[],i=this.localStreams.get(e);if(!i)return r;return Array.from(i.localTrackPublishInfos.values()).filter((e=>e.type===t&&e.published&&e.sender)).forEach((e=>{if(t===vO.TRACK_TYPE_VIDEO){const t=e.upstream?e.upstream.height:0,i=e.upstream?e.upstream.width:0,n="".concat(e.ssrc,":").concat(t,"*").concat(i);r.push(n)}else{var n;const t=null===(n=i.localStream.getAudioHRTCTrack())||void 0===n?void 0:n.getTrackProfile(),o="".concat(e.ssrc,":").concat(t?t.sampleRate:0);r.push(o)}})),r}generateMainAudioOptTag(){const e=this.generateOptTags(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO);return e.length>0?e[0]:null}generateAuxOptTag(){const e=this.generateOptTags(yO.STREAM_TYPE_AUX,vO.TRACK_TYPE_VIDEO);return e.length>0?e[0]:null}generateMainVideoOptTags(){const e=this.generateOptTags(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO);return e.length>0?e:null}}var UM={},xM={exports:{}},LM=xM.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(LM).forEach((function(e){LM[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var o=0;o1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},jM=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n{for(const t in e)ZM.includes(t)||delete e[t]})));return XR.shieldIpAddress(WM(t))}}getMedias(e,t){return e.media.filter((e=>{let{type:r}=e;return r===t}))}deleteUnexpectedMedia(e){e.media&&(e.media=e.media.filter((e=>{let{type:t}=e;return t===vO.TRACK_TYPE_VIDEO||t===vO.TRACK_TYPE_AUDIO||t===vO.TYPE_APPLICATION})),this.portType_===NC.portNormal&&e.groups&&(e.groups=e.groups.filter((e=>{let{type:t}=e;return"BUNDLE"!==t.toLocaleUpperCase()}))))}transformVideoPayload(e){if(!e.rtp)return void this.logger_.warn(this.module_,"transformVideoPayload failed ,rtp is null");let t=null,r=null,i=0;for(const n of e.rtp){if(n.codec.toUpperCase()!==wM.H264)continue;r||(r=n.payload,this.logger_.info(this.module_,"record firstPayload, firstPayload: ".concat(r)));const o=eD.getPacketizationMode(e.fmtp,n.payload),s=eD.getProfileLevelId(e.fmtp,n.payload);if(1===o&&(0===i&&(r=n.payload,i=1),"42e01f"===s)){t=n.payload,this.logger_.info(this.module_,"set retainPayload in transformVideoPayload, retainPayload: ".concat(t));break}}t||(t=r,this.logger_.info(this.module_,"no expected payload, use firstPayload as retainPayload, retainPayload: ".concat(t))),t?(eD.deletePayload(e,t),eD.modifyPayload(e,AM.h264PayLoad),eD.addVideoFec(e),eD.addFmtpAttr(e,AM.h264PayLoad,"max-br","5000000"),eD.addFmtpAttr(e,AM.h264PayLoad,QM,"1"),eD.addFmtpAttr(e,AM.rtxPayLoad,"apt","".concat(AM.h264PayLoad)),eD.addFmtpAttr(e,AM.rtxPayLoad,QM,"1")):this.logger_.error(this.module_,"transformVideoPayload failed,can not find expected payload.")}transformAudioPayload(e){if(!e.rtp)return void this.logger_.warn(this.module_,"transformAudioPayload failed, rtp is null");let t;for(const r of e.rtp)if(r.codec.toLowerCase()===wM.OPUS){t=r.payload;break}t?(eD.deletePayload(e,t),eD.modifyPayload(e,CM.opusPayload),eD.addNack(e)):this.logger_.error(this.module_,"transformAudioPayload failed,can not find expected payload.")}deleteRetransmissionSsrc(e){if(!e.ssrcGroups||!e.ssrcs)return;const t=[];e.ssrcGroups.forEach((e=>{let{ssrcs:r}=e;const i=this.getRetransmissionSsrc(r);null!=i&&t.push(i)})),0!==t.length&&(e.ssrcGroups=void 0,e.ssrcs=e.ssrcs.filter((e=>{let{id:r}=e;return!t.includes(r.toString())})))}addVideoSsrcRange(e,t){!t||t.length<1||(e.invalid||(e.invalid=[]),e.invalid.push({value:"send-ssrc-list:".concat(t.join(","))}))}static addAudioSsrcRange(e,t,r){if(t)if(e.invalid||(e.invalid=[]),r){const r=XR.getRandomUint32();e.invalid.push({value:"send-ssrc-list:".concat(t,",").concat(r)})}else e.invalid.push({value:"send-ssrc-list:".concat(t)})}modifyCandidate(e,t){if(!e.candidates){const r=null==t?void 0:t.find((t=>"".concat(e.mid)==="".concat(t.sdpMid)));if(r){const t=/.*generation\s(\d+).*/.exec(r.candidate)||[],i=/.*network\-id\s(\d+).*/.exec(r.candidate)||[],n=/.*network\-cost\s(\d+).*/.exec(r.candidate)||[];e.candidates=e.candidates||[],e.candidates.push({foundation:r.foundation,component:"rtp"===r.component?1:2,transport:r.protocol,priority:r.priority,ip:r.address,port:r.port,type:r.type,raddr:r.relatedAddress,rport:r.relatedPort,tcptype:r.tcpType,generation:2===t.length?parseInt(t[1]):void 0,"network-id":2===i.length?parseInt(i[1]):void 0,"network-cost":2===n.length?parseInt(n[1]):void 0})}}}static getPacketizationMode(e,t){if(!e)return 1;for(const r of e){if(r.payload!==t)continue;if(!r.config.includes(qM))return 1;const e=JM(r.config);return null==e[qM]?1:parseInt(String(e[qM]),10)}return 1}static getProfileLevelId(e,t){if(!e)return"";for(const r of e){if(r.payload!==t)continue;if(!r.config.includes(XM))return"";const e=JM(r.config);return e[XM]?String(e[XM]):""}return""}static deletePayload(e,t){e.rtp&&(e.rtp=e.rtp.filter((e=>{let{payload:r}=e;return r===t}))),e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>{let{payload:r}=e;return r===t}))),e.fmtp&&(e.fmtp=e.fmtp.filter((e=>{let{payload:r}=e;return r===t}))),e.payloads=t.toString()}static modifyPayload(e,t){e.rtp&&e.rtp.forEach((e=>{e.payload=t})),e.rtcpFb&&e.rtcpFb.forEach((e=>{e.payload=t})),e.fmtp&&e.fmtp.forEach((r=>{r.payload=t,e.type===vO.TRACK_TYPE_AUDIO&&/stereo/.test(r.config)&&(r.config=r.config.replace("stereo=1","stereo=0"))})),e.payloads=t.toString()}static addVideoFec(e){e.rtp||(e.rtp=[]),e.rtp.push({payload:AM.rtxPayLoad,codec:"rtx",rate:9e4}),e.rtp.push({payload:AM.redPayLoad,codec:"red",rate:9e4}),e.rtp.push({payload:AM.ulpfecPayLoad,codec:"ulpfec",rate:9e4}),e.payloads="".concat(AM.rtxPayLoad," ").concat(e.payloads," ").concat(AM.redPayLoad," ").concat(AM.ulpfecPayLoad)}static addFmtpAttr(e,t,r,i){if(!e.fmtp||0===e.fmtp.length)return e.fmtp=[],void e.fmtp.push({payload:t,config:r+"="+i});const n=e.fmtp.find((e=>e.payload===t));if(n){if(JM(n.config)[r])return;n.config=n.config+";"+r+"="+i}else e.fmtp.push({payload:t,config:r+"="+i})}static addNack(e){const t=e.rtp[0].payload;e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.push({payload:t,type:"ccm",subtype:"fir"}),e.rtcpFb.push({payload:t,type:"nack"}),e.rtcpFb.push({payload:t,type:"nack",subtype:"pli"})}getRetransmissionSsrc(e){if(!e)return void this.logger_.warn(this.module_,"getRetransmissionSsrc failed, ssrcs is null");const t=e.split(" ");if(2===t.length)return t[1];this.logger_.warn(this.module_,"getRetransmissionSsrc failed, ssrcs(".concat(e,") is invalid"))}static generateSsrcLabel(){return"".concat(XR.generateRandomId(8,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(12,36))}static addSsrcAttr(e,t,r){e.ssrcs||(e.ssrcs=[]);for(let i=0;i{let{id:r}=e;return!t.find((e=>e.toString()===r.toString()))})))}static getNegCmdInfoAndDelete(e){let t="",r="",i=!1;for(let n=0;n{e.value.indexOf("bindCrypto-key")>=0&&(t=e.value.substring(15)),e.value.indexOf("websocket-uri")>=0&&(r=e.value.substring(14))})),e.splice(n,1)):/SCTP/gi.test(e[n].protocol)&&(i=!0));return{bindCryptoKey:t,wsUrl:r,dataChannelEnable:i}}generateSsrcMslabel(){return XR.generateRandomId(36)}containsValidVideoPayload(e){this.logger_.debug(this.module_,"containsValidVideoPayload, offerSdp: ".concat(this.printSdpInfo(e)));const t=this.parseSdp(e);if(!t)return this.logger_.error(this.module_,"containsValidVideoPayload failed,the sdp is invalid"),!1;return this.getMedias(t,vO.TRACK_TYPE_VIDEO).some((e=>{var t;return null===(t=e.rtp)||void 0===t?void 0:t.some((e=>e.codec.toUpperCase()===wM.H264))}))}transformOfferSdp(e){this.logger_.info(this.module_,"transformOfferSdp begin");const t=this.parseSdp(e);if(!t)return void this.logger_.error(this.module_,"transformOfferSdp failed,the sdp is invalid");this.deleteUnexpectedMedia(t);const r=this.getMedias(t,vO.TRACK_TYPE_VIDEO),i=this.getMedias(t,vO.TRACK_TYPE_AUDIO);r.forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e)})),i.forEach((e=>{this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e)}));const n=WM(t);return this.logger_.debug(this.module_,"transformOfferSdp success, sdp: ".concat(this.printSdpInfo(n))),n}editOrigin(e){e.origin&&(e.origin.username=Mw.getBrowserInfo())}modifyAuxSdpInfo(e,t,r){const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyAuxSdpInfo failed,the sdp is invalid : ".concat(e));this.editOrigin(i);const n=this.getMedias(i,vO.TRACK_TYPE_VIDEO);n&&n.length>0&&(this.addVideoSsrcRange(n[0],r),this.modifyCandidate(n[0],t));const o=WM(i);return this.logger_.debug(this.module_,"modifyAuxSdpInfo success, sdp: ".concat(this.printSdpInfo(o))),o}modifyMainSdpInfo(e,t,r,i,n,o){const s=this.parseSdp(e);if(!s)return void this.logger_.error(this.module_,"modifyMainSdpInfo failed, the sdp is invalid : ".concat(e));this.editOrigin(s);const a=this.getMedias(s,vO.TRACK_TYPE_VIDEO),c=this.getMedias(s,vO.TRACK_TYPE_AUDIO);let u="",d="";if(a&&a.length>0&&(this.addVideoSsrcRange(a[0],r),this.modifyCandidate(a[0],t),d=a[0].mid,a.length>1))for(let h=0;h0&&(eD.addAudioSsrcRange(c[0],i,n),this.modifyCandidate(c[0],t),u=c[0].mid);for(const h of s.groups||[])if("BUNDLE"===h.type){h.mids="".concat(u," ").concat(d);break}n&&this.addNegCmdInfo(s,o);const l=WM(s);return this.logger_.debug(this.module_,"modifyMainSdpInfo success, sdp: ".concat(this.printSdpInfo(l))),l}addNegCmdInfo(e,t){if(t){const r=this.parseSdp(t).media.find((e=>e.type===vO.TYPE_APPLICATION)),i=e.media.filter((e=>null==e?void 0:e.type)),n=i[i.length-1];r.mid=["audio","video"].includes(n.mid)?"data":n.mid+1,e.media.push(r),e.groups.forEach((e=>{"BUNDLE"===e.type&&(e.mids="".concat(e.mids," ").concat(r.mid))}))}const r={type:"application",port:443,protocol:"TCP/WSS/RTP *",setup:"active",invalid:[]};r.invalid.push({value:"connection:new"}),r.invalid.push({value:"content:cmd"}),r.invalid.push({value:"bindCrypto-type:0"}),r.invalid.push({value:"bindCrypto-method:hmac-share256"}),e.media.push(r)}getSfuInfo(e,t){const r=this.parseSdp(e),i={ipAddress:"",auxPort:0};let n;const o=this.getMedias(r,vO.TRACK_TYPE_AUDIO);o&&o.length>0&&(i.audioPort=o[0].port,n=o[0].connection);const s=this.getMedias(r,vO.TRACK_TYPE_VIDEO);if(s&&s.length>0&&(i.videoPort=s[0].port,n=s[0].connection),n&&(i.ipAddress=n.ip),t){const e=this.parseSdp(t),r=this.getMedias(e,vO.TRACK_TYPE_VIDEO);r&&r.length>0&&r[0].connection&&(i.auxPort=r[0].port)}return i}}class tD extends eD{static modifyDirection(e){e.ssrcs&&0!==e.ssrcs.length?e.direction=EM.SEND_RECV:e.direction=EM.RECV_ONLY}hasSSRC(e,t){const r=this.parseSdp(e);if(!r)return this.logger_.error(this.module_,"hasSSRC failed"),!1;const i=this.getMedias(r,t);return i&&i.length>0&&!!i[0].ssrcs}getMslabelByCname(e,t){if(!e)return null;if(!e.ssrcs)return null;let r;for(const i of e.ssrcs)if(i.attribute.toLocaleLowerCase()===this.ssrcAttrCname_&&i.value===t){r=i.id;break}if(!r)return null;for(const i of e.ssrcs)if(i.id===r&&i.attribute.toLocaleLowerCase()===this.ssrcAttrMslabel_)return i.value;return null}addSsrc(e,t,r,i,n,o){const s=r,a=this.getMslabelByCname(e,s),c=this.getMslabelByCname(t,s);let u,d,l=!1,h=!1;if(a&&a===i||!n||(h=!0),c&&c===i||!o||(l=!0),h&&(u=c||i||this.generateSsrcMslabel()),l&&(d=i||this.generateSsrcMslabel()),this.logger_.debug(this.module_,"addSsrc, userId: ".concat(r,", audioMslabel: ").concat(u," videooMslabel: ").concat(d)),u){const t=eD.generateSsrcLabel(),r=[[this.ssrcAttrCname_,s],[this.ssrcAttrMslabel_,u],[this.ssrcAttrLabel_,t],[this.ssrcAttrMsid_,u+" "+t]];eD.addSsrcAttr(e,n,r)}if(d){const e=eD.generateSsrcLabel(),r=[[this.ssrcAttrCname_,s],[this.ssrcAttrMslabel_,d],[this.ssrcAttrLabel_,e],[this.ssrcAttrMsid_,d+" "+e]];eD.addSsrcAttr(t,o,r)}return d||u}static modifyMediaSsrc(e,t){if(!e.ssrcs)return;for(let r=0;r0&&(this.portType_===NC.portNormal&&(r[0].rtcpMux=void 0),tD.modifyDirection(r[0])),i&&i.length>0&&(this.portType_===NC.portNormal&&(i[0].rtcpMux=void 0),tD.modifyDirection(i[0])),this.portType_===NC.portNormal&&(t.groups=void 0);const{bindCryptoKey:n,wsUrl:o,dataChannelEnable:s}=eD.getNegCmdInfoAndDelete(t.media),a=WM(t);return this.logger_.debug(this.module_,"transformAnswerSdp success,answerSdp: ".concat(this.printSdpInfo(a))),{remoteDescription:a,bindCryptoKey:n,wsUrl:o,dataChannelEnable:s}}deleteSSRC(e,t,r){if(0===t.length&&!r)return e;this.logger_.info(this.module_,"deleteVideoSSRC ".concat(t,", ").concat(r));const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"deleteVideoSSRC failed");const n=this.getMedias(i,vO.TRACK_TYPE_VIDEO);n&&n.length>0&&(t&&eD.deleteSsrcAttr(n[0],t),tD.modifyDirection(n[0]));const o=this.getMedias(i,vO.TRACK_TYPE_AUDIO);o&&o.length>0&&(r&&eD.deleteSsrcAttr(o[0],[r]),tD.modifyDirection(o[0]));const s=WM(i);return this.logger_.info(this.module_,"deleteVideoSSRC ".concat(t," success")),s}addUser(e,t,r,i){const n=this.parseSdp(e);if(!n)return void this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(e));const o=this.getMedias(n,vO.TRACK_TYPE_VIDEO),s=this.getMedias(n,vO.TRACK_TYPE_AUDIO);let a,c;o&&o.length>0&&(a=o[0]),s&&s.length>0&&(c=s[0]);const u=this.addSsrc(c,a,t,r,i.audioSsrc,i.videoSsrc);a&&tD.modifyDirection(a),c&&tD.modifyDirection(c);const d=WM(n);return this.logger_.debug(this.module_,"addUser success, answerSdp: ".concat(this.printSdpInfo(d))),{answerSdp:d,streamId:u}}deleteUser(e,t,r){const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(e));if((null==t?void 0:t.length)>0){const e=this.getMedias(i,vO.TRACK_TYPE_VIDEO);e&&e.length>0&&(t.forEach((t=>{t&&eD.deleteSsrcAttr(e[0],[t])})),tD.modifyDirection(e[0]))}if((null==r?void 0:r.length)>0){const e=this.getMedias(i,vO.TRACK_TYPE_AUDIO);e&&e.length>0&&(r.forEach((t=>{t&&eD.deleteSsrcAttr(e[0],[t])})),tD.modifyDirection(e[0]))}const n=WM(i);return this.logger_.debug(this.module_,"deleteUser success, answerSdp: ".concat(this.printSdpInfo(n))),n}modifyPublishOfferSdp(e,t,r){this.logger_.debug(this.module_,"modifyPublishOfferSdp start, sdp: ".concat(this.printSdpInfo(e)));const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyPublishOfferSdp failed, the sdp is invalid: ".concat(e));this.deleteUnexpectedMedia(i);const n=this.getMedias(i,vO.TRACK_TYPE_VIDEO),o=this.getMedias(i,vO.TRACK_TYPE_AUDIO);if(n&&n.length>0&&(this.transformVideoPayload(n[0]),this.deleteRetransmissionSsrc(n[0]),t&&t.length>0&&tD.modifyMediaSsrc(n[0],t)),o&&o.length>0&&(this.transformAudioPayload(o[0]),this.deleteRetransmissionSsrc(o[0]),r)){const e=[r];tD.modifyMediaSsrc(o[0],e)}const s=WM(i);return this.logger_.debug(this.module_,"modifyPublishOfferSdp success, sdp: ".concat(this.printSdpInfo(s))),s}}class rD extends eD{static modifyDirectionWhenAddUser(e,t){e&&(e.direction===EM.RECV_ONLY?e.direction=EM.SEND_RECV:e.direction===EM.INACTIVE&&(e.direction=EM.SEND_ONLY)),t&&(t.direction===EM.SEND_ONLY?t.direction=EM.SEND_RECV:t.direction===EM.INACTIVE&&(t.direction=EM.RECV_ONLY))}addSSRC(e,t,r,i){const n=r||this.generateSsrcMslabel();this.logger_.debug(this.module_,"addSSRC, userId:".concat(t,", mslabel:").concat(n,", streamId:").concat(r,", ssrc:").concat(i)),e.ssrcs&&delete e.ssrcs;const o=eD.generateSsrcLabel(),s=[[this.ssrcAttrCname_,t],[this.ssrcAttrMslabel_,n],[this.ssrcAttrLabel_,o],[this.ssrcAttrMsid_,n+" "+o]];return eD.addSsrcAttr(e,i,s),n}static modifyDirectionWhenDelUser(e,t){e.direction===EM.SEND_RECV?e.direction=EM.RECV_ONLY:e.direction===EM.SEND_ONLY&&(e.direction=EM.INACTIVE),t.direction===EM.SEND_RECV?t.direction=EM.SEND_ONLY:t.direction===EM.RECV_ONLY&&(t.direction=EM.INACTIVE)}hasSSRC(e,t){const r=this.parseSdp(e);if(!r)return this.logger_.error(this.module_,"hasSSRC failed"),!1;return this.getMedias(r,t).some((e=>(e.direction===EM.SEND_ONLY||e.direction===EM.SEND_RECV)&&!!e.ssrcs))}delteInvalidLines(e){this.deleteUnexpectedMedia(e);const t=this.getMedias(e,vO.TRACK_TYPE_VIDEO),r=this.getMedias(e,vO.TRACK_TYPE_AUDIO);t.forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e)})),r.forEach((e=>{this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e)}))}getAvailableSenderMedia(e,t){return e.media.filter((e=>{let{type:r,direction:i}=e;return r===t&&(i===EM.SEND_ONLY||i===EM.SEND_RECV)}))}modifyUnifiedMediaSsrc(e,t,r){if(e.ssrcs&&0!==e.ssrcs.length)e.ssrcs.forEach((e=>{e.attribute===this.ssrcAttrCname_&&(e.value=r),e.id=t}));else{const i=[[this.ssrcAttrCname_,r]];eD.addSsrcAttr(e,t,i)}}static modifyBundle(e,t){for(const r of e.groups||[])if("BUNDLE"===r.type){r.mids.split(" ").includes("".concat(t))||(r.mids="".concat(r.mids," ").concat(t));break}}modifyAnswerDirection(e,t){var r;const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyAnswerDirection failed,the sdp is invalid");const n=null===(r=i.media)||void 0===r?void 0:r.find((e=>"".concat(e.mid)==="".concat(t)));return n&&(n.direction===EM.INACTIVE?n.direction=EM.RECV_ONLY:n.direction===EM.SEND_ONLY&&(n.direction=EM.SEND_RECV)),WM(i)}transformAnswerSdp(e,t){this.logger_.debug(this.module_,"transformAnswerSdp, answerSdp: ".concat(this.printSdpInfo(e)));const r=this.parseSdp(e),i=this.parseSdp(t);if(!r||!i)return void this.logger_.error(this.module_,"transformAnswerSdp failed,the sdp is invalid");this.getMedias(r,vO.TRACK_TYPE_AUDIO).forEach((e=>{this.portType_===NC.portNormal&&(e.rtcpMux=void 0),e.ssrcs||(e.direction=EM.INACTIVE)}));let n=this.getMedias(r,vO.TRACK_TYPE_VIDEO);const o=this.getMedias(i,vO.TRACK_TYPE_VIDEO);if(o.length!==n.length){const e=n.map((e=>"".concat(e.mid)));o.forEach((t=>{if(!e.includes("".concat(t.mid))){const e=JSON.parse(JSON.stringify(n[0]));e.mid=t.mid,r.media.push(e),rD.modifyBundle(r,t.mid)}}))}n=this.getMedias(r,vO.TRACK_TYPE_VIDEO),n.forEach((e=>{this.portType_===NC.portNormal&&(e.rtcpMux=void 0),e.direction=EM.INACTIVE})),this.portType_===NC.portNormal&&(r.groups=void 0);const{bindCryptoKey:s,wsUrl:a,dataChannelEnable:c}=eD.getNegCmdInfoAndDelete(r.media),u=this.getMedias(r,vO.TYPE_APPLICATION);if(r.media=r.media.filter((e=>e.type!==vO.TYPE_APPLICATION)),u.length>0){const e=this.getMedias(r,vO.TRACK_TYPE_VIDEO).map((e=>parseInt("".concat(e.mid))));u[0].mid="".concat(Math.max(...e)+1),Mw.isFirefox()&&(u[0].port=9),r.media.push(...u),rD.modifyBundle(r,"".concat(u[0].mid))}const d=WM(r);return this.logger_.debug(this.module_,"transformAnswerSdp success,answerSdp: ".concat(this.printSdpInfo(d))),{remoteDescription:d,bindCryptoKey:s,wsUrl:a,dataChannelEnable:c}}addUser(e,t,r,i,n,o){var s,a;const c=this.parseSdp(e);if(!c)return this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(e)),null;const u=this.parseSdp(t);if(!u)return this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(t)),null;this.delteInvalidLines(u);const d=null===(s=u.media)||void 0===s?void 0:s.find((e=>"".concat(e.mid)===r)),l=null===(a=c.media)||void 0===a?void 0:a.find((e=>e.type===d.type)),h=JSON.parse(JSON.stringify(l));h.mid=r,h.direction=EM.SEND_ONLY,h.type===vO.TRACK_TYPE_AUDIO&&this.portType_===NC.portReduce&&delete h.candidates;const f=this.addSSRC(h,i,n,o);c.media.push(h),rD.modifyBundle(c,r),rD.modifyDirectionWhenAddUser(h,d);const p=WM(c),m=WM(u);return this.logger_.debug(this.module_,"addUser success, offer: ".concat(this.printSdpInfo(m)," answer: ").concat(this.printSdpInfo(p))),{offerSdp:m,answerSdp:p,streamId:f}}async deleteUser(e,t,r,i,n){const o=this.parseSdp(e);if(!o)return this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(e)),null;const s=this.parseSdp(t);if(!s)return this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(t)),null;for(const u of o.media)if(u.ssrcs&&u.ssrcs.some((e=>r.includes(parseInt("".concat(e.id)))))){rD.modifyDirectionWhenDelUser(u,s.media.find((e=>e.mid===u.mid))),u.ssrcs.forEach((e=>{e.value="-"}));const e=i.find((e=>"".concat(e.mid)==="".concat(u.mid)));e&&(e.direction=e.currentDirection===EM.SEND_RECV||e.currentDirection===EM.SEND_ONLY?EM.SEND_ONLY:EM.INACTIVE,await n(e.receiver))}const a=WM(o),c=WM(s);return this.logger_.debug(this.module_,"deleteUser success, offer: ".concat(this.printSdpInfo(c)," answer: ").concat(this.printSdpInfo(a))),{offerSdp:c,answerSdp:a}}modifySdpByMid(e,t,r,i,n,o){var s,a;const c=this.parseSdp(e);if(!c)return this.logger_.error(this.module_,"modifySdpByMid failed,the sdp is invalid : ".concat(e)),null;const u=null===(s=c.media)||void 0===s?void 0:s.find((e=>"".concat(e.mid)===r)),d=this.addSSRC(u,i,n,o),l=this.parseSdp(t);l||this.logger_.error(this.module_,"modifySdpByMid failed,the sdp is invalid : ".concat(t));const h=null===(a=l.media)||void 0===a?void 0:a.find((e=>"".concat(e.mid)===r));rD.modifyDirectionWhenAddUser(u,h);const f=WM(c),p=WM(l);return this.logger_.debug(this.module_,"modifySdpByMid success, offer: ".concat(this.printSdpInfo(p)," answer: ").concat(this.printSdpInfo(f))),{offerSdp:p,answerSdp:f,streamId:d}}getAllMidsByType(e,t){var r;const i=this.parseSdp(e),n=[];return i?(null===(r=i.media)||void 0===r||r.forEach((e=>{e.type===t&&n.push("".concat(e.mid))})),n):(this.logger_.error(this.module_,"getAllMidsByType failed,the sdp is invalid : ".concat(e)),n)}getOfferVideoMidBySsrc(e,t,r){var i;const n=this.parseSdp(e);let o=null;return n?(null===(i=n.media)||void 0===i||i.forEach((e=>{e.type===t&&e.ssrcs&&e.ssrcs.length>0&&"".concat(e.ssrcs[0].id)==="".concat(r)&&(o="".concat(e.mid))})),o):(this.logger_.error(this.module_,"getOfferVideoMidBySsrc failed,the sdp is invalid : ".concat(e)),o)}getIdleTransceiverWithSameSsrc(e,t,r){if(!t||0===t.length)return null;const i=this.parseSdp(e);if(!i)return this.logger_.error(this.module_,"getIdleMidWithSameSsrc failed,the sdp is invalid : ".concat(e)),null;const n=i.media.find((e=>!(!e.ssrcs||0===e.ssrcs.length)&&e.ssrcs[0].id===r));let o;for(const s of t)if(n){if("".concat(n.mid)==="".concat(s.mid)){o=t.splice(t.indexOf(s),1)[0];break}}else{const e=i.media.find((e=>"".concat(e.mid)==="".concat(s.mid)));if(!e.ssrcs||0===e.ssrcs.length){o=t.shift();break}}return o}deleteSSRC(e,t,r,i){if(0===r.length&&!i)return e;this.logger_.info(this.module_,"deleteSSRC ".concat(r,", ").concat(i));const n=this.parseSdp(e),o=this.parseSdp(t);if(!n)return void this.logger_.error(this.module_,"deleteSSRC failed");null==r||r.forEach((e=>{n.media.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).forEach((t=>{var r;if(null!==(r=t.ssrcs)&&void 0!==r&&r.find((t=>t.id===e))){var i;const e=null===(i=o.media)||void 0===i?void 0:i.find((e=>"".concat(e.mid)==="".concat(t.mid)));rD.modifyDirectionWhenPublish(t,e,!1),t.ssrcs=void 0}}))})),n.media.filter((e=>e.type===vO.TRACK_TYPE_AUDIO)).forEach((e=>{var t;if(null!==(t=e.ssrcs)&&void 0!==t&&t.find((e=>e.id===i))){var r;const t=null===(r=o.media)||void 0===r?void 0:r.find((t=>"".concat(t.mid)==="".concat(e.mid)));rD.modifyDirectionWhenPublish(e,t,!1),e.ssrcs=void 0}}));const s=WM(n),a=WM(o);return this.logger_.debug(this.module_,"deleteSSRC ".concat(r," success, offer: ").concat(this.printSdpInfo(s)," answer: ").concat(this.printSdpInfo(a))),{offerSdp:s,answerSdp:a}}modifyPublishOfferSdp(e,t,r,i,n){this.logger_.debug(this.module_,"modifyPublishOfferSdp start, sdp: ".concat(this.printSdpInfo(e)));const o=this.parseSdp(e),s=this.parseSdp(t);if(!o)return void this.logger_.error(this.module_,"modifyPublishOfferSdp failed, the sdp is invalid: ".concat(e));if(this.deleteUnexpectedMedia(o),i&&i.length>0){let e=this.getAvailableSenderMedia(o,vO.TRACK_TYPE_VIDEO);null==i||i.forEach((t=>{var i;let n=e.find((e=>{var r;return null===(r=e.ssrcs)||void 0===r?void 0:r.find((e=>"".concat(e.id)==="".concat(t)))}));n?e=e.filter((e=>{var r;return!e.ssrcs||(null===(r=e.ssrcs)||void 0===r?void 0:r.find((e=>"".concat(e.id)!=="".concat(t))))})):n=e.shift(),this.transformVideoPayload(n),this.deleteRetransmissionSsrc(n),this.modifyUnifiedMediaSsrc(n,t,r);const o=null===(i=s.media)||void 0===i?void 0:i.find((e=>"".concat(e.mid)==="".concat(n.mid)));rD.modifyDirectionWhenPublish(n,o,!0)}))}o.media.filter((e=>{let{type:t,direction:r}=e;return t===vO.TRACK_TYPE_VIDEO&&r!==EM.SEND_ONLY&&r!==EM.SEND_RECV})).forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e),e.ssrcs=void 0}));const a=this.getAvailableSenderMedia(o,vO.TRACK_TYPE_AUDIO);if(a&&a.length>0){const e=a[0];if(this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e),n){var c;const t=null===(c=s.media)||void 0===c?void 0:c.find((t=>"".concat(t.mid)==="".concat(e.mid)));this.modifyUnifiedMediaSsrc(e,n,r),rD.modifyDirectionWhenPublish(e,t,!0)}}const u=WM(o),d=WM(s);return this.logger_.debug(this.module_,"modifyPublishOfferSdp success, offerSdp: ".concat(this.printSdpInfo(u),", answerSdp: ").concat(this.printSdpInfo(d))),{offerSdp:u,answerSdp:d}}static modifyDirectionWhenPublish(e,t,r){r?e.direction===EM.RECV_ONLY?e.direction=EM.SEND_RECV:e.direction===EM.INACTIVE&&(e.direction=EM.SEND_ONLY):e.direction===EM.SEND_ONLY?e.direction=EM.INACTIVE:e.direction===EM.SEND_RECV&&(e.direction=EM.RECV_ONLY),r?t.direction===EM.SEND_ONLY?t.direction=EM.SEND_RECV:t.direction===EM.INACTIVE&&(t.direction=EM.RECV_ONLY):t.direction===EM.SEND_RECV?t.direction=EM.SEND_ONLY:t.direction===EM.RECV_ONLY&&(t.direction=EM.INACTIVE)}generateMatchedAnswerWithOffer(e,t,r){this.logger_.debug(this.module_,"generateCorrespondingRemoteSdpMedia start, sdp: ".concat(this.printSdpInfo(e)));const i=this.parseSdp(e);this.portType_!==NC.portNormal&&rD.modifyBundle(i,t);const n=this.getMedias(i,r);if(!n||0===n.length)return e;const o=JSON.parse(JSON.stringify(n[0]));o.mid=t,delete o.ssrcs,delete o.candidates,o.direction=EM.INACTIVE,i.media.push(o);const s=WM(i);return this.logger_.debug(this.module_,"generateCorrespondingRemoteSdpMedia success, sdp: ".concat(this.printSdpInfo(s))),s}getBrowserDefaultSsrc(e){const t=this.parseSdp(e),r=this.getMedias(t,vO.TRACK_TYPE_VIDEO),i=this.getMedias(t,vO.TRACK_TYPE_AUDIO),n=[];let o;if(r&&r.length>0&&r.forEach((e=>{e.ssrcs&&e.ssrcs.length>0&&n.push(parseInt(e.ssrcs[0].id.toString()))})),i&&i.length>0)for(const s of i)if(s.ssrcs&&s.ssrcs.length>0){o=parseInt(s.ssrcs[0].id.toString());break}return{videoSsrcs:n,audioSsrc:o}}getLeastMid(e){const t=this.parseSdp(e);if(!t)return void this.logger_.error(this.module_,"getLeastMid failed, the sdp is invalid : ".concat(e));let r;for(const i of t.groups||[])if("BUNDLE"===i.type){const e=(i.mids||"").split(" ");r=e[e.length-1];break}return r}}const iD="PeerConnectionsManager";class nD extends $P{constructor(e,t,r){super({logger:e,stat:t,emitter:r}),i(this,"isFireFox",Mw.isFirefox()),this.peerConnections=new Map,Mw.isOnlySupportUnfiedPlan()?(this.sdpDescMode="unified-plan",this.rtcSdp=new rD(this.logger)):(this.sdpDescMode="plan-b",this.rtcSdp=new tD(this.logger)),this.logger.debug(iD,"ConnectionsManager, SDP mode: ".concat(this.sdpDescMode)),this.setPortType(NC.portReduce),this.mainReceiverPreStatisticMap=new Map,this.auxReceiverPreStatisticMap=new Map}setPortType(e){const t=SO.getParameter(fO)||0;0!==t&&(e=t),e===NC.portNormal&&Mw.isOnlySupportUnfiedPlan()&&(e=NC.portReduce),this.portType=e,this.portType===NC.portNormal&&(this.sdpDescMode="plan-b",this.rtcSdp=new tD(this.logger)),this.logger.debug(iD,"ConnectionsManager, portType: ".concat(1===this.portType?"normal":"reduce")),this.rtcSdp.setPortType(this.portType)}getPortType(){return this.portType}setTurnServer(e){this.turnServerConfig=e}isConnectionsExist(){return this.peerConnections.size>0}getConnectionId(){return this.uniqueId}getReceivers(e){var t;const r=null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection;if("plan-b"===this.sdpDescMode)return null==r?void 0:r.getReceivers();const i=[],n=null==r?void 0:r.getTransceivers();if(!n)return null;for(const o of n)o.currentDirection!==EM.SEND_RECV&&o.currentDirection!==EM.RECV_ONLY||i.push(o.receiver);return i}getSenders(e){var t;const r=null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection;if("plan-b"===this.sdpDescMode)return null==r?void 0:r.getSenders();const i=[],n=null==r?void 0:r.getTransceivers();if(!n)return null;for(const o of n)o.currentDirection!==EM.SEND_RECV&&o.currentDirection!==EM.SEND_ONLY||i.push(o.sender);return i}calcChangedStatistic(e,t,r){if(this.mainReceiverPreStatisticMap.has(e)||this.auxReceiverPreStatisticMap.has(e)){const i=this.mainReceiverPreStatisticMap.get(e)||this.auxReceiverPreStatisticMap.get(e);if("number"==typeof t)return Object.prototype.hasOwnProperty.call(i,r[0])?t>=i[r[0]]?t-i[r[0]]:(this.clearReveiverPreStatisticBySsrcLabel(e),t):t;this.doCalcChangedStatisticObject(e,t,i,r)}else if("number"==typeof t)return t}doCalcChangedStatisticObject(e,t,r,i){if(i&&i.length>0){let n=0;for(const e of i)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]>=r[e]?t[e]=t[e]-r[e]:n++);n>=i.length-1&&this.clearReveiverPreStatisticBySsrcLabel(e)}else{let i=0;for(const e in t)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]>=r[e]?t[e]=t[e]-r[e]:i++);i===Object.keys(t).length&&this.clearReveiverPreStatisticBySsrcLabel(e)}}clearReveiverPreStatisticBySsrcLabel(e){this.mainReceiverPreStatisticMap.delete(e)||this.auxReceiverPreStatisticMap.delete(e)}async initConnectionAndSdp(e,t,r,i){this.uniqueId=e;const n=this.createPeerConnection(t),o="main"!==t;let s=await this.createOffer(t,{offerToReceiveAudio:!o,offerToReceiveVideo:!0});if(this.isFireFox){t===yO.STREAM_TYPE_MAIN&&(await n.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(s.sdp)}),n.connection.addTransceiver("video",{direction:EM.INACTIVE}),s=await n.connection.createOffer());const e=this.rtcSdp.getBrowserDefaultSsrc(s.sdp);n.videoSendSsrcs=e.videoSsrcs,n.sendSsrcsMapping=new Map,e.videoSsrcs.forEach(((e,t)=>{n.sendSsrcsMapping.set(t,e)})),!o&&e.audioSsrc&&(n.audioSendSsrc=e.audioSsrc,n.sendSsrcsMapping.set(2,e.audioSsrc))}const a=this.rtcSdp.transformOfferSdp(s.sdp);if(await n.connection.setLocalDescription({type:"offer",sdp:a}),await this.iceAddressCollect(n.connection),!this.isFireFox){const e=n.connection.localDescription.sdp;this.logger.debug(iD,"setLocalDescription, ".concat(t,"sdp offer: ").concat(this.rtcSdp.printSdpInfo(e))),await n.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(e)})}o?this.onConnection(n,r.onTrackHandler,!0):this.rtcSdp.containsValidVideoPayload(s.sdp)||i?this.onConnection(n,r.onTrackHandler,!1):(this.destroyPeerConnection(t),this.logger.error(iD,"initConnectionAndSdp, no H264 payload and try createOffer again"),await this.initConnectionAndSdp(e,t,r,!0))}setSsrcsMapping(e){const t=this.peerConnections.get(yO.STREAM_TYPE_MAIN);t.sendSsrcsMapping&&t.sendSsrcsMapping.size>0&&(t.sendSsrcsMapping.has(0)&&(t.sendSsrcsMapping.set(e.video.sendSsrcBegin,t.sendSsrcsMapping.get(0)),t.sendSsrcsMapping.delete(0)),t.sendSsrcsMapping.has(1)&&(t.sendSsrcsMapping.set(e.video.sendSsrcEnd,t.sendSsrcsMapping.get(1)),t.sendSsrcsMapping.delete(1)),t.sendSsrcsMapping.has(2)&&(t.sendSsrcsMapping.set(e.audio.sendSsrcBegin,t.sendSsrcsMapping.get(2)),t.sendSsrcsMapping.delete(2)));const r=this.peerConnections.get(yO.STREAM_TYPE_AUX);r.sendSsrcsMapping&&r.sendSsrcsMapping.size>0&&r.sendSsrcsMapping.has(0)&&(r.sendSsrcsMapping.set(e.desktopVideo.sendSsrcBegin,r.sendSsrcsMapping.get(0)),r.sendSsrcsMapping.delete(0))}getMappingSsrcs(e,t){if(!e)return;let r;return t||"number"!=typeof e?(r=this.peerConnections.get(t),!r.sendSsrcsMapping||r.sendSsrcsMapping.size<1?e:"number"==typeof e?r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):e:e.map((e=>r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):e))):(r=this.peerConnections.get(yO.STREAM_TYPE_MAIN),r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):(r=this.peerConnections.get(yO.STREAM_TYPE_AUX),r.sendSsrcsMapping.get(e)||e))}async createOffer(e,t){const r=this.peerConnections.get(e).connection,i=await r.createOffer(t);return"plan-b"!==this.sdpDescMode&&r.getTransceivers().forEach((e=>{e.direction=EM.INACTIVE})),i}iceCandidateListener(e,t){this.logger.info(iD,"iceCandidateListener of ".concat(t)),e.connection.onicecandidate=r=>{var i;r.candidate&&"udp"===r.candidate.protocol&&(this.logger.info(iD,"".concat(t," onicecandidate: ").concat(XR.shieldIpAddress(null===(i=r.candidate)||void 0===i?void 0:i.candidate))),e.candidate||(e.candidate=[]),e.candidate.push(r.candidate))}}iceRestart(e,t,r){if(this.stat.setConnectionStatusInfo(QC.CLOSED,XC.MEDIA),e.connectFailedTimes++,this.logger.error(iD,"".concat(t?"aux":"main"," connection statechange, connectFailedTimes: ").concat(e.connectFailedTimes,".")),e.connectFailedTimes<=30&&(this.logger.error(iD,"".concat(t?"aux":"main"," connection statechange, emit media error event.")),e.connectFailedTimes%2==0&&this.eventEmitter.emit(UC.Error,{errCode:Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR,errDesc:"".concat(t?"aux":"main"," peerConnection: ").concat(Jc[Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR])}),30===e.connectFailedTimes))return this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:t?"aux":"main",state:LC.DisConnected}),void(e.connectFailedTimes=0);e.connection.createOffer({iceRestart:!0}).then((r=>{this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:t?"aux":"main",state:LC.Reconnecting}),e.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r.sdp)}),e.connection.setRemoteDescription({sdp:e.connection.remoteDescription.sdp,type:"answer"})})).finally((()=>{r&&r()}))}onConnection(e,t,r){e.connection.ontrack=e=>{t(e,r)},e.connection.onconnectionstatechange=()=>{if(this.logger.info(iD,"onconnectionstatechange, ".concat(r?"aux":"main"," connect state is: ").concat(e.connection.connectionState," ;iceConnectionState: ").concat(e.connection.iceConnectionState)),"disconnected"!==e.connection.iceConnectionState)clearTimeout(e.disConnectDelayHandleTimer),e.disConnectDelayHandleTimer=null,"failed"===e.connection.iceConnectionState||"closed"===e.connection.iceConnectionState?(this.logger.info(iD,"connect state failed go iceRestart: ".concat(e.connection.iceConnectionState)),this.iceRestart(e,r)):"connected"===e.connection.iceConnectionState&&(this.logger.info(iD,"connect state connect: ".concat(e.connection.iceConnectionState)),this.stat.setConnectionStatusInfo(QC.CONNECTED,XC.MEDIA),e.connectFailedTimes=0,this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:r?"aux":"main",state:LC.Connected}),e.connection.getStats().then((e=>{let t=null;e.forEach((e=>{"candidate-pair"===e.type&&(this.isFireFox&&e.selected||e.nominated)&&(t=e.localCandidateId)})),t&&e.forEach((e=>{e.id===t&&(this.logger.info(iD,"transport protocol changed, candidateType: ".concat(e.candidateType,", protocol: ").concat(e.protocol)),this.eventEmitter.emit(UC.TransportProtocolChanged,{protocol:e.protocol,candidateType:e.candidateType}))}))})));else{if(e.disConnectDelayHandleTimer)return;e.disConnectDelayHandleTimer=setTimeout((()=>{this.logger.info(iD,"disConnect state delay handler, go iceRestart: ".concat(e.connection.iceConnectionState)),this.iceRestart(e,r,(()=>{clearTimeout(e.disConnectDelayHandleTimer),e.disConnectDelayHandleTimer=null}))}),5e3)}}}async iceAddressCollect(e){await new Promise((t=>{let r=null;const i=()=>{this.logger.info(iD,"ICE collect Gathering State change: ".concat(e.iceGatheringState)),"complete"===e.iceGatheringState&&(clearTimeout(r),this.logger.info(iD,"ICE collect complete"),e.removeEventListener("icegatheringstatechange",i),t())};e.addEventListener("icegatheringstatechange",i),r=setTimeout((()=>{this.logger.error(iD,"ICE collect timeout"),clearTimeout(r),t()}),6e3)}))}createPeerConnection(e){const t={rtcpMuxPolicy:this.portType===NC.portReduce?"require":"negotiate",bundlePolicy:this.portType===NC.portReduce?"max-bundle":"balanced"},r=[];if(this.turnServerConfig){for(const e of this.turnServerConfig.turnServers)r.push("turn:".concat(e,":").concat(this.turnServerConfig.udpPort||3478,"?transport=udp"));t.iceServers=[{urls:r,username:this.turnServerConfig.userName,credential:this.turnServerConfig.credential}],t.iceTransportPolicy="relay"}t.sdpSemantics=this.sdpDescMode;const i=new RTCPeerConnection(t);var n;this.peerConnections.has(e)&&(null===(n=this.peerConnections.get(e).connection)||void 0===n||n.close());const o={connection:i,connectFailedTimes:0};return this.peerConnections.set(e,o),this.iceCandidateListener(o,e),o}destroyPeerConnection(e,t){const r=this.peerConnections.get(e);r&&(clearTimeout(r.disConnectDelayHandleTimer),r.connectFailedTimes=0,"closed"!==r.connection.signalingState&&(null==t||t.forEach((e=>r.connection.removeTrack(e))),r.connection.close()),"main"===e?this.mainReceiverPreStatisticMap.clear():this.auxReceiverPreStatisticMap.clear(),this.peerConnections.delete(e))}async modifySdpInfo(e,t){const r=this.peerConnections.get(e);let i=null;if(r)if("main"===e){const e=await this.getDataChannelTemplate(t);i=this.rtcSdp.modifyMainSdpInfo(r.connection.localDescription.sdp,r.candidate,r.videoSendSsrcs,r.audioSendSsrc,t,e)}else i=this.rtcSdp.modifyAuxSdpInfo(r.connection.localDescription.sdp,r.candidate,r.videoSendSsrcs);return i}async getDataChannelTemplate(e){let t=null;if(!e)return t;let r=null;try{r=new RTCPeerConnection,r.createDataChannel("dataChannelTemplate"),t=(await r.createOffer()).sdp}catch(jN){this.logger.error(iD,"getDataChannelTemplate failed, unsupport datachannel: ".concat(jN))}finally{r&&r.close()}return t}async setLocalDescriptionShim(e,t){let r;!this.isFireFox&&t||(r=(await e.createOffer()).sdp),await e.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r||t)})}async handleAnswerSdpFromServer(e,t,r){const i=this.peerConnections.get(e).connection,{remoteDescription:n,bindCryptoKey:o,wsUrl:s,dataChannelEnable:a}=this.rtcSdp.transformAnswerSdp(t,i.localDescription.sdp);let c;this.logger.debug(iD,"handleAnswerSdpFromServer, ".concat(e," sdp answer: ").concat(this.rtcSdp.printSdpInfo(n))),c=r?await r({remoteDescription:n,bindCryptoKey:o,wsUrl:s,dataChannelEnable:a}):{answerSdp:n},c.offerSdp&&c.offerSdp!==i.localDescription.sdp&&await this.setLocalDescriptionShim(i,c.offerSdp);try{await i.setRemoteDescription({type:"answer",sdp:c.answerSdp})}catch(jN){throw this.logger.error(iD,"setRemoteDescription error, answer sdp invalid or offer sdp invalid"),new qc(Gc.RTC_ERR_CODE_ANSWER_SDP_INVALID,(null==jN?void 0:jN.message)||"setRemoteDescription error, answer sdp invalid or offer sdp invalid")}}getSfuInfoFromSdp(e,t){return this.rtcSdp.getSfuInfo(e,t)}async generateAndSetOfferSdpByHandler(e,t){const r=this.peerConnections.get(e).connection;let i;i=t?await t(r.localDescription.sdp):r.localDescription.sdp,await this.setLocalDescriptionShim(r,i)}async generateAndSetAnswerSdpByHandler(e,t){const r=this.peerConnections.get(e).connection;let i;i=t?(await t(r.remoteDescription.sdp)).answerSdp:r.remoteDescription.sdp,await r.setRemoteDescription({type:"answer",sdp:i})}async deleteUser(e,t,r){const i=this.peerConnections.get(e).connection,n=i.remoteDescription.sdp;let o={offerSdp:i.localDescription.sdp,answerSdp:n};if("plan-b"===this.sdpDescMode)o.answerSdp=this.rtcSdp.deleteUser(o.answerSdp,t,r);else{const n=i.getTransceivers();t&&t.length>0&&(o=await this.rtcSdp.deleteUser(o.answerSdp,o.offerSdp,t,n,(t=>this.recordCurrentReceiverStatistic(e,t)))),r&&r.length>0&&(o=await this.rtcSdp.deleteUser(o.answerSdp,o.offerSdp,r,n,(t=>this.recordCurrentReceiverStatistic(e,t))))}await this.setLocalDescriptionShim(i,o.offerSdp),await i.setRemoteDescription({type:"answer",sdp:o.answerSdp})}async recordCurrentReceiverStatistic(e,t){const r=await t.getStats();r&&r.forEach(((t,r)=>{(this.isFireFox||/RTCInboundRTP(Video|Audio)Stream_.*/gi.test(r))&&this["main"===e?"mainReceiverPreStatisticMap":"auxReceiverPreStatisticMap"].set(r,t)}))}getAllIdleReceiverTransceivers(e,t,r){const i=e.getTransceivers(),n=this.rtcSdp.getAllMidsByType(r,t);return i.filter((e=>n.includes("".concat(e.mid))&&e.currentDirection!==EM.SEND_RECV&&e.currentDirection!==EM.RECV_ONLY))}getIdleSendTransceiver(e,t,r,i){const n=e.getTransceivers();if(this.isFireFox&&i){const e=this.rtcSdp.getOfferVideoMidBySsrc(r,t,this.getMappingSsrcs(i));return null==n?void 0:n.find((t=>t.mid===e))}const o=this.rtcSdp.getAllMidsByType(r,t);return null==n?void 0:n.find((e=>o.includes("".concat(e.mid))&&e.currentDirection!==EM.SEND_ONLY&&e.currentDirection!==EM.SEND_RECV))}async addTrack(e,t,r,i){const n=this.peerConnections.get(e).connection;if("plan-b"===this.sdpDescMode)return n.addTrack(t,r);const o=n.localDescription.sdp;let s=this.getIdleSendTransceiver(n,"audio"===t.kind?vO.TRACK_TYPE_AUDIO:vO.TRACK_TYPE_VIDEO,o,i);if(s){await s.sender.replaceTrack(t),s.direction=s.currentDirection===EM.RECV_ONLY?EM.SEND_RECV:EM.SEND_ONLY;const e=this.rtcSdp.modifyAnswerDirection(n.remoteDescription.sdp,s.mid);await this.setLocalDescriptionShim(n),await n.setRemoteDescription({type:"answer",sdp:e})}else this.logger.info(iD,"addTrack, no available sender, addTranscevier"),s=await this.addTransceiver(n,"audio"===t.kind?vO.TRACK_TYPE_AUDIO:vO.TRACK_TYPE_VIDEO),await s.sender.replaceTrack(t),s.direction=s.currentDirection===EM.RECV_ONLY?EM.SEND_RECV:EM.SEND_ONLY;return s.sender}removeTrack(e,t){const r=this.peerConnections.get(e).connection;"closed"!==r.signalingState&&r.removeTrack(t)}async modifyPublishOfferSdp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;const s=this.peerConnections.get(e).connection;let a,c,u=(await s.createOffer()).sdp;return(n&&n.length>0||o)&&("plan-b"===this.sdpDescMode?u=this.rtcSdp.deleteSSRC(u,n,o):a=this.rtcSdp.deleteSSRC(u,s.remoteDescription.sdp,this.getMappingSsrcs(n,e),this.getMappingSsrcs(o,e))),"plan-b"===this.sdpDescMode?u=this.rtcSdp.modifyPublishOfferSdp(u,r,i):a=this.rtcSdp.modifyPublishOfferSdp(a?a.offerSdp:u,a?a.answerSdp:s.remoteDescription.sdp,t,this.getMappingSsrcs(r,e),this.getMappingSsrcs(i,e)),"plan-b"===this.sdpDescMode?(await s.setLocalDescription({type:"offer",sdp:u}),await s.setRemoteDescription(s.remoteDescription),c=u):(await this.setLocalDescriptionShim(s,a.offerSdp),await s.setRemoteDescription({type:"answer",sdp:a.answerSdp}),c=a.offerSdp),c}async addTopAudioUserBatch(e,t,r,i){const n=this.peerConnections.get("main").connection;let o,s={offerSdp:n.localDescription.sdp,answerSdp:e};"plan-b"!==this.sdpDescMode&&(o=this.getAllIdleReceiverTransceivers(n,vO.TRACK_TYPE_AUDIO,s.answerSdp));for(let a=0;a{clearTimeout(e),t.receiver.track.enabled=!0}),300)}}else t=await this.addTransceiver(r,vO.TRACK_TYPE_VIDEO,a);t.direction=t.currentDirection===EM.SEND_ONLY?EM.SEND_RECV:EM.RECV_ONLY,a=this.rtcSdp.modifySdpByMid(a.answerSdp,a.offerSdp,t.mid,c,e.streamId,e.videoSsrc)}await this.setLocalDescriptionShim(r,a.offerSdp),await r.setRemoteDescription({type:"answer",sdp:a.answerSdp})}}async addTransceiver(e,t,r){var i;e.addTransceiver(t,{direction:EM.INACTIVE});const n=await e.createOffer();await this.setLocalDescriptionShim(e,n.sdp);const o=this.rtcSdp.getLeastMid(n.sdp),s=this.rtcSdp.generateMatchedAnswerWithOffer((null==r?void 0:r.answerSdp)||e.remoteDescription.sdp,o,t);return r&&(r.offerSdp=n.sdp,r.answerSdp=s),await e.setRemoteDescription({type:"answer",sdp:s}),null===(i=e.getTransceivers())||void 0===i?void 0:i.find((e=>"".concat(e.mid)===o))}getConnection(e){var t;return this.isConnectionsExist()&&this.peerConnections.get(e)?null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection:null}getConnectionRTT(){let e=0;if(!this.isConnectionsExist())return e;const t=OO.getLatestReport(this.uniqueId,yO.STREAM_TYPE_MAIN);if(t){const r=t.get("candidate-pair");e=r&&r.currentRoundTripTime||0}return e}getICETransportStat(e){if(!e)throw this.logger.error(iD,"getICETransportStat, pcType is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"pcType is null");const t=OO.getLatestReport(this.uniqueId,e);if(!t)return null;try{const e=t.get("candidate-pair");return{currentRoundTripTime:e.currentRoundTripTime||0,availableOutgoingBitrate:e.availableOutgoingBitrate||0,bytesSent:e.bytesSent||0,bytesReceived:e.bytesReceived||0}}catch(jN){return this.logger.error(iD,"getICETransportStat failed",jN),null}}getInfo(){return{moduleName:"PeerConnectionsManager"}}async refreshOffer(e){const t=this.peerConnections.get(e).connection,r=await t.createOffer();return await t.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r.sdp)}),r}}var oD={exports:{}};!function(e,t){self,e.exports=function(){var e={d:function(t,r){for(var i in r)e.o(r,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{GrsBaseInfo:function(){return O},GrsClient:function(){return M},GrsErrorCode:function(){return s},Logger:function(){return l}});var r=function(e){return"string"!=typeof e||""==e},i=function(e){return void 0===e||null==e||"{}"==JSON.stringify(e)},n=function(e){return!(void 0!==e&&e instanceof Array&&"[]"!=JSON.stringify(e))},o=function(e){if("string"!=typeof e||""==e)return{};try{var t=JSON.parse(e);return void 0===t||null==t?{}:t}catch(e){return{}}},s={ERR_OK:0,ERR_INTERNAL_ERROR:1,ERR_INVALID_PARAM:2,ERR_INIT:3,GRS_SET_ROUTER_DIR:4,GRS_SET_SYSTEM_INFO:5,GRS_SERVICE_CONFIGURE_NO_FILE:6,GRS_SERVICE_CONFIGURE_READ_ERROR:7,GRS_SET_CA_FILE:8,GRS_SERVICE_CONFIGURE_PARSE_ERROR:9,GRS_SERVICE_CONFIGURE_PARSE_VALUE_ERROR:10,GRS_ROUTER_CONFIGURE_EMPTY:11,GRS_ROUTER_APP_CONFIGURE_READ_ERROR:12,GRS_ROUTER_SDK_CONFIGURE_READ_ERROR:13,GRS_ROUTER_CONFIGURE_PARSE_VALUE_ERROR:14,GRS_ROUTER_SERVER_NAME_EMPTY:15,GRS_ROUTER_BY_EMPTY:16,GRS_APK_ROUTER_NO_APPLICATION:17,GRS_NOT_FIND:18,GRS_NOT_FIND_APPLICATION:19,GRS_NOT_FIND_SERVICE_LIST:20,GRS_NOT_FIND_SERVING_COUNTRY_GROUP:21,GRS_NOT_FIND_SERVICE:22,GRS_NOT_FIND_ADDRESS:23,GRS_NOT_FIND_COUNTRY:24};function a(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r");for(var c in a){if("ser_country"===a[c]&&!r(t)){s=t;break}if("reg_country"===a[c]&&!r(i)){s=i;break}if("issue_country"===a[c]&&!r(n)){s=n;break}if("geo_ip"===a[c]&&!r(o)){s=o;break}}return s},p=function(e,t){var r="";for(var i in e)if(e[i].countriesOrAreas.includes(t)){r=e[i].id;break}return r},m=function(e,t){var r={};if(i(e))return r;var n=e.errorList;if(!i(n)&&t in n)return r.results=n[t],r.status="failure",r;var o=e.services;return!i(o)&&t in o?(r.results=o[t],r.status="success",r):(r.results="GRS_NOT_FIND_SERVICE",r.status="notFindService",r)},g=function(e,t,r,i){var n="",o=m(e,r);if("success"===o.status&&i in o.results)return l.i("getGrsUrl","Return The Server Cached Data"),o.results[i];l.i("getGrsUrl","Cannot find "+r+"("+i+") in serverUrlInfo: ",JSON.stringify(e));var s=m(t,r);return"success"===s.status&&i in s.results?(l.i("getGrsUrl","Return The Local JSON Data"),n=s.results[i]):l.i("getGrsUrl","Cannot find "+r+"("+i+") in localUrlInfo: ",JSON.stringify(t)),n},_=function(e,t,r){var i={},n=m(e,r);if("success"===n.status)return l.i("getGrsUrl","Return The Server Cached Data"),n.results;l.i("getGrsUrl","Cannot find "+r+" in serverUrlInfo: ",JSON.stringify(e));var o=m(t,r);return"success"===o.status?i=o.results:l.i("getGrsUrl","Cannot find "+r+" in localUrlInfo: ",JSON.stringify(t)),i};function S(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function v(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,i=new Array(t);r=(new Date).getTime())return l.i("getGrsDataFromServerOrCache","During The Suppression Or The Cache Not Expired"),void t(a);c=r(a.header.ETag)?"&":a.header.ETag,b(t,e,a,s,c)}))},b=function(e,t,n,o,s){C(t,s).then((function(t){if(l.d("getGrsDataFromServerOrCache","handleGrsDataFromServer: ",t),t.success){if(200===t.statusCode)return localStorage.setItem(o,JSON.stringify(t)),void e(t);if(304===t.statusCode)return n["cache-time"]=(new Date).getTime(),n.header=t.header,localStorage.setItem(o,JSON.stringify(n)),void e(n);if(503===t.statusCode)return void function(e,t,n,o){i(e)||r(e)?(t.header["cache-control"]="private,max-age="+t.header["Retry-After"],localStorage.setItem(n,JSON.stringify(t)),o(t)):(e["cache-time"]=(new Date).getTime(),e.header["cache-control"]="private,max-age="+t.header["Retry-After"],localStorage.setItem(n,JSON.stringify(e)),o(e))}(n,t,o,e);i(n)||r(n)?(t.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(t)),e(t)):(n["cache-time"]=(new Date).getTime(),n.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(n)),e(n))}})).catch((function(t){l.i("getGrsDataFromServerOrCache","handleGrsDataFromServer catch: ",t),i(n)||r(n)?(localStorage.setItem(o,JSON.stringify(t)),e(t)):(n["cache-time"]=(new Date).getTime(),n.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(n)),e(n))}))},C=function(e,t){var r=e.getServerConfig().grs_server.grs_query_timeout,i=e.getServerConfig().grs_server.grs_base_url,n=e.getServerConfig().grs_server.grs_query_endpoint,o=[];for(var s in i)o.push(i[s]+n+"?"+e.getGrsReqParamJoint());return function(e,t,r,i){l.i("post","urls: ",e);var n=[];return e.forEach((function(e){n.push(R(e,t,r,1e3*i))})),Promise.race(n)}(o,e._servicList,{"Content-Type":"application/json;charset=UTF-8","User-Agent":e.getUserAgent(),"If-None-Match":t},r)};function A(e){return function(e){if(Array.isArray(e))return w(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return w(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?w(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r0?t.match(/msie [\d.]+;/gi):t.indexOf("firefox")>0?t.match(/firefox\/[\d.]+/gi):t.indexOf("chrome")>0?t.match(/chrome\/[\d.]+/gi):t.indexOf("safari")>0&&t.indexOf("chrome")<0?t.match(/safari\/[\d.]+/gi):void 0)[0].replace("/","; ")}catch(t){e="unknown; web-browser"}return this.packageName+"/"+this.versionName+" ("+e+"; NA) network-grs-web/5.0.9.300 "+this.serviceName}}])&&k(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function P(e,t){for(var r=0;r{r.userState===bO.Joined&&(r.mainStream&&r.mainStream.remoteTrackInfos&&r.mainStream.remoteTrackInfos.forEach((r=>{r.cssrc===e&&(t=r.mute)})),r.auxStream&&r.auxStream.remoteTrackInfos&&r.auxStream.remoteTrackInfos.forEach((r=>{r.cssrc===e&&(t=r.mute)})))})),t}checkRemoteTop3NeedReport(){let e=0;return this.remoteUserInfos.forEach((t=>{t.userState===bO.Joined&&t.mainStream&&t.mainStream.remoteTrackInfos&&t.mainStream.remoteTrackInfos.forEach((t=>{t.type===vO.TRACK_TYPE_AUDIO&&e++}))})),!(e<3)}initialize(e,t){e&&t&&(this.localUserId=e,this.audioCssrcs=this.getCssrcRangeByType(t,_D.audio),this.mainVideoCssrcs=this.getCssrcRangeByType(t,_D.mainVideo),this.auxVideoCssrcs=this.getCssrcRangeByType(t,_D.auxVideo))}getStreamInfoByPStreamUid(e){let t=null;return Array.from(this.remoteUserInfos.values()).forEach((r=>{var i,n,o;if(null!==(i=r.mainStream)&&void 0!==i&&i.remoteTrackInfos.get(e.toString()))t=null===(o=r.mainStream)||void 0===o?void 0:o.remoteTrackInfos.get(e.toString());else if(null!==(n=r.auxStream)&&void 0!==n&&n.remoteTrackInfos.get(e.toString())){var s;t=null===(s=r.auxStream)||void 0===s?void 0:s.remoteTrackInfos.get(e.toString())}})),t}getCssrcRangeByType(e,t){if(!e)throw this.logger.error(SD,"sdpRepInfo is null"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);const r=t===_D.audio?e.audio:t===_D.mainVideo?e.video:e.desktopVideo,i=null==r?void 0:r.receiveSsrcBegin,n=null==r?void 0:r.receiveSsrcEnd;if(!i||!n||i>=n)throw this.logger.error(SD,"begin or end is invalid"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);return vD.getCssrcRange(i,n)}static getCssrcRange(e,t){const r=[];let i;for(i=e;i<=t;i++)r.push(i);return r}refreshRemoteUserList(e,t,r){const i=[],n=this.getUserStreamUpdatedList(e,t);return n?(n.addedUsers.forEach((t=>{const n=this.addUser(t,e,r);n&&i.push(n)})),n.updatedUsers.forEach((t=>{const n=this.updateUser(t,e,r);n&&i.push(n)})),n.removedUsers.forEach((t=>{const n=this.removeUser(t,e,r);n&&i.push(n)})),this.logger.info(SD,"refreshRemoteUserStreamList success, ".concat(this.getTracksUpdateInfosString(i))),i):null}addUser(e,t,r){return this.updateUser(e,t,r)}updateUser(e,t,r){var i,n,o;if(e.userId===this.localUserId)return null;const s={userId:e.userId,userUid:e.userUid,nickname:e.appData.nickname,roomId:t,relaySrcRoomId:null===(i=e.relayUserSrcInfo)||void 0===i?void 0:i.roomId},a=null===(n=e.videoStreams)||void 0===n?void 0:n.filter((e=>e.content!==CC.desktop)),c=null===(o=e.videoStreams)||void 0===o?void 0:o.filter((e=>e.content===CC.desktop)),u=e.audioStreams,d=this.getUserInfoById(s.userId,s.roomId),l=this.doRefreshRemoteStreamList(s,yO.STREAM_TYPE_MAIN,a,u,r),h=this.doRefreshRemoteStreamList(s,yO.STREAM_TYPE_AUX,c,null,r),f=this.getUserInfoById(s.userId,s.roomId);return{userInfo:f.userInfo,preUserState:d?f.userState:bO.NotJoin,curUserState:f.userState,isUserNameChanged:null,mainStream:l,auxStream:h}}removeUser(e,t,r){if(e.userId===this.localUserId)return null;const i={userId:e.userId,userUid:e.userUid,nickname:e.appData.nickname,roomId:t};this.doRefreshRemoteStreamList(i,yO.STREAM_TYPE_MAIN,[],[],r),this.doRefreshRemoteStreamList(i,yO.STREAM_TYPE_AUX,[],[],r);const n={status:pD.exitRoom,userId:e.userId,userUid:e.userUid},o=this.updateUserListInfo(t,[n]);return o&&0!==o.length?o[0]:null}getUserStreamUpdatedList(e,t){const r=this.getAllUserInfos(e),i=[],n=[],o=[];return r.forEach((e=>{if(e.userInfo.userId===wC)return;const r=t.find((t=>t.userId===e.userInfo.userId)),i=this.getAllTracksByMediaType(e.userInfo.roomId,e.userInfo.userId,vO.TRACK_TYPE_VIDEO),s=this.getAllTracksByMediaType(e.userInfo.roomId,e.userInfo.userId,vO.TRACK_TYPE_AUDIO);if(r){r.audioStreams&&(r.audioStreams=r.audioStreams.filter((e=>"main"===e.content)));const e={userId:r.userId,userUid:r.userUid,appData:r.appData,videoStreams:r.videoStreams,audioStreams:r.audioStreams,relayUserSrcInfo:r.relayUserSrcInfo};n.push(e)}else{const t=i.map((e=>({content:e.content,codec:e.codec,fps:e.fps,height:e.height,maxFs:e.maxFs,maxMbps:e.maxMbps,mute:e.mute,pt:e.pt,ssrc:e.pssrc,streamData:e.streamData,streamUid:parseInt(e.trackId),width:e.width}))),r=s.map((e=>({content:e.content,codec:e.codec,maxMbps:e.maxMbps,mute:e.mute,pt:e.pt,ssrc:e.pssrc,streamData:e.streamData,streamUid:parseInt(e.trackId),channels:e.channels,sampleRate:e.sampleRate}))),n={userId:e.userInfo.userId,userUid:e.userInfo.userUid,appData:{nickname:e.userInfo.nickname},videoStreams:t,audioStreams:r};o.push(n)}})),t.forEach((e=>{if(!r.some((t=>t.userInfo.userId===e.userId))){e.audioStreams&&(e.audioStreams=e.audioStreams.filter((e=>"main"===e.content)));const t={userId:e.userId,userUid:e.userUid,appData:e.appData,videoStreams:e.videoStreams,audioStreams:e.audioStreams,relayUserSrcInfo:e.relayUserSrcInfo};i.push(t)}})),{addedUsers:i,updatedUsers:n,removedUsers:o}}updateUserListInfo(e,t){if(!t||!e)return null;const r=[],i=[];return t.forEach((t=>{var n;const o={userId:t.userId,userUid:t.userUid,roomId:e,nickname:t.appData?t.appData.nickname:null,relaySrcRoomId:null===(n=t.relayUserSrcInfo)||void 0===n?void 0:n.roomId},s=this.updateUserInfo(o,t.status);s&&r.push(s),i.push(t.userId)})),r.push(...this.getOtherRemoteUserPublishInfos(i,e)),this.logger.info(SD,"updateUserListInfo success, ".concat(this.getTracksUpdateInfosString(r))),r}updateUserInfo(e,t){if(this.logger.info(SD,"updateUserInfo begin, updateType:".concat(t,", userInfo: ").concat(JSON.stringify(e))),e.userId===this.localUserId)return null;const r=this.getUserInfoById(e.userId,e.roomId),i=r?r.userState:bO.NotJoin,n=!!r&&vD.isUserNameChanged(r.userInfo,null==e?void 0:e.nickname);switch(t){case pD.exitRoom:if(!r)return this.logger.error(SD,"remote user leave, but user not exist"),null;break;case pD.joinRoom:r||this.initializeRemoteUser(e,!0);break;default:this.logger.error(SD,"updateUserInfo, unknown user status:".concat(t))}const o=this.getUserInfoById(e.userId,e.roomId),s=t===pD.joinRoom?vD.getUserUpdateInfoWhenJoin(i,n,o):vD.getUserUpdateInfoWhenQuit(i,o);if(t===pD.exitRoom&&o.userState===bO.NotJoin){const t=vD.generateUniqueId(e.userId,e.roomId);this.remoteUserInfos.delete(t)}return s}static getUserUpdateInfoWhenJoin(e,t,r){return r.userState=e===bO.Rejoining?bO.Joined:r.userState,{userInfo:r.userInfo,preUserState:e,curUserState:r.userState,isUserNameChanged:t,mainStream:null,auxStream:null}}static getUserUpdateInfoWhenQuit(e,t){return t.userState=e===bO.Rejoining?e:bO.NotJoin,{userInfo:t.userInfo,preUserState:e,curUserState:t.userState,isUserNameChanged:null,mainStream:vD.getStreamListUpdateInfoWhenQuitOrRejoin(t,yO.STREAM_TYPE_MAIN,e),auxStream:vD.getStreamListUpdateInfoWhenQuitOrRejoin(t,yO.STREAM_TYPE_AUX,e)}}static getStreamListUpdateInfoWhenQuitOrRejoin(e,t,r){return r===bO.Rejoining?vD.getStreamListUpdateInfoWhenRejoin(e,t):vD.getStreamListUpdateInfoWhenQuit(e,t)}static getStreamListUpdateInfoWhenQuit(e,t){const r=t===yO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,i=vD.getRemoteTrackInfos(r),n=null==i?void 0:i.filter((e=>e.isSubscribed));return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:[],updatedTracks:[],removedTracks:i,subscribedTracks:n,tracks4Subscribe:[],tracks4Unsubscribe:n,allSubscribeTracks:[]}}static getStreamListUpdateInfoWhenRejoin(e,t){const r=t===yO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,i=vD.getRemoteTrackInfos(r),n=null==i?void 0:i.filter((e=>e.isSubscribed));return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:[],updatedTracks:[],removedTracks:i,subscribedTracks:n,tracks4Subscribe:[],tracks4Unsubscribe:[],allSubscribeTracks:n}}getTracks4UnSubscribe(e){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const t=[];return e.forEach((e=>{e.isSubscribed&&(e.isSubscribed=!1,t.push(e))})),this.logger.info(SD,"getTracks4UnSubscribe success, tracks4Unsubscribe: ".concat(JSON.stringify(t))),t}cachePlayInfo(e,t,r,i,n){if(!n)return;const o=this.getUserInfoById(e.userId,e.roomId),s=t===yO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,a=null==s?void 0:s.subscribeOption;return a?vD.isStreamRemoved(r,i)?(a.audio=!1,a.video=!1,void(a.resolutions=null)):void n.forEach((e=>{if(e.isSubscribed){if(a.audio&&e.type===vO.TRACK_TYPE_AUDIO){var t;const r=null==s||null===(t=s.remoteStream)||void 0===t?void 0:t.getAudioHRTCTrack();r&&(a.audioPlayInfo.playElement=r.getElementId(),a.audioPlayInfo.objectFit=r.getObjectFit(),a.audioPlayInfo.muted=r.getTrackMuted(),e.muted=r.getTrackMuted())}if(a.video&&e.type===vO.TRACK_TYPE_VIDEO){var r;const t=null==s||null===(r=s.remoteStream)||void 0===r?void 0:r.getVideoHRTCTrackByTrackId(e.trackId);if(t){var i;const r=null===(i=a.resolutions)||void 0===i?void 0:i.find((t=>t.resolutionId===e.trackId));r&&(r.playElement=t.getElementId(),r.objectFit=t.getObjectFit(),r.muted=t.getTrackMuted(),e.muted=t.getTrackMuted())}}}})):void 0}static isStreamRemoved(e,t){return!(e&&0!==e.length||t&&0!==t.length)}getTracks4Subscribe(e,t,r,i,n){if(this.logger.debug(SD,"getTracks4Subscribe begin"),!(i&&0!==i.length||n&&0!==n.length))return this.logger.debug(SD,"getTracks4Subscribe success, tracks4Subscribe: []"),[];const o=n.filter((e=>e.isSubscribed)),s=[],a=this.isAudioTrackNeedSubscribe(e.userId,e.roomId,t),c=i.find((e=>e.type===vO.TRACK_TYPE_AUDIO));if(a&&c){c.cssrc=this.allocateAudioReceiveSsrc(e.roomId),c.isSubscribed=!0,c.state=CO.resolutionChange;const r=this.getAudioTrackPlayInfo(e.userId,e.roomId,t);r&&(c.playElement=r.playElement,c.objectFit=r.objectFit,c.muted=r.muted);const i=o.find((e=>e.type===vO.TRACK_TYPE_AUDIO));i&&(c.state=i.state,c.muted=i.muted),s.push(c)}const u=o.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)),d=i.filter((e=>e.type===vO.TRACK_TYPE_VIDEO));for(const l of d){const r={resolutionId:l.trackId,width:l.width,height:l.height};if(this.updateVideoSubscribeOption(e.userId,e.roomId,t,r,u)){l.cssrc=this.allocateVideoReceiveSsrc(e.roomId,t),l.isSubscribed=!0,l.state=CO.resolutionChange;const i=this.getVideoTrackPlayInfo(e.userId,e.roomId,t,r);i&&(l.playElement=i.playElement,l.objectFit=i.objectFit,l.muted=i.muted);const n=this.getTrack4Replace(l,u);n&&n.state!==CO.normal&&(l.state=n.state,l.muted=n.muted),s.push(l)}}return this.logger.info(SD,"getTracks4Subscribe success, tracks4Subscribe: ".concat(JSON.stringify(s))),s}getAudioTrackPlayInfo(e,t,r){var i;const n=this.getUserInfoById(e,t);return null===(i=(r===yO.STREAM_TYPE_MAIN?n.mainStream:n.auxStream).subscribeOption)||void 0===i?void 0:i.audioPlayInfo}getVideoTrackPlayInfo(e,t,r,i){var n,o;const s=this.getUserInfoById(e,t),a=null===(n=(r===yO.STREAM_TYPE_MAIN?s.mainStream:s.auxStream).subscribeOption)||void 0===n||null===(o=n.resolutions)||void 0===o?void 0:o.find((e=>e.resolutionId===i.resolutionId));return a?{playElement:a.playElement,objectFit:a.objectFit,muted:a.muted}:null}updateVideoSubscribeOption(e,t,r,i,n){const o=this.getUserInfoById(e,t),s=r===yO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,a=null==s?void 0:s.subscribeOption;if(!a)return!1;if(!a.video)return!1;const c=a.resolutions.find((e=>e.resolutionId===i.resolutionId||e.height===i.height&&e.width===i.width||(null==n?void 0:n.length)));return c&&(c.resolutionId=i.resolutionId),!!c}enableTopThreeAudioMode(e){const t=this.getAllUserInfos(e);null==t||t.forEach((e=>{var t,r;null!==(t=e.mainStream)&&void 0!==t&&t.subscribeOption&&(e.mainStream.subscribeOption.audio=!1),null!==(r=e.auxStream)&&void 0!==r&&r.subscribeOption&&(e.auxStream.subscribeOption.audio=!1)})),this.logger.info(SD,"enableTopThreeAudioMode success")}isAudioTrackNeedSubscribe(e,t,r){var i;const n=this.getUserInfoById(e,t),o=r===yO.STREAM_TYPE_MAIN?n.mainStream:n.auxStream;return null==o||null===(i=o.subscribeOption)||void 0===i?void 0:i.audio}getTrack4Replace(e,t){return(null==t?void 0:t.find((t=>t.trackId===e.trackId||t.height===e.height&&t.width===e.width)))||(null!=t&&t.length?t[0]:null)}getAllUserStreamsByType(e,t,r){return this.getAllUserInfos(e).map((i=>{const n=t&&t!==yO.STREAM_TYPE_MAIN?null:vD.getStreamInfoByType(i,yO.STREAM_TYPE_MAIN,r),o=t&&t!==yO.STREAM_TYPE_AUX?null:vD.getStreamInfoByType(i,yO.STREAM_TYPE_AUX,r);return{userId:i.userInfo.userId,roomId:e,mainStream:n,auxStream:o}}))}static getStreamInfoByType(e,t,r){const i=t===yO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,n=vD.getRemoteTrackInfos(i),o=vD.getTracksByType(n,r);return{remoteStream:i?i.remoteStream:null,tracks:o}}getUserInfoById(e,t){const r=vD.generateUniqueId(e,t);return this.remoteUserInfos.get(r)}getUserInfoByUid(e,t){let r=null;for(const i of this.remoteUserInfos.values())if(i.userInfo.userUid===e&&i.userInfo.roomId===t){r=i;break}return r}static getTracksByType(e,t){return e&&0!==e.length?t?e.filter((e=>e.type===t)):e:[]}static isUserNameChanged(e,t){return t&&e&&e.nickname&&e.nickname!==t}static getRemoteTrackInfos(e){return null!=e&&e.remoteTrackInfos?Array.from(e.remoteTrackInfos.values()):null}getAllTracksByMediaType(e,t,r){var i,n;const o=vD.generateUniqueId(t,e),s=this.remoteUserInfos.get(o);if(!s)return null;const a=[],c=null===(i=vD.getRemoteTrackInfos(s.mainStream))||void 0===i?void 0:i.filter((e=>e.type===r));c&&a.push(...c);const u=null===(n=vD.getRemoteTrackInfos(s.auxStream))||void 0===n?void 0:n.filter((e=>e.type===r));return u&&a.push(...u),a}getMaxResolutionTrack(e){let t;for(const r of e)r.type!==vO.TRACK_TYPE_AUDIO&&(t?Math.max(r.width,r.height)-Math.max(t.width,t.height)>0&&(t=r):t=r);return this.logger.info(SD,"getMaxResolutionTrackId, maxResolution: ".concat(JSON.stringify(t))),t}getMaxResolutionTrackId(e){var t;if(!e)return null;const r=Array.from(e.remoteTrackInfos.values());let i;for(const n of r)n.type!==vO.TRACK_TYPE_AUDIO&&(i?Math.max(n.width,n.height)-Math.max(i.width,i.height)>0&&(i=n):i=n);return this.logger.info(SD,"getMaxResolutionTrackId, maxResolution: ".concat(JSON.stringify(i))),null===(t=i)||void 0===t?void 0:t.trackId}getAllSubscribedMainStream(e){const t=this.getAllUserInfos(e),r=[];return t.forEach((e=>{var t;null!==(t=e.mainStream)&&void 0!==t&&t.remoteTrackInfos&&Array.from(e.mainStream.remoteTrackInfos.values()).some((e=>e.isSubscribed))&&r.push(e)})),r}batchSubscribeMainStream(e,t){if(!e||!t)return null;const r=this.getAllSubscribedMainStream(e),i=[],n=t.find((e=>e.userId===wC));if(n){this.getUserInfoById(wC,e)||this.createRemoteShadowUser(e,n.resolutionIds)}return this.getAllUserInfos(e).forEach((n=>{const o=t.find((e=>e.userId===n.userInfo.userId));if(o){const t={video:!0,audio:!1,resolutionIds:o.resolutionIds,autoAdjustResolution:o.autoAdjustResolution,minResolution:o.minResolution},r=this.subscribeSingleStream(o.userId,e,yO.STREAM_TYPE_MAIN,t,IO.TOPN_AUDIOPOLICY,!0);i.push(r)}else{var s;const e=vD.getRemoteTrackInfos(n.mainStream),o=null==e?void 0:e.filter((e=>e.isSubscribed)),a=this.needUnsubscribeMainStream(n,t,r),c=vD.getAnotherStreamUpdateInfo(yO.STREAM_TYPE_MAIN,n),u={userInfo:n.userInfo,curUserState:n.userState,preUserState:n.userState,mainStream:{remoteStream:null===(s=n.mainStream)||void 0===s?void 0:s.remoteStream,preTracks:e,curTracks:e,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:o,tracks4Subscribe:null,tracks4Unsubscribe:o,allSubscribeTracks:a?null:o},auxStream:c};i.push(u)}})),this.logger.info(SD,"batchSubscribeMainStream success, infos: ".concat(this.getTracksUpdateInfosString(i))),i}needUnsubscribeMainStream(e,t,r){const i=!t.some((t=>t.userId===e.userInfo.userId)),n=r.some((t=>e.userInfo.userId===t.userInfo.userId));return i&&n}createRemoteShadowUser(e,t){const r={userId:wC,userUid:kC,nickname:"",roomId:e},i=[];null==t||t.forEach((e=>{const t=gD[e]||gD.LD,r={content:CC.main,ssrc:t.pssrc,streamUid:t.streamUid,pt:AM.h264PayLoad,width:t.width,height:t.height};i.push(r)})),this.doRefreshRemoteStreamList(r,yO.STREAM_TYPE_MAIN,i,null,!1),this.logger.info(SD,"createRemoteShadowUser success, upstreams: ".concat(JSON.stringify(i)))}subscribeResultCallback(e,t){if(e)try{e.successSubscribeInfos.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{e.state=CO.normal})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{e.state=CO.normal}))})),e.failSubscribeInfos.forEach((e=>this.releaseResource(e,t))),e.successUnsubscribeInfos.forEach((e=>this.releaseResource(e,!1))),e.failUnsubscribeInfos.forEach((e=>this.recoverUnsubscribeResource(e,t))),this.logger.info(SD,"subscribeResultCallback success")}catch(jN){this.logger.error(SD,"subscribeResultCallback fail, errMsg:".concat(jN))}}releaseResource(e,t){var r,i,n,o;const s=this.getUserInfoById(e.userId,e.roomId);null==e||null===(r=e.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i||i.forEach((r=>{if(this.unAllocateReceiveSsrc(e.roomId,yO.STREAM_TYPE_MAIN,r.type,r.cssrc),r.state=CO.normal,r.isSubscribed=!1,r.isTrackReady=!1,r.cssrc=0,t){const e=s.mainStream.subscribeOption;vD.recoverUnsubscribeOption(e,r)}})),null==e||null===(n=e.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o||o.forEach((r=>{if(this.unAllocateReceiveSsrc(e.roomId,yO.STREAM_TYPE_AUX,r.type,r.cssrc),r.state=CO.normal,r.isSubscribed=!1,r.isTrackReady=!1,r.cssrc=0,t){const e=s.mainStream.subscribeOption;vD.recoverUnsubscribeOption(e,r)}}))}recoverUnsubscribeResource(e,t){var r,i,n,o;const s=this.getUserInfoById(e.userId,e.roomId);null==e||null===(r=e.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i||i.forEach((r=>{var i;this.recoverReceiveSsrc(e.roomId,yO.STREAM_TYPE_MAIN,r.type,r.cssrc),r.isSubscribed=!0;const n=null===(i=s.mainStream)||void 0===i?void 0:i.remoteTrackInfos;if(n.has(r.trackId)||n.set(r.trackId,r),t){const e=s.mainStream.subscribeOption;vD.recoverSubscribeOption(e,r)}})),null==e||null===(n=e.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o||o.forEach((r=>{var i;this.recoverReceiveSsrc(e.roomId,yO.STREAM_TYPE_AUX,r.type,r.cssrc),r.isSubscribed=!0;const n=null===(i=s.auxStream)||void 0===i?void 0:i.remoteTrackInfos;if(n.has(r.trackId)||n.set(r.trackId,r),t){const e=s.mainStream.subscribeOption;vD.recoverSubscribeOption(e,r)}}))}static recoverSubscribeOption(e,t){if(t.type===vO.TRACK_TYPE_AUDIO)e.audio=!0;else{e.video=!0;const r={resolutionId:t.trackId,width:t.width,height:t.height};e.resolutions.push(r)}}static recoverUnsubscribeOption(e,t){if(t.type===vO.TRACK_TYPE_AUDIO)e.audio=!1;else{if(!e.video)return;e.resolutions?e.resolutions.forEach((t=>{var r;const i=null==e||null===(r=e.resolutions)||void 0===r?void 0:r.map((e=>e.resolutionId)).indexOf(t.resolutionId);i>-1&&e.resolutions.splice(i,1)})):(e.video=!1,e.resolutions=null)}}subscribeStream(e,t,r,i,n,o,s){const a=this.subscribeSingleStream(e,t,r,i,n,o),c=[];if(s&&(s.streamIds=[]),a){c.push(a);(r===yO.STREAM_TYPE_MAIN?a.mainStream.tracks4Subscribe:a.auxStream.tracks4Subscribe).forEach((e=>{e.trackId&&s&&s.streamIds.push(e.trackId)}))}return c.push(...this.getOtherRemoteUserPublishInfos([e],t)),this.logger.info(SD,"subscribeStream success, ".concat(this.getTracksUpdateInfosString(c))),c}subscribeSingleStream(e,t,r,i,n){var o,s;let a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],c=arguments.length>6&&void 0!==arguments[6]&&arguments[6];if(!e||!t||!i)return null;const u=this.getUserInfoById(e,t);if(!u)return this.logger.error(SD,"subscribeStream fail, user not exist}"),null;const d=[],l=[],h=[],f=vD.getRemoteTrackInfos(u.mainStream),p=vD.getRemoteTrackInfos(u.auxStream),m=r===yO.STREAM_TYPE_MAIN?f:p,g=null==m?void 0:m.filter((e=>e.isSubscribed));this.updateAudioTrackSubInfo(r,i,c,u,n,d,l,h),this.updateVideoTrackSubInfo(r,i,a,u,d,l,h),this.updateSubscribeOption(e,t,r,i,mD.subscribe);const _={remoteStream:r===yO.STREAM_TYPE_MAIN?null===(o=u.mainStream)||void 0===o?void 0:o.remoteStream:null===(s=u.auxStream)||void 0===s?void 0:s.remoteStream,preTracks:m,curTracks:m,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:g,tracks4Subscribe:d,tracks4Unsubscribe:l,allSubscribeTracks:h},S=vD.getAnotherStreamUpdateInfo(r,u);return{curUserState:u.userState,preUserState:u.userState,userInfo:u.userInfo,mainStream:r===yO.STREAM_TYPE_MAIN?_:S,auxStream:r===yO.STREAM_TYPE_AUX?_:S}}resubscribeMainStreamAudio(e){const t=this.previousAudioSubscribedUsers.get(e),r=t?Array.from(t.values()):null;if(this.logger.info(SD,"resubscribeMainStreamAudio, preAudioSubscribedUsers: ".concat(r)),!r)return null;const i={video:!1,audio:!0},n=[];r.forEach((t=>{var r,o;const s=this.subscribeSingleStream(t,e,yO.STREAM_TYPE_MAIN,i,IO.USER_SUBSCRIBE_AUDIOPOLICY);(null==s||null===(r=s.mainStream)||void 0===r||null===(o=r.tracks4Subscribe)||void 0===o?void 0:o.length)>0&&n.push(s)}));const o=[];return o.push(...n),o.push(...this.getOtherRemoteUserPublishInfos(r,e)),this.logger.info(SD,"resubscribeMainStreamAudio success, ".concat(this.getTracksUpdateInfosString(o))),n}unsubscribeAllMainStreamAudio(e){const t={video:!1,audio:!0},r=[],i=[];return this.getAllUserInfos(e).forEach((n=>{var o;if(null!==(o=n.mainStream)&&void 0!==o&&o.remoteTrackInfos?Array.from(n.mainStream.remoteTrackInfos.values()).some((e=>e.type===vO.TRACK_TYPE_AUDIO&&e.isSubscribed)):null){i.push(n.userInfo.userId);const o=this.unsubscribeSingleStream(n.userInfo.userId,e,yO.STREAM_TYPE_MAIN,t,IO.TOPN_AUDIOPOLICY);r.push(o)}})),r.push(...this.getOtherRemoteUserPublishInfos(i,e)),this.logger.info(SD,"unsubscribeAllMainStreamAudio success, ".concat(this.getTracksUpdateInfosString(r))),r}updateAudioTrackSubInfo(e,t,r,i,n,o,s,a){if(!i)return;const c=vD.getRemoteTrackInfos(i.mainStream),u=vD.getRemoteTrackInfos(i.auxStream),d=e===yO.STREAM_TYPE_MAIN?c:u,l=null==d?void 0:d.find((e=>e.type===vO.TRACK_TYPE_AUDIO));if(!l)return void this.logger.info(SD,"updateAudioTrackSubInfo: ".concat(e,", no audio track exist"));const h=l.isSubscribed?l:null;if(t.audio&&!l.isSubscribed){n===IO.USER_SUBSCRIBE_AUDIOPOLICY?(l.isSubscribed=!0,l.cssrc=this.allocateAudioReceiveSsrc(i.userInfo.roomId),o.push(l)):this.logger.warn(SD,"updateAudioTrackSubInfo, not common audio mode, but audio option is true, reserve it");const e=this.previousAudioSubscribedUsers.get(i.userInfo.roomId);null==e||e.set(i.userInfo.userId,i.userInfo.userId)}if((h||!h&&o.some((e=>e.type===vO.TRACK_TYPE_AUDIO)))&&a.push(l),r&&!t.audio&&h){l.isSubscribed=!1,s.push(l);const e=this.previousAudioSubscribedUsers.get(i.userInfo.roomId);null==e||e.delete(i.userInfo.userId)}}updateVideoTrackSubInfo(e,t,r,i,n,o,s){const a=vD.getRemoteTrackInfos(i.mainStream),c=vD.getRemoteTrackInfos(i.auxStream),u=e===yO.STREAM_TYPE_MAIN?a:c,d=null==u?void 0:u.filter((e=>e.type===vO.TRACK_TYPE_VIDEO));if(!d||0===d.length)return;const l=[];d.filter((e=>e.isSubscribed)).forEach((e=>{l.push(e)}));const h=[];if(t.video)if(t.resolutionIds)t.resolutionIds.forEach((t=>{const r=i.userInfo.userId===wC?gD[t].streamUid.toString():t,o=d.find((e=>e.trackId.toString()===r));o&&(h.push(o),l.some((e=>e.trackId.toString()===r))||(o.isSubscribed=!0,o.cssrc=this.allocateVideoReceiveSsrc(i.userInfo.roomId,e),n.push(o)))}));else{const t=this.getMaxResolutionTrack(d).trackId,r=t&&d.find((e=>e.trackId===t));r&&(h.push(r),l.some((e=>e.trackId===t))||(r.isSubscribed=!0,r.cssrc=this.allocateVideoReceiveSsrc(i.userInfo.roomId,e),n.push(r)))}const f=n.filter((e=>e.type===vO.TRACK_TYPE_VIDEO));f.forEach((e=>{e.autoAdjustResolution=t.autoAdjustResolution||DC.ON,e.minResolution=t.minResolution||"LD"})),s.push(...f),r?l.forEach((e=>{h.some((t=>t.trackId===e.trackId))?s.push(e):(e.isSubscribed=!1,o.push(e))})):s.push(...l)}unAllocateReceiveSsrc(e,t,r,i){r!==vO.TRACK_TYPE_AUDIO?this.unAllocateVideoReceiveSsrc(e,t,i):this.unAllocateAudioReceiveSsrc(e,i)}recoverReceiveSsrc(e,t,r,i){r!==vO.TRACK_TYPE_AUDIO?this.recoverVideoReceiveSsrc(e,t,i):this.recoverAudioReceiveSsrc(e,i)}unAllocateAudioReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const i=r.audioReceiveSsrcs.indexOf(t);-1===i&&this.logger.error(SD,"unAllocateAudioReceiveSsrc error, ".concat(t," not allocated")),r.audioReceiveSsrcs.splice(i,1),this.logger.info(SD,"unAllocateAudioReceiveSsrc success, ".concat(t))}recoverAudioReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);-1===r.audioReceiveSsrcs.indexOf(t)&&r.audioReceiveSsrcs.push(t),this.logger.info(SD,"recoverAudioReceiveSsrc success, ".concat(t))}unAllocateVideoReceiveSsrc(e,t,r){const i=this.roomSsrc.get(e);if(!i)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=i.videoReceiveSsrcs.indexOf(r);-1!==n?(i.videoReceiveSsrcs.splice(n,1),this.logger.info(SD,"unAllocateVideoReceiveSsrc success, ".concat(t,", ").concat(r))):this.logger.error(SD,"unAllocateVideoReceiveSsrc error, ".concat(t,", ").concat(r," not allocated"))}recoverVideoReceiveSsrc(e,t,r){const i=this.roomSsrc.get(e);if(!i)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);-1===i.videoReceiveSsrcs.indexOf(r)&&i.videoReceiveSsrcs.push(r),this.logger.info(SD,"recoverVideoReceiveSsrc success, ".concat(t,", ").concat(r))}allocateAudioReceiveSsrc(e){const t=this.roomSsrc.get(e);if(!t)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!this.audioCssrcs||0===this.audioCssrcs.length)throw this.logger.error(SD,"audio ssrc not found"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);for(const r of this.audioCssrcs)if(!t.audioReceiveSsrcs.includes(r))return t.audioReceiveSsrcs.push(r),this.logger.info(SD,"allocateAudioReceiveSsrc success, ".concat(r)),r;throw this.logger.error(SD,"have no available audio receive ssrc"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}allocateVideoReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return t===yO.STREAM_TYPE_AUX?this.doAllocateVideoReceiveSsrc(this.auxVideoCssrcs,r.videoReceiveSsrcs):this.doAllocateVideoReceiveSsrc(this.mainVideoCssrcs,r.videoReceiveSsrcs)}doAllocateVideoReceiveSsrc(e,t){if(!e||0===e.length)throw this.logger.error(SD,"video ssrc not found"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);for(const r of e)if(!t.includes(r))return t.push(r),this.logger.info(SD,"allocateVideoReceiveSsrc success, ".concat(r)),r;throw this.logger.error(SD,"have no available video receive ssrc"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}unsubscribeStream(e,t,r,i){const n=this.unsubscribeSingleStream(e,t,r,i,IO.USER_SUBSCRIBE_AUDIOPOLICY);this.updateSubscribeOption(e,t,r,i,mD.unsubscribe);const o=[];return n&&o.push(n),o.push(...this.getOtherRemoteUserPublishInfos([e],t)),this.logger.info(SD,"unsubscribeStream success, ".concat(this.getTracksUpdateInfosString(o))),o}updateSubscribeOption(e,t,r,i,n){if(!i)throw this.logger.error(SD,"updateSubscribeOption fail, trackOption is null}"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const o=this.getUserInfoById(e,t),s=r===yO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream;n===mD.subscribe?s.subscribeOption=this.getFullSubscribeOptions(s,i):(i.audio&&(s.subscribeOption.audio=!1),i.video&&(i.resolutionIds?i.resolutionIds.forEach((e=>{var t,r;const i=null===(t=s.subscribeOption)||void 0===t||null===(r=t.resolutions)||void 0===r?void 0:r.map((e=>e.resolutionId)).indexOf(e);i>-1&&s.subscribeOption.resolutions.splice(i,1)})):(s.subscribeOption.video=!1,s.subscribeOption.resolutions=null)))}getFullSubscribeOptions(e,t){if(!t)throw this.logger.error(SD,"trackOption is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=[],i={};if(t.video)if(t.resolutionIds)t.resolutionIds.forEach((t=>{vD.appendResolutions(e,t,r)}));else{const t=this.getMaxResolutionTrackId(e);vD.appendResolutions(e,t,r)}if(t.audio){const t=Array.from(e.remoteTrackInfos.values()).find((e=>e.type===vO.TRACK_TYPE_AUDIO));null!=t&&t.playElement&&(i.playElement=t.playElement,i.objectFit=t.objectFit,i.muted=t.muted)}return{audio:t.audio,video:t.video,resolutions:r,audioPlayInfo:i,autoAdjustResolution:t.autoAdjustResolution,minResolution:t.minResolution}}static appendResolutions(e,t,r){const i=e.remoteTrackInfos.get(t);if(i){const e={resolutionId:t,width:i.width,height:i.height};i.playElement&&(e.playElement=i.playElement,e.objectFit=i.objectFit,e.muted=i.muted),r.push(e)}}getRemoteUserInfoById(e,t){if(!e||!t)return null;const r=this.getUserInfoById(e,t);return r||(this.logger.error(SD,"unsubscribeSingleStream fail, user not exist}"),null)}unsubscribeSingleStream(e,t,r,i,n){var o,s;const a=this.getRemoteUserInfoById(e,t);if(null===a)return null;const c=vD.getRemoteTrackInfos(a.mainStream),u=vD.getRemoteTrackInfos(a.auxStream),d=r===yO.STREAM_TYPE_MAIN?c:u;if(!d||0===d.length)return this.logger.warn(SD,"unsubscribeSingleStream, no track exist ".concat(e)),null;const l=d.filter((e=>e.isSubscribed)),h=[];if(i.audio){const r=d.find((e=>e.type===vO.TRACK_TYPE_AUDIO&&e.isSubscribed));if(r&&(r.isSubscribed=!1,h.push(r),n===IO.USER_SUBSCRIBE_AUDIOPOLICY)){const r=this.previousAudioSubscribedUsers.get(t);null==r||r.delete(e)}}i.video&&this.unsubscribeVideo(i,l,h,e,d);const f={remoteStream:r===yO.STREAM_TYPE_MAIN?null===(o=a.mainStream)||void 0===o?void 0:o.remoteStream:null===(s=a.auxStream)||void 0===s?void 0:s.remoteStream,preTracks:d,curTracks:d,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:l,tracks4Subscribe:null,tracks4Unsubscribe:h,allSubscribeTracks:Array.from(d.values()).filter((e=>e.isSubscribed))},p=vD.getAnotherStreamUpdateInfo(r,a);return{preUserState:a.userState,curUserState:a.userState,userInfo:a.userInfo,mainStream:r===yO.STREAM_TYPE_MAIN?f:p,auxStream:r===yO.STREAM_TYPE_AUX?f:p}}unsubscribeVideo(e,t,r,i,n){if(e.resolutionIds)e.resolutionIds.forEach((e=>{const t=i===wC?gD[e].streamUid.toString():e,o=null==n?void 0:n.find((e=>e.trackId.toString()===t&&e.isSubscribed));o&&(o.isSubscribed=!1,r.push(o))}));else{const e=null==t?void 0:t.filter((e=>e.type==vO.TRACK_TYPE_VIDEO));null==e||e.forEach((e=>{e.isSubscribed=!1,r.push(e)}))}}updateUserName(e,t,r){const i=this.getUserInfoById(e,t);i?(i.userInfo.nickname=r,this.logger.info(SD,"updateUserName success, userId: ".concat(e,", nickName: ").concat(r))):this.logger.error(SD,"updateUserName fail, user not exist}")}isRemoteUserSubscribed(e,t){var r,i;const n=this.getUserInfoById(e,t);if(!n)return this.logger.info(SD,"isRemoteUserSubscribed, user not exist}"),!1;const o=!(null===(r=n.mainStream)||void 0===r||!r.remoteTrackInfos)&&Array.from(n.mainStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)).length>0,s=!(null===(i=n.auxStream)||void 0===i||!i.remoteTrackInfos)&&Array.from(n.auxStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)).length>0;return o||s}getUserInfoByStreamId(e,t){return this.getAllUserInfos(e).find((e=>{var r,i;return(null===(r=e.mainStream)||void 0===r?void 0:r.remoteTrackInfos.has(t))||(null===(i=e.auxStream)||void 0===i?void 0:i.remoteTrackInfos.has(t))}))}getAllUserInfos(e){return Array.from(this.remoteUserInfos.values()).filter((t=>t.userInfo.roomId===e))}getAllSubscribedUpdateInfos4Unsubscribe(e){return this.getAllUserInfos(e).map((e=>{const t=vD.getRemoteTrackInfos(e.mainStream).filter((e=>e.isSubscribed));t.forEach((e=>{e.isSubscribed=!1}));const r=vD.getRemoteTrackInfos(e.auxStream).filter((e=>e.isSubscribed));return r.forEach((e=>{e.isSubscribed=!1})),{userInfo:e.userInfo,preUserState:e.userState,curUserState:e.userState,mainStream:{remoteStream:e.mainStream.remoteStream,tracks4Unsubscribe:t,allSubscribeTracks:[]},auxStream:{remoteStream:e.auxStream.remoteStream,tracks4Unsubscribe:r,allSubscribeTracks:[]}}}))}initializeRemoteUser(e,t){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r={userInfo:e,userState:t?bO.Joined:bO.NotJoin,mainStream:null,auxStream:null},i=vD.generateUniqueId(e.userId,e.roomId);return this.remoteUserInfos.set(i,r),this.roomSsrc.has(e.roomId)||this.roomSsrc.set(e.roomId,{audioReceiveSsrcs:[],videoReceiveSsrcs:[]}),this.logger.info(SD,"initializeRemoteUser success, userInfo: ".concat(JSON.stringify(e))),r}updateRemoteUser(e){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const t=this.getUserInfoById(e.userId,e.roomId);return t?(e.nickname=e.nickname||t.userInfo.nickname,t.userInfo=e,this.logger.info(SD,"updateRemoteUser success, userInfo: ".concat(JSON.stringify(e))),t):null}initializeRemoteStream(e,t,r){const i=e===yO.STREAM_TYPE_MAIN?"main":"auxiliary",n=new rM({type:i,log:this.logger,userId:t,client:this.client,roomId:r}),o={remoteTrackInfos:new Map,remoteStream:n,subscribeOption:{audio:!1,video:!1}};if(!this.previousAudioSubscribedUsers.has(r)){const e=new Map;this.previousAudioSubscribedUsers.set(r,e)}return this.logger.info(SD,"initializeStreamInfo success, userId: ".concat(t,", type: ").concat(o.remoteStream.getType())),o}refreshRemoteStreamList(e,t,r){const i=null==t?void 0:t.filter((e=>e.content!==CC.desktop)),n=null==t?void 0:t.filter((e=>e.content===CC.desktop)),o=this.getUserInfoById(e.userId,e.roomId),s=this.doRefreshRemoteStreamList(e,yO.STREAM_TYPE_MAIN,i,r,!1),a=this.doRefreshRemoteStreamList(e,yO.STREAM_TYPE_AUX,n,null,!1),c=this.getUserInfoById(e.userId,e.roomId);return this.getAllPublishInfosWhenStreamUpdate(!o,s,a,c)}doRefreshRemoteStreamList(e,t,r,i,n){if(this.logger.info(SD,"doRefreshRemoteStreamList begin, streamType:".concat(t,",isLocalRejoin:").concat(n,",")+"userInfo: ".concat(JSON.stringify(e),", allVideoStreams: ").concat(JSON.stringify(r),", allAudioStreams: ").concat(JSON.stringify(i))),e.userId===this.localUserId)return null;const o=this.getUserInfoById(e.userId,e.roomId);e.relaySrcRoomId=e.relaySrcRoomId||(null==o?void 0:o.userInfo.relaySrcRoomId);const s=o?this.updateRemoteUser(e):this.initializeRemoteUser(e,!0),a=this.getStreamInfoByStreamType(t,s,e),c=vD.getRemoteTrackInfos(a),u=null==c?void 0:c.filter((e=>e.isSubscribed)),d=a.remoteTrackInfos,l=[],h=[],f=[];null==c||c.forEach((e=>{this.isPreTrackInvalid(r,i,e,n)&&(n&&e.isSubscribed&&(e.state=CO.localRejoin),f.push(e),d.delete(e.trackId))})),this.refreshTracks(r,i,c,d,n,l,h,f),this.cachePlayInfo(e,t,r,i,f);const p=this.getTracks4Subscribe(e,t,a.remoteStream,l,f),m=this.getTracks4UnSubscribe(f),g=Array.from(a.remoteTrackInfos.values());return this.updateRemoteStreamTracks(g,a.remoteStream),{remoteStream:a.remoteStream,preTracks:c,curTracks:g,addedTracks:l,updatedTracks:h,removedTracks:f,subscribedTracks:u,tracks4Subscribe:p,tracks4Unsubscribe:m,allSubscribeTracks:null==g?void 0:g.filter((e=>e.isSubscribed))}}refreshTracks(e,t,r,i,n,o,s,a){(null!=e&&e.length||null!=t&&t.length)&&(null==r||r.forEach((e=>{e.state===CO.remoteRejoinCache&&(a.push(e),i.delete(e.trackId))}))),this.refreshVideoStreamTracks(e,r,i,n,o,s),this.refreshAudioStreamTracks(t,r,i,n,o,s)}refreshVideoStreamTracks(e,t,r,i,n,o){null==e||e.forEach((e=>{const s=null==t?void 0:t.find((t=>t.trackId===e.streamUid.toString()));if(s){const t=vD.generateUpdateVideoTrack(e,s);r.set(e.streamUid.toString(),t),s.state===CO.remoteRejoinCache||i?(t.isSubscribed=!1,t.isTrackReady=!1,n.push(t)):vD.isSameResolution(s,e)&&!vD.isMuteStatusChange(s,e)||o.push(s)}else{const t=vD.generateNewVideoTrack(e);r.set(e.streamUid.toString(),t),n.push(t)}}))}refreshAudioStreamTracks(e,t,r,i,n,o){null==e||e.forEach((e=>{if("main"===(null==e?void 0:e.content)){const s=null==t?void 0:t.find((t=>t.trackId===e.streamUid.toString()));if(s){const t=vD.generateUpdateAudioTrack(e,s);r.set(e.streamUid.toString(),t),s.state===CO.remoteRejoinCache||i?(t.isSubscribed=!1,t.isTrackReady=!1,n.push(t)):vD.isMuteStatusChange(s,e)&&o.push(s)}else{const t=vD.generateNewAudioTrack(e);r.set(e.streamUid.toString(),t),n.push(t)}}}))}remoteUserReconnect(e){if(!e)return;const t=this.getUserInfoById(e.userId,e.roomId);if(!t)return this.logger.error(SD,"remoteUserReconnect, user not exist"),null;this.isRemoteUserSubscribed(e.userId,e.roomId)&&this.cacheHistorySubscription(t),t.userState=bO.Rejoining,this.logger.info(SD,"remoteUserReconnect, update user state to rejoining")}cacheHistorySubscription(e){if(!e)return null;const t=this.getSubscribedTracksInfo(e.userInfo.userId,e.userInfo.roomId,yO.STREAM_TYPE_MAIN),r=this.getSubscribedTracksInfo(e.userInfo.userId,e.userInfo.roomId,yO.STREAM_TYPE_AUX);null==t||t.forEach((e=>{e.state=CO.remoteRejoinCache})),null==r||r.forEach((e=>{e.state=CO.remoteRejoinCache}))}getSubscribedTracksInfo(e,t,r){var i,n;const o=this.getUserInfoById(e,t);if(!o)return this.logger.error(SD,"getSubscribedMainTracksInfo, user not exist}"),null;const s=r===yO.STREAM_TYPE_MAIN?null===(i=o.mainStream)||void 0===i?void 0:i.remoteTrackInfos:null===(n=o.auxStream)||void 0===n?void 0:n.remoteTrackInfos;return s&&Array.from(s.values()).filter((e=>e.isSubscribed))}getStreamInfoByStreamType(e,t,r){if(!(e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream)){const i=this.initializeRemoteStream(e,r.userId,r.roomId);e===yO.STREAM_TYPE_MAIN?t.mainStream=i:t.auxStream=i}return e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream}static generateNewVideoTrack(e){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:!1,isTrackReady:!1,pssrc:e.ssrc,cssrc:0,type:vO.TRACK_TYPE_VIDEO,width:e.width,height:e.height,state:CO.normal,mute:e.mute,maxFs:e.maxFs,fps:e.fps}}static generateNewAudioTrack(e){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:!1,isTrackReady:!1,pssrc:e.ssrc,cssrc:0,type:vO.TRACK_TYPE_AUDIO,state:CO.normal,mute:e.mute}}static generateUpdateVideoTrack(e,t){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:t.isSubscribed,isTrackReady:t.isTrackReady,pssrc:t.pssrc,cssrc:t.cssrc,type:vO.TRACK_TYPE_VIDEO,width:e.width,height:e.height,state:t.state,mute:e.mute}}static generateUpdateAudioTrack(e,t){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:t.isSubscribed,isTrackReady:t.isTrackReady,pssrc:t.pssrc,cssrc:t.cssrc,type:vO.TRACK_TYPE_AUDIO,state:t.state,mute:e.mute}}updateRemoteStream(e,t,r){const i=null==t?void 0:t.filter((e=>e.content!==CC.desktop)),n=null==t?void 0:t.filter((e=>e.content===CC.desktop)),o=this.doUpdateRemoteStream(e,yO.STREAM_TYPE_MAIN,i,r),s=this.doUpdateRemoteStream(e,yO.STREAM_TYPE_AUX,n,null),a=this.getUserInfoById(e.userId,e.roomId);return{userInfo:a.userInfo,preUserState:a.userState,curUserState:a.userState,isUserNameChanged:null,mainStream:o,auxStream:s}}doUpdateRemoteStream(e,t,r,i){this.logger.info(SD,"updateRemoteStreamInfo begin, streamType:".concat(t)+"userInfo: ".concat(JSON.stringify(e),", videoStreams: ").concat(JSON.stringify(r),", audioStreams: ").concat(JSON.stringify(i),","));if(!this.getUserInfoById(e.userId,e.roomId))return this.logger.error(SD,"updateRemoteStream, user not exist"),null;const n=this.getUserInfoById(e.userId,e.roomId),o=this.getStreamInfoByStreamType(t,n,e),s=vD.getRemoteTrackInfos(o),a=null==s?void 0:s.filter((e=>e.isSubscribed)),c=o.remoteTrackInfos,u=[];null==r||r.forEach((e=>{const t=null==s?void 0:s.find((t=>t.trackId===e.streamUid.toString()));if(t&&(!vD.isSameResolution(t,e)||vD.isMuteStatusChange(t,e))){const r=vD.generateUpdateVideoTrack(e,t);c.set(e.streamUid.toString(),r),u.push(t)}})),null==i||i.forEach((e=>{const t=null==s?void 0:s.find((t=>t.trackId===e.streamUid.toString()));if(t&&vD.isMuteStatusChange(t,e)){const r=vD.generateUpdateAudioTrack(e,t);c.set(e.streamUid.toString(),r),u.push(t)}}));const d=Array.from(o.remoteTrackInfos.values());return this.updateRemoteStreamTracks(d,o.remoteStream),{remoteStream:o.remoteStream,preTracks:s,curTracks:d,addedTracks:[],updatedTracks:u,removedTracks:[],subscribedTracks:a,tracks4Subscribe:[],tracks4Unsubscribe:[],allSubscribeTracks:null==d?void 0:d.filter((e=>e.isSubscribed))}}getAllPublishInfosWhenStreamUpdate(e,t,r,i){const n={userInfo:i.userInfo,preUserState:e?bO.NotJoin:i.userState,curUserState:i.userState,isUserNameChanged:null,mainStream:t,auxStream:r},o=[];return o.push(n),o.push(...this.getOtherRemoteUserPublishInfos([i.userInfo.userId],i.userInfo.roomId)),this.logger.info(SD,"updateRemoteStreamInfo success, ".concat(this.getTracksUpdateInfosString(o))),o}getOtherRemoteUserPublishInfos(e,t){const r=[];return this.getAllUserInfos(t).forEach((t=>{if(!e.includes(t.userInfo.userId)){var i,n,o,s,a,c;const e=null!==(i=t.mainStream)&&void 0!==i&&null!==(n=i.remoteTrackInfos)&&void 0!==n&&n.size?Array.from(t.mainStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)):null,u=null!==(o=t.auxStream)&&void 0!==o&&null!==(s=o.remoteTrackInfos)&&void 0!==s&&s.size?Array.from(t.auxStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)):null,d={userInfo:t.userInfo,curUserState:t.userState,preUserState:t.userState,mainStream:{remoteStream:null===(a=t.mainStream)||void 0===a?void 0:a.remoteStream,allSubscribeTracks:e},auxStream:{remoteStream:null===(c=t.auxStream)||void 0===c?void 0:c.remoteStream,allSubscribeTracks:u}};r.push(d)}})),r}static getAnotherStreamUpdateInfo(e,t){const r=e===yO.STREAM_TYPE_MAIN?t.auxStream:t.mainStream,i=vD.getRemoteTrackInfos(r),n=i?i.filter((e=>e.isSubscribed)):null;return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:n?[...n]:null,tracks4Subscribe:null,tracks4Unsubscribe:null,allSubscribeTracks:n?[...n]:null}}getTracksUpdateInfosString(e){if(!e)return"";let t="";return e.forEach((e=>{t=t+vD.getTracksUpdateInfoString(e)+" "})),t}static getTracksUpdateInfoString(e){var t,r,i,n,o,s,a,c,u,d,l,h,f,p,m,g,_,S,v,y,I,T,R,E,b,C,A,w,k,O,P,M,D,N,U,x,L,B,V,Y,j,F,H,K,z,W,G,J,q,X,Q,$,Z,ee;return e?"userId:".concat(e.userInfo.userId,", preUserState: ").concat(e.preUserState,",curUserState: ").concat(e.curUserState,",")+"main stream:"+"".concat(null!==(t=e.mainStream)&&void 0!==t&&null!==(r=t.preTracks)&&void 0!==r&&r.length?"preTracks:"+JSON.stringify(null===(i=e.mainStream)||void 0===i?void 0:i.preTracks)+",":"")+"".concat(null!==(n=e.mainStream)&&void 0!==n&&null!==(o=n.curTracks)&&void 0!==o&&o.length?"curTracks:"+JSON.stringify(null===(s=e.mainStream)||void 0===s?void 0:s.curTracks)+",":"")+"".concat(null!==(a=e.mainStream)&&void 0!==a&&null!==(c=a.addedTracks)&&void 0!==c&&c.length?"addedTracks:"+JSON.stringify(null===(u=e.mainStream)||void 0===u?void 0:u.addedTracks)+",":"")+"".concat(null!==(d=e.mainStream)&&void 0!==d&&null!==(l=d.updatedTracks)&&void 0!==l&&l.length?"updatedTracks:"+JSON.stringify(null===(h=e.mainStream)||void 0===h?void 0:h.updatedTracks)+",":"")+"".concat(null!==(f=e.mainStream)&&void 0!==f&&null!==(p=f.removedTracks)&&void 0!==p&&p.length?"removedTracks:"+JSON.stringify(null===(m=e.mainStream)||void 0===m?void 0:m.removedTracks)+",":"")+"".concat(null!==(g=e.mainStream)&&void 0!==g&&null!==(_=g.subscribedTracks)&&void 0!==_&&_.length?"subscribedTracks:"+JSON.stringify(null===(S=e.mainStream)||void 0===S?void 0:S.subscribedTracks)+",":"")+"".concat(null!==(v=e.mainStream)&&void 0!==v&&null!==(y=v.tracks4Subscribe)&&void 0!==y&&y.length?"tracks4Subscribe:"+JSON.stringify(null===(I=e.mainStream)||void 0===I?void 0:I.tracks4Subscribe)+",":"")+"".concat(null!==(T=e.mainStream)&&void 0!==T&&null!==(R=T.tracks4Unsubscribe)&&void 0!==R&&R.length?"tracks4Unsubscribe:"+JSON.stringify(null===(E=e.mainStream)||void 0===E?void 0:E.tracks4Unsubscribe)+",":"")+"".concat(null!==(b=e.mainStream)&&void 0!==b&&null!==(C=b.allSubscribeTracks)&&void 0!==C&&C.length?"allSubscribeTracks:"+JSON.stringify(null===(A=e.mainStream)||void 0===A?void 0:A.allSubscribeTracks)+",":"")+"aux stream:"+"".concat(null!==(w=e.auxStream)&&void 0!==w&&null!==(k=w.preTracks)&&void 0!==k&&k.length?"preTracks:"+JSON.stringify(null===(O=e.auxStream)||void 0===O?void 0:O.preTracks)+",":"")+"".concat(null!==(P=e.auxStream)&&void 0!==P&&null!==(M=P.curTracks)&&void 0!==M&&M.length?"curTracks:"+JSON.stringify(null===(D=e.auxStream)||void 0===D?void 0:D.curTracks)+",":"")+"".concat(null!==(N=e.auxStream)&&void 0!==N&&null!==(U=N.addedTracks)&&void 0!==U&&U.length?"addedTracks:"+JSON.stringify(null===(x=e.auxStream)||void 0===x?void 0:x.addedTracks)+",":"")+"".concat(null!==(L=e.auxStream)&&void 0!==L&&null!==(B=L.updatedTracks)&&void 0!==B&&B.length?"updatedTracks:"+JSON.stringify(null===(V=e.auxStream)||void 0===V?void 0:V.updatedTracks)+",":"")+"".concat(null!==(Y=e.auxStream)&&void 0!==Y&&null!==(j=Y.removedTracks)&&void 0!==j&&j.length?"removedTracks:"+JSON.stringify(null===(F=e.auxStream)||void 0===F?void 0:F.removedTracks)+",":"")+"".concat(null!==(H=e.auxStream)&&void 0!==H&&null!==(K=H.subscribedTracks)&&void 0!==K&&K.length?"subscribedTracks:"+JSON.stringify(null===(z=e.auxStream)||void 0===z?void 0:z.subscribedTracks)+",":"")+"".concat(null!==(W=e.auxStream)&&void 0!==W&&null!==(G=W.tracks4Subscribe)&&void 0!==G&&G.length?"tracks4Subscribe:"+JSON.stringify(null===(J=e.auxStream)||void 0===J?void 0:J.tracks4Subscribe)+",":"")+"".concat(null!==(q=e.auxStream)&&void 0!==q&&null!==(X=q.tracks4Unsubscribe)&&void 0!==X&&X.length?"tracks4Unsubscribe:"+JSON.stringify(null===(Q=e.auxStream)||void 0===Q?void 0:Q.tracks4Unsubscribe)+",":"")+"".concat(null!==($=e.auxStream)&&void 0!==$&&null!==(Z=$.allSubscribeTracks)&&void 0!==Z&&Z.length?"allSubscribeTracks:"+JSON.stringify(null===(ee=e.auxStream)||void 0===ee?void 0:ee.allSubscribeTracks):""):""}updateRemoteStreamTracks(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!e)return void this.logger.error(SD,"updateRemoteStreamTracks , curAllTracks is null");const r=new Map;e.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).forEach((e=>{r.set(e.trackId.toString(),{streamId:e.trackId.toString(),width:e.width,height:e.height})}));const i=e.some((e=>e.type===vO.TRACK_TYPE_AUDIO)),n=t.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN;t.updateRemoteResolutions(n,[...r.values()],i)}isPreTrackInvalid(e,t,r,i){return!!i||r.state!==CO.remoteRejoinCache&&(r.type===vO.TRACK_TYPE_VIDEO&&this.isPreVideoTrackRemoved(e,r)||r.type===vO.TRACK_TYPE_AUDIO&&this.isPreAudioTrackRemoved(t,r))}isPreVideoTrackRemoved(e,t){return!(null!=e&&e.some((e=>e.streamUid.toString()===t.trackId)))}isPreAudioTrackRemoved(e,t){return!(null!=e&&e.some((e=>e.streamUid.toString()===t.trackId)))}static isSameResolution(e,t){if(!e||!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e.height===t.height&&e.width===t.width}static isMuteStatusChange(e,t){if(!e||!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e.mute!==t.mute}clear(e){if(e){for(const o of this.remoteUserInfos.keys())if(o.indexOf("#".concat(e))>0){var t,r,i,n;const e=this.remoteUserInfos.get(o);null===(t=e.mainStream)||void 0===t||null===(r=t.remoteStream)||void 0===r||r.close(),null===(i=e.auxStream)||void 0===i||null===(n=i.remoteStream)||void 0===n||n.close(),this.remoteUserInfos.delete(o)}this.roomSsrc.delete(e),this.previousAudioSubscribedUsers.delete(e)}}static generateUniqueId(e,t){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return"".concat(e,"#").concat(t)}}function yD(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const ID=[200,201,204];const TD=new class{setLogServerConfigs(e){this.logServerConfigs=function(e){for(var t=1;tyA)throw this.logger.error(RD,"relayClients size over maxium: ".concat(yA)),new qc(Gc.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM);if(this.find(e.clientSymbol,t))throw this.logger.error(RD,"addRelayConnection:".concat(t," already exist")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"addRelayConnection:".concat(t," already exist"));return new AN(e.clientConfig,e.clientSymbol)}getRelayConnection(e,t){return this.find(e.clientSymbol,t)}stopRelayConnection(e,t){e.mainRelayRoomSymbol?(this.find(e.mainRelayRoomSymbol,t)||this.logger.error(RD,"stopRelayClient:".concat(t," not exist")),this.remove(e.mainRelayRoomSymbol,t)):t?this.remove(e.clientSymbol,t):this.remove(e.clientSymbol)}roleValidCheck4RelayRoom(e,t){if(t===sM.JOINER){let t=!1;for(const r of this.relayClients.get(e.mainRelayRoomSymbol||e.clientSymbol).values())if(r.userInfo.role===sM.JOINER){t=!0;break}if(t)throw this.logger.error(RD,"only one joiner can include in relayRooms."),new qc(Gc.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM)}}switchRoleParamsCheck(e,t,r){if(t!==sM.JOINER&&t!==sM.PLAYER||null==r||!r.signature||null==r||!r.ctime)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.roleValidCheck4RelayRoom(e,t)}};var bD=Sn,CD="ArrayBuffer",AD=HS[CD];en({global:!0,constructor:!0,forced:c[CD]!==AD},{ArrayBuffer:AD}),bD(CD);var wD={exports:{}};!function(e,t){e.exports=function(){var e=Math.imul,t=Math.clz32;function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var r,i=0;ie.length)&&(t=e.length);for(var r=0,i=Array(t);r=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==r.return||r.return()}finally{if(a)throw o}}}}var R=function(e){var t=Math.abs,n=Math.max,a=Math.floor;function c(e,t){var r;if(i(this,c),(r=u.call(this,e)).sign=t,Object.setPrototypeOf(f(r),c.prototype),e>c.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return r}s(c,e);var u=m(c);return o(c,[{key:"toDebugString",value:function(){var e,t=["BigInt["],r=T(this);try{for(r.s();!(e=r.n()).done;){var i=e.value;t.push((i?(i>>>0).toString(16):i)+", ")}}catch(e){r.e(e)}finally{r.f()}return t.push("]"),t.join("")}},{key:"toString",value:function(){var e=0e||36this.length&&(r=this.length);for(var i=32767&e,n=e>>>15,o=0,s=t,a=0;a>>15,h=c.__imul(d,i),f=c.__imul(d,n),p=c.__imul(l,i),m=s+h+o;o=m>>>30,m&=1073741823,o+=(m+=((32767&f)<<15)+((32767&p)<<15))>>>30,s=c.__imul(l,n)+(f>>>15)+(p>>>15),this.__setDigit(a,1073741823&m)}if(0!==o||0!==s)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(e,t,r){for(var i,n=0,o=0;o>>15,this.__setHalfDigit(t+o,32767&i);return n}},{key:"__inplaceSub",value:function(e,t,r){var i=0;if(1&t){t>>=1;for(var n=this.__digit(t),o=32767&n,s=0;s>>1;s++){var a=e.__digit(s),c=(n>>>15)-(32767&a)-i;i=1&c>>>15,this.__setDigit(t+s,(32767&c)<<15|32767&o),i=1&(o=(32767&(n=this.__digit(t+s+1)))-(a>>>15)-i)>>>15}var u=e.__digit(s),d=(n>>>15)-(32767&u)-i;if(i=1&d>>>15,this.__setDigit(t+s,(32767&d)<<15|32767&o),t+s+1>=this.length)throw new RangeError("out of bounds");0==(1&r)&&(i=1&(o=(32767&(n=this.__digit(t+s+1)))-(u>>>15)-i)>>>15,this.__setDigit(t+e.length,1073709056&n|32767&o))}else{t>>=1;for(var l=0;l>>15)-(f>>>15)-(i=1&p>>>15);i=1&m>>>15,this.__setDigit(t+l,(32767&m)<<15|32767&p)}var g=this.__digit(t+l),_=e.__digit(l),S=(32767&g)-(32767&_)-i;i=1&S>>>15;var v=0;0==(1&r)&&(i=1&(v=(g>>>15)-(_>>>15)-i)>>>15),this.__setDigit(t+l,(32767&v)<<15|32767&S)}return i}},{key:"__inplaceRightShift",value:function(e){if(0!==e){for(var t,r=this.__digit(0)>>>e,i=this.length-1,n=0;n>>e;this.__setDigit(i,r)}}},{key:"__digit",value:function(e){return this[e]}},{key:"__unsignedDigit",value:function(e){return this[e]>>>0}},{key:"__setDigit",value:function(e,t){this[e]=0|t}},{key:"__setDigitGrow",value:function(e,t){this[e]=0|t}},{key:"__halfDigitLength",value:function(){var e=this.length;return 32767>=this.__unsignedDigit(e-1)?2*e-1:2*e}},{key:"__halfDigit",value:function(e){return 32767&this[e>>>1]>>>15*(1&e)}},{key:"__setHalfDigit",value:function(e,t){var r=e>>>1,i=this.__digit(r),n=1&e?32767&i|t<<15:1073709056&i|32767&t;this.__setDigit(r,n)}}],[{key:"BigInt",value:function(e){var t=Number.isFinite;if("number"==typeof e){if(0===e)return c.__zero();if(c.__isOneDigitInt(e))return 0>e?c.__oneDigit(-e,!0):c.__oneDigit(e,!1);if(!t(e)||a(e)!==e)throw new RangeError("The number "+e+" cannot be converted to BigInt because it is not an integer");return c.__fromDouble(e)}if("string"==typeof e){var i=c.__fromString(e);if(null===i)throw new SyntaxError("Cannot convert "+e+" to a BigInt");return i}if("boolean"==typeof e)return!0===e?c.__oneDigit(1,!1):c.__zero();if("object"===r(e)){if(e.constructor===c)return e;var n=c.__toPrimitive(e);return c.BigInt(n)}throw new TypeError("Cannot convert "+e+" to a BigInt")}},{key:"toNumber",value:function(e){var t=e.length;if(0===t)return 0;if(1===t){var r=e.__unsignedDigit(0);return e.sign?-r:r}var i=e.__digit(t-1),n=c.__clz30(i),o=30*t-n;if(1024>>=12;var h=d-12,f=12<=d?0:a<<20+d,p=20+d;for(0>>30-h,f=a<>>30-p,p-=30;var m=c.__decideRounding(e,p,u,a);if((1===m||0===m&&1==(1&f))&&0==(f=f+1>>>0)&&0!=++l>>>20&&(l=0,1023<++s))return e.sign?-1/0:1/0;var g=e.sign?-2147483648:0;return s=s+1023<<20,c.__kBitConversionInts[1]=g|s|l,c.__kBitConversionInts[0]=f,c.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(e){if(0===e.length)return e;var t=e.__copy();return t.sign=!e.sign,t}},{key:"bitwiseNot",value:function(e){return e.sign?c.__absoluteSubOne(e).__trim():c.__absoluteAddOne(e,!0)}},{key:"exponentiate",value:function(e,t){if(t.sign)throw new RangeError("Exponent must be positive");if(0===t.length)return c.__oneDigit(1,!1);if(0===e.length)return e;if(1===e.length&&1===e.__digit(0))return e.sign&&0==(1&t.__digit(0))?c.unaryMinus(e):e;if(1=c.__kMaxLengthBits)throw new RangeError("BigInt too big");if(1===e.length&&2===e.__digit(0)){var i=1+(0|r/30),n=new c(i,e.sign&&0!=(1&r));n.__initializeDigits();var o=1<>=1;0!==r;r>>=1)a=c.multiply(a,a),0!=(1&r)&&(s=null===s?a:c.multiply(s,a));return s}},{key:"multiply",value:function(e,t){if(0===e.length)return e;if(0===t.length)return t;var r=e.length+t.length;30<=e.__clzmsd()+t.__clzmsd()&&r--;var i=new c(r,e.sign!==t.sign);i.__initializeDigits();for(var n=0;nc.__absoluteCompare(e,t))return c.__zero();var r,i=e.sign!==t.sign,n=t.__unsignedDigit(0);if(1===t.length&&32767>=n){if(1===n)return i===e.sign?e:c.unaryMinus(e);r=c.__absoluteDivSmall(e,n,null)}else r=c.__absoluteDivLarge(e,t,!0,!1);return r.sign=i,r.__trim()}},{key:"remainder",value:function(e,t){if(0===t.length)throw new RangeError("Division by zero");if(0>c.__absoluteCompare(e,t))return e;var r=t.__unsignedDigit(0);if(1===t.length&&32767>=r){if(1===r)return c.__zero();var i=c.__absoluteModSmall(e,r);return 0===i?c.__zero():c.__oneDigit(i,e.sign)}var n=c.__absoluteDivLarge(e,t,!1,!0);return n.sign=e.sign,n.__trim()}},{key:"add",value:function(e,t){var r=e.sign;return r===t.sign?c.__absoluteAdd(e,t,r):0<=c.__absoluteCompare(e,t)?c.__absoluteSub(e,t,r):c.__absoluteSub(t,e,!r)}},{key:"subtract",value:function(e,t){var r=e.sign;return r===t.sign?0<=c.__absoluteCompare(e,t)?c.__absoluteSub(e,t,r):c.__absoluteSub(t,e,!r):c.__absoluteAdd(e,t,r)}},{key:"leftShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?c.__rightShiftByAbsolute(e,t):c.__leftShiftByAbsolute(e,t)}},{key:"signedRightShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?c.__leftShiftByAbsolute(e,t):c.__rightShiftByAbsolute(e,t)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(e,t){return 0>c.__compareToBigInt(e,t)}},{key:"lessThanOrEqual",value:function(e,t){return 0>=c.__compareToBigInt(e,t)}},{key:"greaterThan",value:function(e,t){return 0(e=a(e)))throw new RangeError("Invalid value: not (convertible to) a safe integer");if(0===e)return c.__zero();if(e>=c.__kMaxLengthBits)return t;var r=0|(e+29)/30;if(t.length(e=a(e)))throw new RangeError("Invalid value: not (convertible to) a safe integer");if(0===e)return c.__zero();if(t.sign){if(e>c.__kMaxLengthBits)throw new RangeError("BigInt too big");return c.__truncateAndSubFromPowerOfTwo(e,t,!1)}if(e>=c.__kMaxLengthBits)return t;var r=0|(e+29)/30;if(t.length>>i)return t}return c.__truncateToNBits(e,t)}},{key:"ADD",value:function(e,t){if(e=c.__toPrimitive(e),t=c.__toPrimitive(t),"string"==typeof e)return"string"!=typeof t&&(t=t.toString()),e+t;if("string"==typeof t)return e.toString()+t;if(e=c.__toNumeric(e),t=c.__toNumeric(t),c.__isBigInt(e)&&c.__isBigInt(t))return c.add(e,t);if("number"==typeof e&&"number"==typeof t)return e+t;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(e,t){return c.__compare(e,t,0)}},{key:"LE",value:function(e,t){return c.__compare(e,t,1)}},{key:"GT",value:function(e,t){return c.__compare(e,t,2)}},{key:"GE",value:function(e,t){return c.__compare(e,t,3)}},{key:"EQ",value:function(e,t){for(;;){if(c.__isBigInt(e))return c.__isBigInt(t)?c.equal(e,t):c.EQ(t,e);if("number"==typeof e){if(c.__isBigInt(t))return c.__equalToNumber(t,e);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("string"==typeof e){if(c.__isBigInt(t))return null!==(e=c.__fromString(e))&&c.equal(e,t);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("boolean"==typeof e){if(c.__isBigInt(t))return c.__equalToNumber(t,+e);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("symbol"===r(e)){if(c.__isBigInt(t))return!1;if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else{if("object"!==r(e))return e==t;if("object"===r(t)&&t.constructor!==c)return e==t;e=c.__toPrimitive(e)}}}},{key:"NE",value:function(e,t){return!c.EQ(e,t)}},{key:"DataViewGetBigInt64",value:function(e,t){var r=!!(2>>30),u.__setDigit(2,s>>>28),u.__trim()}},{key:"DataViewSetBigInt64",value:function(e,t,r){var i=!!(3>>2,2t)n=-t-1;else{if(0===r)return-1;r--,i=e.__digit(r),n=29}var o=1<>>20)-1023,i=1+(0|r/30),n=new c(i,0>e),o=1048575&c.__kBitConversionInts[1]|1048576,s=c.__kBitConversionInts[0],a=20,u=r%30,d=0;if(u>>l,o=o<<32-l|s>>>l,s<<=32-l}else if(u===a)d=32,t=o,o=s,s=0;else{var h=u-a;d=32-h,t=o<>>32-h,o=s<>>2,o=o<<30|s>>>2,s<<=30):t=0,n.__setDigit(f,t);return n.__trim()}},{key:"__isWhitespace",value:function(e){return!!(13>=e&&9<=e)||(159>=e?32==e:131071>=e?160==e||5760==e:196607>=e?10>=(e&=131071)||40==e||41==e||47==e||95==e||4096==e:65279==e)}},{key:"__fromString",value:function(e){var t=11073741824/a)return null;var d=new c(0|(29+(a*s+u>>>c.__kBitsPerCharTableShift))/30,!1),l=10>t?t:10,h=10>=c.__kBitsPerCharTableShift;var f=[],p=[],m=!1;do{for(var g,_=0,S=0;;){if(g=void 0,o-48>>>0>>0>>0>>0>>c.__kBitsPerCharTableShift)/30;d.__inplaceMultiplyAdd(R,T,b)}while(!v)}if(n!==i){if(!c.__isWhitespace(o))return null;for(n++;n>>c-(o-=30))}if(0!==n){if(i>=e.length)throw new Error("implementation bug");e.__setDigit(i++,n)}for(;i>>1)+(85&i))>>>2)+(51&i))>>>4)+(15&i),o=t-1,s=e.__digit(r-1),a=0|(30*r-c.__clz30(s)+n-1)/n;if(e.sign&&a++,268435456>>g,h=30-g;h>=n;)u[d--]=c.__kConversionChars[l&o],l>>>=n,h-=n}var _=(l|s<>>n-h;0!==l;)u[d--]=c.__kConversionChars[l&o],l>>>=n;if(e.sign&&(u[d--]="-"),-1!==d)throw new Error("implementation bug");return u.join("")}},{key:"__toStringGeneric",value:function(e,t,r){var i=e.length;if(0===i)return"";if(1===i){var n=e.__unsignedDigit(0).toString(t);return!1===r&&e.sign&&(n="-"+n),n}var o,s,a=30*i-c.__clz30(e.__digit(i-1)),u=c.__kMaxBitsPerChar[t]-1,d=a*c.__kBitsPerCharTableMultiplier,l=1+(d=0|(d+=u-1)/u)>>1,h=c.exponentiate(c.__oneDigit(t,!1),c.__oneDigit(l,!1)),f=h.__unsignedDigit(0);if(1===h.length&&32767>=f){(o=new c(e.length,!1)).__initializeDigits();for(var p,m=0,g=2*e.length-1;0<=g;g--)p=m<<15|e.__halfDigit(g),o.__setHalfDigit(g,0|p/f),m=0|p%f;s=m.toString(t)}else{var _=c.__absoluteDivLarge(e,h,!0,!0);o=_.quotient;var S=_.remainder.__trim();s=c.__toStringGeneric(S,t,!0)}o.__trim();for(var v=c.__toStringGeneric(o,t,!0);s.lengthi?c.__absoluteLess(r):0}},{key:"__compareToNumber",value:function(e,r){if(c.__isOneDigitInt(r)){var i=e.sign,n=0>r;if(i!==n)return c.__unequalSign(i);if(0===e.length){if(n)throw new Error("implementation bug");return 0===r?0:-1}if(1o?c.__absoluteGreater(i):st)return c.__unequalSign(r);if(0===t)throw new Error("implementation bug: should be handled elsewhere");if(0===e.length)return-1;c.__kBitConversionDouble[0]=t;var i=2047&c.__kBitConversionInts[1]>>>20;if(2047==i)throw new Error("implementation bug: handled elsewhere");var n=i-1023;if(0>n)return c.__absoluteGreater(r);var o=e.length,s=e.__digit(o-1),a=c.__clz30(s),u=30*o-a,d=n+1;if(ud)return c.__absoluteGreater(r);var l=1048576|1048575&c.__kBitConversionInts[1],h=c.__kBitConversionInts[0],f=20,p=29-a;if(p!==(0|(u-1)%30))throw new Error("implementation bug");var m,g=0;if(p>>_,l=l<<32-_|h>>>_,h<<=32-_}else if(p===f)g=32,m=l,l=h,h=0;else{var S=p-f;g=32-S,m=l<>>32-S,l=h<>>=0)>(m>>>=0))return c.__absoluteGreater(r);if(s>>2,l=l<<30|h>>>2,h<<=30):m=0;var y=e.__unsignedDigit(v);if(y>m)return c.__absoluteGreater(r);if(yr&&e.__unsignedDigit(0)===t(r):0===c.__compareToDouble(e,r)}},{key:"__comparisonResultToBool",value:function(e,t){return 0===t?0>e:1===t?0>=e:2===t?0t;case 3:return e>=t}if(c.__isBigInt(e)&&"string"==typeof t)return null!==(t=c.__fromString(t))&&c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if("string"==typeof e&&c.__isBigInt(t))return null!==(e=c.__fromString(e))&&c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if(e=c.__toNumeric(e),t=c.__toNumeric(t),c.__isBigInt(e)){if(c.__isBigInt(t))return c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if("number"!=typeof t)throw new Error("implementation bug");return c.__comparisonResultToBool(c.__compareToNumber(e,t),r)}if("number"!=typeof e)throw new Error("implementation bug");if(c.__isBigInt(t))return c.__comparisonResultToBool(c.__compareToNumber(t,e),2^r);if("number"!=typeof t)throw new Error("implementation bug");return 0===r?et:3===r?e>=t:void 0}},{key:"__absoluteAdd",value:function(e,t,r){if(e.length>>30,o.__setDigit(a,1073741823&n);for(;a>>30,o.__setDigit(a,1073741823&u)}return a>>30,n.__setDigit(s,1073741823&i);for(;s>>30,n.__setDigit(s,1073741823&a)}return n.__trim()}},{key:"__absoluteAddOne",value:function(e,t){var r=2>>30,r.__setDigit(s,1073741823&n);return 0!==o&&r.__setDigitGrow(i,1),r}},{key:"__absoluteSubOne",value:function(e,t){for(var r,i=e.length,n=new c(t=t||i,!1),o=1,s=0;s>>30,n.__setDigit(s,1073741823&r);if(0!==o)throw new Error("implementation bug");for(var a=i;ai?0:e.__unsignedDigit(i)>t.__unsignedDigit(i)?1:-1}},{key:"__multiplyAccumulate",value:function(e,t,r,i){if(0!==t){for(var n=32767&t,o=t>>>15,s=0,a=0,u=0;u>>15,p=c.__imul(h,n),m=c.__imul(h,o),g=c.__imul(f,n);s=(d+=a+p+s)>>>30,d&=1073741823,s+=(d+=((32767&m)<<15)+((32767&g)<<15))>>>30,a=c.__imul(f,o)+(m>>>15)+(g>>>15),r.__setDigit(i,1073741823&d)}for(;0!==s||0!==a;i++){var _=r.__digit(i);_+=s+a,a=0,s=_>>>30,r.__setDigit(i,1073741823&_)}}}},{key:"__internalMultiplyAdd",value:function(e,t,r,i,n){for(var o=r,s=0,a=0;a>>15,t),h=d+((32767&l)<<15)+s+o;o=h>>>30,s=l>>>15,n.__setDigit(a,1073741823&h)}if(n.length>i)for(n.__setDigit(i++,o+s);i>>0,s=0|o/t,a=0|(o=((i=0|o%t)<<15|e.__halfDigit(n-1))>>>0)/t;i=0|o%t,r.__setDigit(n>>>1,s<<15|a)}return r}},{key:"__absoluteModSmall",value:function(e,t){for(var r=0,i=2*e.length-1;0<=i;i--)r=0|((r<<15|e.__halfDigit(i))>>>0)%t;return r}},{key:"__absoluteDivLarge",value:function(e,t,r,i){var n=t.__halfDigitLength(),o=t.length,s=e.__halfDigitLength()-n,a=null;r&&(a=new c(s+2>>>1,!1)).__initializeDigits();var u=new c(n+2>>>1,!1);u.__initializeDigits();var d=c.__clz15(t.__halfDigit(n-1));0>>0;m=0|_/h;for(var S=0|_%h,v=t.__halfDigit(n-2),y=l.__halfDigit(p+n-2);c.__imul(m,v)>>>0>(S<<16|y)>>>0&&(m--,!(32767<(S+=h))););}c.__internalMultiplyAdd(t,m,0,o,u);var I=l.__inplaceSub(u,p,n+1);0!==I&&(I=l.__inplaceAdd(t,p,n),l.__setHalfDigit(p+n,32767&l.__halfDigit(p+n)+I),m--),r&&(1&p?f=m<<15:a.__setDigit(p>>>1,f|m))}if(i)return l.__inplaceRightShift(d),r?{quotient:a,remainder:l}:l;if(r)return a;throw new Error("unreachable")}},{key:"__clz15",value:function(e){return c.__clz30(e)-15}},{key:"__specialLeftShift",value:function(e,t,r){var i=e.length,n=new c(i+r,!1);if(0===t){for(var o=0;o>>30-t;return 0r)throw new RangeError("BigInt too big");var i=0|r/30,n=r%30,o=e.length,s=0!==n&&0!=e.__digit(o-1)>>>30-n,a=o+i+(s?1:0),u=new c(a,e.sign);if(0===n){for(var d=0;d>>30-n;if(s)u.__setDigit(o+i,l);else if(0!==l)throw new Error("implementation bug")}return u.__trim()}},{key:"__rightShiftByAbsolute",value:function(e,t){var r=e.length,i=e.sign,n=c.__toShiftAmount(t);if(0>n)return c.__rightShiftByMaximum(i);var o=0|n/30,s=n%30,a=r-o;if(0>=a)return c.__rightShiftByMaximum(i);var u=!1;if(i)if(0!=(e.__digit(o)&(1<>>s,m=r-o-1,g=0;g>>s;l.__setDigit(m,p)}return u&&(l=c.__absoluteAddOne(l,!0,l)),l.__trim()}},{key:"__rightShiftByMaximum",value:function(e){return e?c.__oneDigit(1,!0):c.__zero()}},{key:"__toShiftAmount",value:function(e){if(1c.__kMaxLengthBits?-1:t}},{key:"__toPrimitive",value:function(e){var t=1>>a}return i.__setDigit(n,s),i.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(e,t,r){for(var i,n=Math.min,o=0|(e+29)/30,s=new c(o,r),a=0,u=o-1,d=0,l=n(u,t.length);a>>30,s.__setDigit(a,1073741823&i);for(;a>>m)-d,h&=g-1}return s.__setDigit(u,h),s.__trim()}},{key:"__digitPow",value:function(e,t){for(var r=1;0>>=1,e*=e;return r}},{key:"__isOneDigitInt",value:function(e){return(1073741823&e)===e}}]),c}(h(Array));return R.__kMaxLength=33554432,R.__kMaxLengthBits=R.__kMaxLength<<5,R.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],R.__kBitsPerCharTableShift=5,R.__kBitsPerCharTableMultiplier=1<>>0)/t)},R.__imul=e||function(e,t){return 0|e*t},R}()}(wD);var kD=wD.exports;const OD="CommandMsgManager";class PD{constructor(e,t){i(this,"RTP_HEADER_V_P_X_CC",144),i(this,"RTP_HEADER_V_P_X_CC_BRODACAST",128),this.event=e,this.remoteUserManager=t,this.cmdMsgPacketSeqNum=0}receivedCmdRtpPacketDecode(e){var t,r;const i=new DataView(e),n=i.getUint16(2),o=i.getUint32(4);iE.getLogger().debug(OD,"receive ".concat(n," msg of timeStamp ").concat(o));const s=i.getUint32(8);if(s!==this.cmdReceiveSsrc)return void iE.getLogger().error(OD,"receive msg ssrc not matched, ".concat(this.cmdReceiveSsrc," - ").concat(s));let a=0;if(0==(16&i.getUint8(0)))a=12;else{a=16+4*i.getUint16(14)}const c=kD.toNumber(kD.DataViewGetBigUint64(i,a)),u=i.buffer.slice(a+16);let d=null;d=this.msgFormat===VC.STRING?MD.ArrayBufferToMsg(u):u,this.event.emit(UC.CmdMsgReceived,{msg:d,srcUserId:null===(t=this.remoteUserManager.getUserInfoByUid(c,this.roomId))||void 0===t||null===(r=t.userInfo)||void 0===r?void 0:r.userId})}genCmdRtpPacketMsg(e){const t=!e.userUid,r=new DataView(new ArrayBuffer(t?28:44));t?r.setUint8(0,this.RTP_HEADER_V_P_X_CC_BRODACAST):r.setUint8(0,this.RTP_HEADER_V_P_X_CC),r.setUint8(1,this.RTP_HEADER_M_PT),r.setUint16(2,this.cmdMsgPacketSeqNum++),r.setUint32(4,Math.floor((new Date).getTime()/1e3)),r.setUint32(8,this.cmdSendSsrc);const{userUid:i=0,msg:n}=e;let o=0;return t?o=12:(r.setUint16(12,4096),r.setUint16(14,3),r.setUint8(16,21),r.setUint8(17,8),kD.DataViewSetBigUint64(r,18,kD.BigInt(i)),r.setUint16(26,0),o=28),kD.DataViewSetBigUint64(r,o,kD.BigInt(this.selfUserUid)),kD.DataViewSetBigUint64(r,o+8,kD.BigInt(0)),MD.concatArrayBuffer(r.buffer,MD.msgBodyToArrayBuffer(n))}sendCommandMsg(e,t,r){let i=0;var n,o;t&&(i=null===(n=this.remoteUserManager.getUserInfoById(t,r))||void 0===n||null===(o=n.userInfo)||void 0===o?void 0:o.userUid);return this.transportChannel.sendMessage(this.genCmdRtpPacketMsg({msg:e,userUid:i}))}setCommandChannelParams(e,t){this.reset(),this.RTP_HEADER_M_PT=t.tranportOptions.payload,this.roomId=e,this.msgFormat=t.msgFormat,this.cmdSendSsrc=t.tranportOptions.sendSsrc,this.cmdReceiveSsrc=t.tranportOptions.receiveSsrc,this.selfUserUid=t.tranportOptions.userUid,this.extraParamsHandle(t),this.initCmdTranportChannel()}}class MD{static msgBodyToArrayBuffer(e){if("string"==typeof e){return(new TextEncoder).encode(e).buffer}return e}static ArrayBufferToMsg(e){return new TextDecoder("utf-8").decode(e)}static concatArrayBuffer(){let e=0;for(var t=arguments.length,r=new Array(t),i=0;iawait this.wsConnectOnce(e,r,i,t)),!1,t,this.getAsyncInterval(n),this.needInterrupted())}getAsyncInterval(e){return t=>"function"==typeof(null==t?void 0:t.getCode)&&t.getCode()===Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT?0:e}needInterrupted(){return e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}async wsConnectOnce(e,t,r,i){this.close(),this.connectionId=XR.generateRandomId(32),this.websocket=new WebSocket(e),this.websocket.binaryType="arraybuffer",iE.getLogger().info(DD,"wsConnectOnce, url:".concat(XR.shieldUrlParameters(e),", begin create websocket ").concat(this.connectionId," connection with server ")),this.websocket.onopen=this.onopen.bind(this),this.websocket.onerror=this.onerror.bind(this),this.websocket.onmessage=this.onmessage.bind(this),this.websocket.onclose=this.onclose.bind(this);try{const e=1===i?t:r;await this.getConnectionResp(e,this.connectionId)}catch(jN){throw iE.getLogger().error(DD,"wsConnectOnce, connect occur exception, error: ".concat(jN)),jN}finally{this.connectionCallbacks.delete(this.connectionId)}}async getConnectionResp(e,t){await mP.callWithTimeout(new Promise(((e,r)=>{this.connectionCallbacks.set(t,(i=>{if(i.isSuccess)iE.getLogger().info(DD,"getConnectionResp, connectId:".concat(t,", connect success")),e();else{const e=Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR,n=i.code,o="".concat(n||""," websocket connect error"),s=new qc(e,o);iE.getLogger().info(DD,"getConnectionResp, connectId:".concat(t,", connect fail, errMsg=").concat(s)),r(s)}}))})),e).catch((t=>{if(t.getCode()!==Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT)throw t;throw iE.getLogger().error(DD,"getConnectionResp, websocket connect timeout after ".concat(e," ms")),this.websocket&&this.websocket.readyState===this.websocket.CONNECTING&&(iE.getLogger().info(DD,"getConnectionResp, websocket connect timeout, close webSocket manual"),this.close()),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT)})).finally((()=>{this.connectionCallbacks.delete(t)}))}onopen(){iE.getLogger().info(DD,"onopen, wss connection success."),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!0}),this.event_.emit("CMD_CHANNEL_ESTABLISHED")}onmessage(e){e.data?this.event_.emit("CMD_MSG_REVEIVED",e.data):iE.getLogger().error(DD,"onerror, websocket message is null.")}onerror(e){iE.getLogger().error(DD,"onerror, websocket occur error:".concat(JSON.stringify(e))),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!1})}async onclose(e){const t=e.code,r=e.reason;iE.getLogger().warn(DD,"onclose, code:".concat(t,", reason:").concat(r)),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!1,code:t,reason:r}),iE.getLogger().error(DD,"reconnect"),this.event_.emit("CMD_CONNECTION_RECONNECT")}sendMessage(e){if(!this.websocket)return iE.getLogger().error(DD,"send cmd message failed for websocket is null."),!1;try{return this.websocket.send(e),!0}catch(jN){return iE.getLogger().error(DD,"send cmd message failed."),!1}}close(){this.websocket&&(this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onmessage=null,this.websocket.onclose=null,this.websocket.close(),this.websocket=null,this.connectionCallbacks.clear())}}class UD extends PD{constructor(e,t){super(e,t),this.reconnctInterval=[2,5,10,20],this.reconnctIdx=0}initCmdTranportChannel(){this.transportChannel||(this.transportChannel=new ND),this.transportChannel.on("CMD_MSG_REVEIVED",(e=>{this.receivedCmdRtpPacketDecode(e)})),this.transportChannel.on("CMD_CHANNEL_ESTABLISHED",(()=>{iE.getLogger().info(DD,"cmd websocket connection established."),this.event.emit(UC.CmdChannelEstablished,BC.WEBSOCKET),this.reconnctIdx=0,this.transportChannel.sendMessage(this.genCmdBindRtpPacketMsg())})),this.transportChannel.on("CMD_CONNECTION_RECONNECT",(async()=>{if(this.reconnctIdx===this.reconnctInterval.length)iE.getLogger().info(DD,"cmd websocket connection disconnect."),this.event.emit(UC.CmdChannelDisconnect,BC.WEBSOCKET);else try{this.event.emit(UC.CmdChannelReconnecting);const e=this.reconnctInterval[Math.min(this.reconnctIdx,this.reconnctInterval.length-1)];if(iE.getLogger().error(DD,"cmd websocket reconnect wait for ".concat(e,"s.")),await XR.sleep(1e3*e),!this.transportChannel)return;this.reconnctIdx++,iE.getLogger().error(DD,"cmd websocket reconnect begin."),await this.transportChannel.wsConnect(this.cmdSocketUrl,1,1e4,1e4,500)}catch(jN){iE.getLogger().error(DD,"cmd websocket reconnect failed: ".concat(jN))}}));try{this.transportChannel.wsConnect(this.cmdSocketUrl,1,1e4,1e4,500)}catch(jN){iE.getLogger().error(DD,"cmd websocket connect failed: ".concat(jN))}}extraParamsHandle(e){this.bindCryptoKey=e.wsOptions.bindCryptoKey,this.cmdSocketUrl=e.wsOptions.wsDomain?e.wsOptions.wsUrl.replace(/(ws(s)?:\/\/)[^\/|:]+(.*)/,"$1".concat(e.wsOptions.wsDomain,"$3")):e.wsOptions.wsUrl}reset(){this.roomId=null,this.cmdSendSsrc=0,this.cmdReceiveSsrc=0,this.selfUserUid=0,this.bindCryptoKey=null,this.cmdMsgPacketSeqNum=0,this.reconnctIdx=0,this.transportChannel&&(this.transportChannel.off("CMD_MSG_REVEIVED"),this.transportChannel.off("CMD_CHANNEL_ESTABLISHED"),this.transportChannel.off("CMD_CONNECTION_RECONNECT"),this.transportChannel.close(),this.transportChannel=null)}genCmdBindRtpPacketMsg(){const e=new DataView(new ArrayBuffer(20));e.setUint8(0,this.RTP_HEADER_V_P_X_CC),e.setUint8(1,this.RTP_HEADER_M_PT),e.setUint16(2,this.cmdMsgPacketSeqNum++),e.setUint32(4,Math.floor((new Date).getTime()/1e3)),e.setUint32(8,this.cmdSendSsrc),e.setUint16(12,4096),e.setUint16(14,1),e.setUint8(16,24),e.setUint8(17,1),e.setUint8(18,0),e.setUint8(19,0);const t=MD.numberArrayToArrayBuffer(uT.exports.HmacSHA256(uT.exports.lib.WordArray.create(MD.arrayBufferToNumberArray(e)),this.bindCryptoKey).words);return MD.concatArrayBuffer(e.buffer,t)}}const xD="DataChannelMsgManager";class LD{constructor(e){this.event_=new VO,this.dataChannel=e.createDataChannel("commandMsgDataChannel",{ordered:!0}),this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=this.onopen.bind(this),this.dataChannel.onerror=this.onerror.bind(this),this.dataChannel.onmessage=this.onmessage.bind(this),this.dataChannel.onclose=this.onclose.bind(this)}on(e,t){this.event_.on(e,t)}off(e,t){t?this.event_.removeListener(e,t):this.event_.removeAllListeners(e)}sendMessage(e){var t;if(!this.dataChannel||"open"!==this.dataChannel.readyState)return iE.getLogger().error(xD,"send message with dataChannel failed for dataChannel unavaliable: ".concat(null===(t=this.dataChannel)||void 0===t?void 0:t.readyState,".")),!1;try{return this.dataChannel.bufferedAmount>=1024e6&&iE.getLogger().warn(xD,"buffer over high threshold of 1M: ".concat(this.dataChannel.bufferedAmount,", send message may blocked and delay.")),this.dataChannel.send(e),!0}catch(jN){return iE.getLogger().error(xD,"send message with dataChannel occur error: ".concat(jN,".")),!1}}close(){this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onerror=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel.close(),this.dataChannel=null)}onopen(){iE.getLogger().info(xD,"onopen, RTCDataChannel connection status: ".concat(this.dataChannel.readyState)),clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_ESTABLISHED")}onmessage(e){e.data?this.event_.emit("CMD_MSG_REVEIVED",e.data):iE.getLogger().error(xD,"onerror, RTCDataChannel message is null.")}onerror(e){iE.getLogger().error(xD,"onerror, RTCDataChannel occur error: ".concat(e)),this.dataChannelDisConnectTimer||(this.dataChannelDisConnectTimer=setTimeout((()=>{clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_DISCONNECT")}),3e4))}onclose(e){iE.getLogger().info(xD,"onclose, RTCDataChannel closed: ".concat(e)),this.dataChannelDisConnectTimer||(this.dataChannelDisConnectTimer=setTimeout((()=>{clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_DISCONNECT")}),3e4))}}class BD extends PD{initCmdTranportChannel(){this.transportChannel||(this.transportChannel=new LD(this.connection)),this.transportChannel.on("CMD_MSG_REVEIVED",(e=>{super.receivedCmdRtpPacketDecode(e)})),this.transportChannel.on("CMD_CHANNEL_ESTABLISHED",(()=>{iE.getLogger().info(xD,"cmd dataChannel connection established."),this.event.emit(UC.CmdChannelEstablished,BC.DATA_CHANNEL)})),this.transportChannel.on("CMD_CHANNEL_DISCONNECT",(()=>{iE.getLogger().info(xD,"cmd dataChannel connection disconnect."),this.event.emit(UC.CmdChannelDisconnect,BC.DATA_CHANNEL)}))}extraParamsHandle(e){this.connection=e.dataChannelOptions.connection}reset(){this.roomId=null,this.cmdSendSsrc=0,this.cmdReceiveSsrc=0,this.selfUserUid=0,this.cmdMsgPacketSeqNum=0,this.transportChannel&&(this.transportChannel.off("CMD_MSG_REVEIVED"),this.transportChannel.off("CMD_CHANNEL_ESTABLISHED"),this.transportChannel.close(),this.transportChannel=null)}}var VD,YD,jD,FD,HD,KD,zD,WD,GD,JD,qD,XD,QD,$D,ZD,eN,tN,rN,iN,nN,oN,sN,aN,cN,uN,dN,lN,hN,fN,pN,mN,gN,_N,SN,vN,yN,IN,TN;const RN=1e4;var EN=function(e){return e[e.mute=0]="mute",e[e.unmute=1]="unmute",e[e.noChange=2]="noChange",e}(EN||{});const bN={FHD:CC.main,HD:CC.middle1,SD:CC.middle2,LD:CC.slides},CN="Client";let AN=(VD=fP("Client$enableTopThreeAudioMode#boolean#boolean"),YD=lP("".concat(CN,"_switchAudioMode")),jD=fP("Client$getConnectionState#string"),FD=fP("Client$setNetworkBandwidth#void#NetworkBandwidth"),HD=hP("Client$join#Promise#string#JoinConfig"),KD=hP("Client$enableRtcStats#Promise#boolean#number"),zD=hP("Client$leave#Promise"),WD=hP("Client$publish#Promise#Stream#PublishOption"),GD=lP("".concat(CN,"_publishImpl")),JD=hP("Client$unpublish#Promise#Stream"),qD=hP("Client$subscribeAudio#Promise#string"),XD=hP("Client$unSubscribeAudio#Promise#string"),QD=hP("Client$subscribe#Promise#RemoteStream#SubscribeOption"),$D=hP("Client$batchSubscribe#Promise#SubscribeParam[]"),ZD=hP("Client$unsubscribe#Promise#Stream#SubscribeOption"),eN=hP("Client$switchRole#Promise#number#Authorization"),tN=lP("".concat(CN,"_refreshRemoteStreamList")),rN=lP("".concat(CN,"_updateRemoteStream")),iN=lP("".concat(CN,"_removeRemoteStream")),nN=lP("".concat(CN,"_handleWatchMsg")),oN=lP("".concat(CN,"_refreshRoomUserInfos")),sN=fP("Client$setVolume4TopThree#void#number"),aN=fP("Client$muteAudio4TopThree#void#boolean"),cN=hP("Client$setAudioOutput4TopThree#void"),uN=fP("Client$isTopNAudioMuted#boolean"),dN=hP("Client$changeUserName#Promise#string"),lN=hP("Client$startLiveStreaming#Promise#string#string[]#PublishConfig#UserConfig[]"),hN=hP("Client$updateLiveStreaming#Promise#string#string[]#PublishConfig#UserConfig[]"),fN=hP("Client$stopLiveStreaming#Promise#string"),pN=fP("Client$setProxyServer#void#string"),mN=fP("Client$setTurnServer#void#TurnServerConfig"),gN=hP("Client$addMultiRoomMediaRelay#Promise#MultiRoomMediaRelayInfo"),_N=hP("Client$stopMultiRoomMediaRelay#Promise#MultiRoomMediaRelayInfo"),SN=fP("Client$addRelayClient#Client#string"),vN=hP("Client$stopRelayClient#Promise#string"),yN=fP("Client$enableCommandMsg#boolean#boolean"),IN=fP("Client$renewSignature#boolean#ctime#signature"),TN=class e extends $P{constructor(e,t){super({logger:!0,stat:!0,emitter:!0,config:e}),i(this,"status",OC.Idle),i(this,"localRejoinFlag",!1),i(this,"resolutionChangeInfo",{mainResolutionChangeTimer:null,auxResolutionChangeTimer:null,preVideoHeight:new Map}),this.clientSymbol=Symbol("".concat(CN,"_").concat(QP.getSequence())),t&&(this.mainRelayRoomSymbol=t),this.locker=new aP,this.roomId="",this.clientConfig=e,this.userInfo=void 0,this.waitConfigCallbackFunc=void 0,this.topNAudioVolume=100,this.audioPolicy=IO.USER_SUBSCRIBE_AUDIOPOLICY,this.connectState={prevState:"DISCONNECTED",curState:"DISCONNECTED"},this.logger.info(CN,"HRTC VERSION = ".concat(uA,", userAgent = ").concat(navigator.userAgent)),this.top3VolumeUserIds=[],LO.initDeviceChangedNotify(this.eventEmitter,!1),this.accessManager=new fD(this.logger),this.lastCycleFrameDecodedMap=new Map,this.streamInterruptedUsersMap=new Map,this.streamDetectionCriterion=0,this.audioStreams4TopN=new MM,this.downLinkData=null,this.upLinkData=null,this.preNetQuality=null,this.remoteUserManager=new vD(this),this.stat.setRemoteUserManager(this.remoteUserManager),this.connectionsManager=new nD(this.logger,this.stat,this.eventEmitter),this.streamPublishManager=new NM,this.audioLevelInterval=1e3,this.isLoopRejoining=!1,this.upStreamData=null,this.sdpRepInfo=null,this.startupQoSMap=new Map,this.initReport4WindowEvent(),this.cmdMsgAbility={enable:!1,cmdManager:null,msgFormat:VC.STRING},this.roomStreamStatus={},this.isSignatureExpired=!1,this.pktsLostRate={up:0,down:0,preDownRate:[],preRTT:0}}initReport4WindowEvent(){window.onunload=()=>{var e,t;const r=XR.getCurrentTimestamp();null===(e=this.stat)||void 0===e||e.recordCallbackInfoBeacon("window-onunload",null===(t=this.getInfo())||void 0===t?void 0:t.moduleName,r,r,{event:"window-onunload"},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))},window.onbeforeunload=()=>{var e,t;const r=XR.getCurrentTimestamp();null===(e=this.stat)||void 0===e||e.recordCallbackInfoBeacon("window-onbeforeunload",null===(t=this.getInfo())||void 0===t?void 0:t.moduleName,r,r,{event:"window-onbeforeunload"},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))},window.onhashchange=e=>{var t,r;const i=XR.getCurrentTimestamp();null===(t=this.stat)||void 0===t||t.recordCallbackInfoBeacon("window-onhashchange",null===(r=this.getInfo())||void 0===r?void 0:r.moduleName,i,i,{event:"window-onhashchange",newURL:(null==e?void 0:e.newURL)||"",oldURL:(null==e?void 0:e.oldURL)||""},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))}}getSessionStatus(){return this.status}on(e,t){super.on(e,t,![UC.VolumeIndicator,UC.TransportStats].includes(e.toString()))}off(e,t){super.off(e,t,![UC.VolumeIndicator,UC.TransportStats].includes(e.toString()))}getSymbol(){return this.identifiedID}getInfo(){var e,t;return{moduleName:"Client",appId:this.clientConfig.appId,roomId:this.roomId,userName:null===(e=this.userInfo)||void 0===e?void 0:e.userName,userId:null===(t=this.userInfo)||void 0===t?void 0:t.userId,domain:this.clientConfig.domain,upStreamData:this.upStreamData,sdpRepInfo:this.sdpRepInfo,countryCode:this.clientConfig.countryCode}}enableTopThreeAudioMode(e){return this.enableTopThreeAudioModeImpl(e)}enableTopThreeAudioModeImpl(e){let t=!1;return e&&this.status===OC.Idle&&(this.audioPolicy=IO.TOPN_AUDIOPOLICY,t=!0),t}async switchAudioMode(e){try{if(e!==TO.TOPN_AUDIOPOLICY&&e!==TO.USER_SUBSCRIBE_AUDIOPOLICY)throw this.logger.error(CN,"audioMode is invalid"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e%=2,this.logger.info(CN,"switchAudioMode start, new audioPolicy: ".concat(e,", original audioPolicy: ").concat(this.audioPolicy)),this.status===OC.Joined&&(e===IO.USER_SUBSCRIBE_AUDIOPOLICY&&this.audioPolicy===IO.TOPN_AUDIOPOLICY?(this.audioPolicy=e,await this.switchAudioPolicyTop2User()):e===IO.TOPN_AUDIOPOLICY&&this.audioPolicy===IO.USER_SUBSCRIBE_AUDIOPOLICY&&(this.audioPolicy=e,await this.switchAudioPolicyUser2Top(),this.top3VolumeUserIds&&this.top3VolumeUserIds.length>0&&this.eventEmitter.emit(UC.VolumeIndicator,{userVolumeInfos:this.top3VolumeUserIds}))),this.stat.getMediaStat().setAudioPolicy(this.audioPolicy),this.audioPolicy===IO.USER_SUBSCRIBE_AUDIOPOLICY?TO.USER_SUBSCRIBE_AUDIOPOLICY:TO.TOPN_AUDIOPOLICY}catch(jN){this.logger.error(CN,"switchAudioMode, audioPolicy: ".concat(e,", error: ").concat(jN))}return this.audioPolicy}async switchAudioPolicyTop2User(){await this.signal.changeAudioPolicy(IO.USER_SUBSCRIBE_AUDIOPOLICY),await this.unsubscribeAudio4Top();const e=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,vO.TRACK_TYPE_VIDEO);for(const t of e){const e=t.mainStream.tracks;for(const t of e)t.isSubscribed&&await this.resubscribeUserAudio()}}async resubscribeUserAudio(){this.logger.info(CN,"resubscribeUserAudio start");const e=this.remoteUserManager.resubscribeMainStreamAudio(this.roomId);await this.updateSubscribe(e),null==e||e.forEach((e=>{var t,r,i,n;(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Subscribe)||void 0===r?void 0:r.length)>0&&(null===(i=e.mainStream)||void 0===i||null===(n=i.remoteStream)||void 0===n||n.rePlayAudio())}))}async switchAudioPolicyUser2Top(){await this.unsubscribeAudio4SubscribeUsers(),await this.signal.changeAudioPolicy(IO.TOPN_AUDIOPOLICY),this.remoteUserManager.enableTopThreeAudioMode(this.roomId),await this.connectionsManager.generateAndSetOfferSdpByHandler(yO.STREAM_TYPE_MAIN),await this.connectionsManager.generateAndSetAnswerSdpByHandler(yO.STREAM_TYPE_MAIN,this.addSsrc4Top3.bind(this))}async unsubscribeAudio4SubscribeUsers(){this.logger.info(CN,"unsubscribeAudio4SubscribeUsers start");const e=this.remoteUserManager.unsubscribeAllMainStreamAudio(this.roomId);await this.updateSubscribe(e)}async unsubscribeAudio4Top(){await this.unsubscribeUsersAudio()}async unsubscribeAudio4SubscribeAll(){await this.unsubscribeUsersAudio()}async unsubscribeUsersAudio(){const e=[];for(const t of this.audioStreams4TopN.getAudioStreams()){const r=t.ssrc;this.audioStreams4TopN.close(t.streamId),this.logger.info(CN,"delete audio ssrc:".concat(r)),e.push(r)}e.length>0&&await this.connectionsManager.deleteUser(yO.STREAM_TYPE_MAIN,null,e)}async getLocalAudioStats(){const e=new Map,t=this.streamPublishManager.getPublishedMainAudioTrackInfo();if(!t)return this.logger.error(CN,"local stream has not published yet."),e;if("function"!=typeof t.sender.getStats)return this.logger.error(CN,"audio rtpsender is not support getStat"),e;const r={bytesSent:0,packetsSent:0},i=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN),n=this.userInfo.userId||(null==i?void 0:i.getUserId()),o=OO.getLatestStats(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(pC,"_").concat(t.ssrc));return o&&(r.bytesSent=o.bytesSent,r.packetsSent=o.packetsSent,e.set(n,r)),e}async getLocalVideoStats(){const e=new Map,t={mainStream:[],subStream:null};let r=null,i=null;const n=this.streamPublishManager.getMainStreamVideoPublishInfo();if(n){const i=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN),o=this.userInfo.userId||(null==i?void 0:i.getUserId());for(const s of n){r={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0};const i=OO.getLatestStats(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(s.ssrc));i&&(r.bytesSent=XR.getValue(i.bytesSent,0),r.packetsSent=XR.getValue(i.packetsSent,0),r.framesEncoded=XR.getValue(i.framesEncoded,0),r.framesSent=XR.getValue(i.framesSent,0),r.frameWidth=XR.getValue(i.frameWidth,0),r.frameHeight=XR.getValue(i.frameHeight,0),e.has(o)?e.get(o).mainStream.push(r):(t.mainStream.push(r),e.set(o,t)))}}else this.logger.debug(CN,"have no local mainstream collect stats");const o=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(o&&"function"==typeof o.sender.getStats){const r=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN),n=this.userInfo.userId||(null==r?void 0:r.getUserId());i={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0};const s=OO.getLatestStats(this.userInfo.roomId,yO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(o.ssrc));s&&(i.bytesSent=XR.getValue(s.bytesSent,0),i.packetsSent=XR.getValue(s.packetsSent,0),i.framesEncoded=XR.getValue(s.framesEncoded,0),i.framesSent=XR.getValue(s.framesSent,0),i.frameWidth=XR.getValue(s.frameWidth,0),i.frameHeight=XR.getValue(s.frameHeight,0),e.has(n)?e.get(n).subStream=i:(t.subStream=i,e.set(n,t)))}else this.logger.debug(CN,"have no local substream collect stats");return e}async getRemoteAudioStats(){const e=new Map,t=this.remoteUserManager.getAllUserStreamsByType(this.roomId,yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO),r=this.connectionsManager.getReceivers(yO.STREAM_TYPE_MAIN);if(!r||0===r.length)return this.logger.error(CN,"getRemoteAudioStats, peerConnection is not support getReceivers"),e;for(const i of t){const t=i.userId;if(i.mainStream)for(const r of i.mainStream.tracks){const i={bytesReceived:0,packetsReceived:0,packetsLost:0},n=OO.getLatestStats(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(hC,"_").concat(r.cssrc));t&&n&&(i.bytesReceived=XR.getValue(n.bytesReceived,0),i.packetsReceived=XR.getValue(n.packetsReceived,0),i.packetsLost=XR.getValue(n.packetsLost,0),this.connectionsManager.calcChangedStatistic(n.id,i,["bytesReceived","packetsReceived","packetsLost"]),e.set(t,i))}}return e}async getRemoteVideoStats(){const e=new Map,t=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,vO.TRACK_TYPE_VIDEO);for(const r of t)r.mainStream&&await this.getRemoteVideoTracksStatistic(r.userId,yO.STREAM_TYPE_MAIN,!1,r.mainStream.tracks,e),r.auxStream&&await this.getRemoteVideoTracksStatistic(r.userId,yO.STREAM_TYPE_AUX,!0,r.auxStream.tracks,e);return e}isSendingStream(){var e,t;const r=(null===(e=this.connectionsManager.getSenders(yO.STREAM_TYPE_MAIN))||void 0===e?void 0:e.length)>0,i=(null===(t=this.connectionsManager.getSenders(yO.STREAM_TYPE_AUX))||void 0===t?void 0:t.length)>0;return r||i}isReceivingStream(){var e,t;const r=(null===(e=this.connectionsManager.getReceivers(yO.STREAM_TYPE_MAIN))||void 0===e?void 0:e.length)>0,i=(null===(t=this.connectionsManager.getReceivers(yO.STREAM_TYPE_AUX))||void 0===t?void 0:t.length)>0;return r||i}async getRemoteVideoTracksStatistic(e,t,r,i,n){if(i&&0!==i.length)for(const o of i){const i=OO.getLatestStats(this.userInfo.roomId,r?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,"".concat(fC,"_").concat(o.cssrc));if(!i)continue;const s={streamId:o.trackId,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0,frameWidth:0,frameHeight:0,frameRate:0,frameDropped:0};if(s.bytesReceived=XR.getValue(i.bytesReceived,0),s.packetsReceived=XR.getValue(i.packetsReceived,0),s.packetsLost=XR.getValue(i.packetsLost,0),s.framesDecoded=XR.getValue(i.framesDecoded,0),s.frameDropped=XR.getValue(i.framesDropped,0),s.frameRate=XR.getValue(i.framesPerSecond,0),s.frameWidth=i.frameWidth,s.frameHeight=i.frameHeight,this.connectionsManager.calcChangedStatistic(i.id,s,["bytesReceived","packetsReceived","packetsLost","framesDecoded"]),s.frameWidth&&s.frameHeight){const e=i.trackId;if(e){const t=OO.getLatestStats(this.userInfo.roomId,r?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN,e)||{frameWidth:0,frameHeight:0};s.frameWidth=t.frameWidth,s.frameHeight=t.frameHeight}}if(n.has(e))t===yO.STREAM_TYPE_AUX?n.get(e).subStream=s:n.get(e).mainStream.push(s);else{const r={mainStream:[],subStream:null};t===yO.STREAM_TYPE_AUX?r.subStream=s:r.mainStream.push(s),n.set(e,r)}}}async getDownloadStatistic(e){const t=new Map,r=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,e);for(const a of r)await this.getTrackDownloadStatistic([...a.mainStream.tracks,...a.auxStream.tracks],t);if(0===t.size)return this.downLinkData=null,-1;let i=0,n=0,o=0;for(const[a,c]of t)if(this.downLinkData&&this.downLinkData.has(a)){const e=c.packetsReceived-this.downLinkData.get(a).packetsReceived;e>0&&(n+=e,i+=Math.max(c.packetsLost-this.downLinkData.get(a).packetsLost,0),o+=Math.max(c.nackCount-this.downLinkData.get(a).nackCount,0))}else n+=c.packetsReceived,i+=c.packetsLost,o+=c.nackCount;let s=0;if(n<=0)s=-1;else{let e=1e3*this.connectionsManager.getConnectionRTT();e?this.pktsLostRate.preRTT=e:e=this.pktsLostRate.preRTT,s=e<=40?100*o/(o+n):e<=60?.9*o*100/(.9*o+n):e<=100?.8*o*100/(.8*o+n):e<=150?.7*o*100/(.7*o+n):.6*o*100/(.6*o+n),s=Math.min(Math.max(100*i/(i+n),s),100)}return this.downLinkData=t,this.logger.debug(CN,"downLinkData packetsLost:".concat(i,", packetsReceived:").concat(n,",rate:").concat(s)),s}async getTrackDownloadStatistic(e,t){for(const r of e){const e=r.type===vO.TRACK_TYPE_VIDEO?"".concat(fC):"".concat(hC),i=OO.getLatestStats(this.userInfo.roomId,r.streamType,"".concat(e,"_").concat(r.cssrc)),n={packetsReceived:0,packetsLost:0,nackCount:0};i&&(n.packetsReceived=XR.getValue(i.packetsReceived,0),n.packetsLost=XR.getValue(i.packetsLost,0),n.nackCount=XR.getValue(i.nackCount,0),this.connectionsManager.calcChangedStatistic(i.id,n),t.set(r.cssrc.toString(),n))}}static getSenderType(e,t){return"audio"===e||t&&t.sender?yO.STREAM_TYPE_MAIN:yO.STREAM_TYPE_AUX}async getUploadStatistic(t){var r,i;const n=this.streamPublishManager.getPublishedMainVideoTrackInfo(),o=this.streamPublishManager.getPublishedMainAudioTrackInfo(),s=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(!n&&!o&&!s)return-1;const a={packetsLost:0,packetsSent:0,fractionLost:0},c=t===vO.TRACK_TYPE_VIDEO?"".concat(mC):"".concat(pC),u=t===vO.TRACK_TYPE_VIDEO?(null==n?void 0:n.ssrc)||(null==s?void 0:s.ssrc):null==o?void 0:o.ssrc;if(u){const r=OO.getLatestStats(this.userInfo.roomId,e.getSenderType(t,n),"".concat(c,"_").concat(u));if(r&&(a.packetsSent=XR.getValue(r.packetsSent,0),r.remoteId)){const r=t===vO.TRACK_TYPE_VIDEO?"".concat(_C):"".concat(gC),i=OO.getLatestRemoteInboundStats(this.userInfo.roomId,e.getSenderType(t,n),"".concat(r,"_").concat(u));a.packetsLost=XR.getValue(null==i?void 0:i.packetsLost,0),a.fractionLost=XR.getValue(null==i?void 0:i.fractionLost,0)}}let d=0,l=0;this.upLinkData?(l=a.packetsSent-this.upLinkData.packetsSent,d=a.packetsLost-this.upLinkData.packetsLost):(l=a.packetsSent,d=a.packetsLost);const h=(null===(r=this.upLinkData)||void 0===r?void 0:r.deltaPacketsSend)||0,f=(null===(i=this.upLinkData)||void 0===i?void 0:i.deltaPacketsLost)||0;this.upLinkData=a,d<=0?(l=h||this.upLinkData.packetsSent,d=f||this.upLinkData.packetsLost):(this.upLinkData.deltaPacketsSend=l,this.upLinkData.deltaPacketsLost=d);const p=l>0?Math.max(d/l*100,100*(a.fractionLost||0)):-1;return this.logger.debug(CN,"upLinkData packetsLost:".concat(a.packetsLost," ").concat(d," ").concat(100*(a.fractionLost||0),", packetssend:").concat(l,", rate:").concat(p)),p}getConnectionState(){return this.connectState.curState}async getTransportStats(){const e=this.stat.getMediaStat().getTransportMediaStats(),t=this.streamPublishManager.getPublishedMainVideoTrackInfo();if(t){const r=OO.getLatestStats(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(_C,"_").concat(t.ssrc))||{};e.rtt=1e3*(r.roundTripTime||0)}else e.rtt=1e3*this.connectionsManager.getConnectionRTT();return e.upPktsLostRate=this.pktsLostRate.up,e.downPktsLostRate=this.pktsLostRate.down,e}transportStatsRegularReport(){clearTimeout(this.transportStatsTimer),this.transportStatsTimer=setTimeout((()=>{clearTimeout(this.transportStatsTimer),this.calcPktsLostRate().then((async()=>{const e=await this.getTransportStats();if(e.downVideoStreams=await this.getRemoteVideoStats(),this.predownVideoStreams)for(const a of e.downVideoStreams.keys()){var t;for(const t of(null===(r=e.downVideoStreams.get(a))||void 0===r?void 0:r.mainStream)||[]){var r,i;const e=((null===(i=this.predownVideoStreams.get(a))||void 0===i?void 0:i.mainStream)||[]).find((e=>e.streamId===t.streamId));t.bitrate=e?8*Math.max(t.bytesReceived-e.bytesReceived,0):t.bytesReceived,t.frameRate=t.frameRate||(e?Math.max(t.framesDecoded-e.framesDecoded,0):t.framesDecoded)}const o=null===(t=e.downVideoStreams.get(a))||void 0===t?void 0:t.subStream;if(o){var n;const e=null===(n=this.predownVideoStreams.get(a))||void 0===n?void 0:n.subStream;o.bitrate=e?8*Math.max(o.bytesReceived-e.bytesReceived,0):o.bytesReceived,o.frameRate=o.frameRate||(e?Math.max(o.framesDecoded-e.framesDecoded,0):o.framesDecoded)}}else for(const a of e.downVideoStreams.keys()){var o;for(const r of(null===(s=e.downVideoStreams.get(a))||void 0===s?void 0:s.mainStream)||[]){var s;r.bitrate=0}const t=null===(o=e.downVideoStreams.get(a))||void 0===o?void 0:o.subStream;t&&(t.bitrate=0)}this.predownVideoStreams=e.downVideoStreams,this.eventEmitter.emit(UC.TransportStats,e)})).finally(this.transportStatsRegularReport.bind(this,this.predownVideoStreams))}),1e3)}getICETransportStat(e){return this.connectionsManager.getICETransportStat(e)}cleanTransportStats(){this.stat.clearMediaStatBytes()}setNetworkBandwidth(e){if((null==e?void 0:e.maxBandwidth)PC.MAX_BAND_WIDTH)throw this.logger.info(CN,"MaxBandWidth Limits [3072Kpbs, 51200Kpbs]"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.bandwidthParam={maxBandwidth:1e3*(null==e?void 0:e.maxBandwidth)||PC.DEFAULT_BANDWIDTH_4M}}async join(e,t){return await this.joinImpl(e,t)}async joinImpl(e,t){iE.addPrivacyString(null==t?void 0:t.userId),iE.addPrivacyString(null==t?void 0:t.userName),iE.addPrivacyString(null==t?void 0:t.signature),this.logger.info(CN,"join room roomId:".concat(e," userId:").concat(t.userId," role:").concat(t.role));const r=[];let i="";this.roomId=e;try{var n,o,s,a;if(this.status!==OC.Idle)throw this.logger.error(CN,"room status error!"),this.stat.reportJoinInfo(jC.ROOM_NOT_AVAILABLE,void 0,!1,void 0,"room status error!"),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR);TA.checkJoinParams(e,t),this.mainRelayRoomSymbol&&ED.roleValidCheck4RelayRoom(this,t.role);const c=uM.init(this.identifiedID,e,t);this.userInfo=c;const u=await this.accessManager.getAccessInfo(this.clientConfig.countryCode,r);this.stat.getMediaStat().setAudioPolicy(this.audioPolicy),this.stat.setLocalUserInfo(c),await this.locker.lock("".concat(CN,":joinImpl")),this.newSignal(u),this.signalEvent(),this.status=OC.Joining,i=await this.signal.connect(c,r),this.logger.info(CN,"joinImpl, actualAcsIp:".concat(i)),await this.waitNotifyConfig(r),await this.connectionsManager.initConnectionAndSdp(this.roomId,yO.STREAM_TYPE_MAIN,{onTrackHandler:this.onTrackHandler.bind(this)}),await this.connectionsManager.initConnectionAndSdp(this.roomId,yO.STREAM_TYPE_AUX,{onTrackHandler:this.onTrackHandler.bind(this)});const d=await this.connectionsManager.modifySdpInfo(yO.STREAM_TYPE_MAIN,this.cmdMsgAbility.enable),l=await this.connectionsManager.modifySdpInfo(yO.STREAM_TYPE_AUX),h=await this.signal.join(this.userInfo,d,l,this.audioPolicy,null===(n=this.bandwidthParam)||void 0===n?void 0:n.maxBandwidth,this.connectionsManager.getPortType(),this.cmdMsgAbility.enable,this.sfuConfigs);!this.clientConfig.countryCode&&h.countryCode&&this.accessManager.setOpsUrl(h.countryCode),this.sdpRepInfo=h.sdp,h.userInfos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(e.userId,e.userEid)})),null!=h&&h.userEid&&this.stat.getMediaStat().setEncryInfo(this.userInfo.userId,h.userEid.toString());const f=String(h.roomUid);this.stat.setRoomUid(f);const p=null===(o=h.roomStreamStatus)||void 0===o?void 0:o.audience;let m;m=this.audioPolicy===IO.TOPN_AUDIOPOLICY?async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(h,r,i,n),p===YC.PAUSE&&this.userInfo.role===nM?{answerSdp:t}:await this.addSsrc4Top3(t)}:async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(h,r,i,n),{answerSdp:t}};const g=null===(s=h.negSdp.find((e=>e.type===RM.MAIN)))||void 0===s?void 0:s.sdp,_=null===(a=h.negSdp.find((e=>e.type===RM.DESKTOP)))||void 0===a?void 0:a.sdp;this.connectionsManager.setSsrcsMapping(this.sdpRepInfo),await this.connectionsManager.handleAnswerSdpFromServer(yO.STREAM_TYPE_MAIN,g,m),await this.connectionsManager.handleAnswerSdpFromServer(yO.STREAM_TYPE_AUX,_),await this.handleRoomStreamStatus(p),this.upStreamData=h.userInfos.find((e=>{var t;return e.userId===(null===(t=this.userInfo)||void 0===t?void 0:t.userId)})),this.remoteUserManager.initialize(this.userInfo.userId,h.sdp),this.stat.setSFUAddress(this.connectionsManager.getSfuInfoFromSdp(g,_)),this.signal.keepAlive(),this.status=OC.Joined,this.logger.info(CN,"join room success"),this.streamPublishManager.setSdpRepInfo(this.sdpRepInfo),this.statJoinRoomInfo(i,!1,r),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.transportStatsRegularReport(),this.setAudioLevelStatTimer(),ED.addConnectionCache(this.mainRelayRoomSymbol||this.clientSymbol,this.roomId,this),await this.doRefreshRoomUserInfos(this.userInfo.roomId,h.userInfos,!1),this.locker.unlock("".concat(CN,":joinImpl"))}catch(jN){throw this.locker.unlock("".concat(CN,":joinImpl")),this.logger.error(CN,"join occur error: ".concat(jN)),this.cleanup(),this.stat.reportJoinInfo(null==jN?void 0:jN.code,i,!1,r,null==jN?void 0:jN.message),await TD.uploadLogFile(this),jN}}reportLogs(){TD.uploadLogFile(this).then((()=>{this.eventEmitter.emit(UC.LogUploaded,{status:200})})).catch((e=>{this.logger.error(CN,"reportLogs occur error: ".concat(e)),this.eventEmitter.emit(UC.LogUploaded,{status:500})}))}statJoinRoomInfo(e,t,r){this.stat.reportJoinInfo(0,e,t,r,""),this.stat.getMediaStat().setConnectionsManager(this.connectionsManager),OO.addConnection(this.userInfo.roomId,this.connectionsManager),this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos()),this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo()),this.stat.startMediaCollector()}async enableRtcStats(e,t){return await this.enableRtcStatsImpl(e,t)}async enableRtcStatsImpl(e,t){if(this.status!==OC.Joined)throw this.logger.error(CN,"cannot enableRtcStats before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot enableRtcStats before join room");if(!e)return clearTimeout(this.rtcStatsInterval),this.rtcStatsInterval=null,void this.logger.info(CN,"enableRtcStats is disable");if(!Number.isInteger(t)||t<100)throw this.logger.error(CN,"invalid interval"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e&&this.rtcStatsInterval)throw this.logger.error(CN,"enableRtcStats has been invoked, no need do again"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"enableRtcStats has been invoked, no need do again");return this.rtcStatsCriterion=t,this.doEnableRtcStats()}async doEnableRtcStats(){let e=0;const t=()=>{this.rtcStatsInterval=setTimeout((async()=>{const r=(await this.stat.buildRtcStatsDebugInfo(this.rtcStatsCriterion/1e3)).mediaStatsDebugInfo;this.doTriggerRtcStats(r,e),e++,t()}),0===e?0:this.rtcStatsCriterion)};t()}doTriggerRtcStats(e,t){if(0===t)return;if(!e||0==e.length)return;const r=[];e.forEach((e=>{if(!e.event)return;const t=e.streams||[];switch(e.event){case ZC.QoS_UP_STREAM_VIDEO:this.addRtcStatInfos(t,!1,vO.TRACK_TYPE_VIDEO,r);break;case ZC.QoS_UP_STREAM_AUDIO:this.addRtcStatInfos(t,!1,vO.TRACK_TYPE_AUDIO,r,CC.main);break;case ZC.QoS_AUX_UP_STREAM_VIDEO:this.addRtcStatInfos(t,!1,vO.TRACK_TYPE_VIDEO,r,CC.desktop);break;case ZC.QoS_DOWN_STREAM_VIDEO:this.addRtcStatInfos(t,!0,vO.TRACK_TYPE_VIDEO,r);break;case ZC.QoS_DOWN_STREAM_AUDIO:this.addRtcStatInfos(t,!0,vO.TRACK_TYPE_AUDIO,r,CC.main);break;case ZC.QoS_AUX_DOWN_STREAM_VIDEO:this.addRtcStatInfos(t,!0,vO.TRACK_TYPE_VIDEO,r,CC.desktop);break;default:this.logger.debug(CN,"".concat(e.event," no need stats"))}})),this.connectState.curState===vC[yC.CONNECTED]&&r.length>0&&this.eventEmitter.emit(UC.RtcStats,r)}addRtcStatInfos(e,t,r,i,n){let o={};const s=this.userInfo.userName||this.userInfo.userId;for(let v=0;v{this.logger.info(CN,"leave room"),this.status!==OC.Joined&&this.status!==OC.Rejoining?t(new qc(Gc.RTC_ERR_CODE_STATUS_ERROR)):(this.status=OC.Leaving,this.signal.leave().then((r=>{if(r instanceof qc)return this.stat.reportLeavInfo(FC.LEAVE_ROOM_ERROR),this.stat.getMediaStat().clearEncryUserId(),void t(r);this.doLeaveRoom(),this.stat.reportLeavInfo(FC.LEAVE_ROOM_SUCCESS),this.stat.getMediaStat().clearEncryUserId(),this.stopStreamResolutionDetection(),this.logger.info(CN,"leave success"),e()})))}))}doLeaveRoom(){this.cleanup(),this.cleanTransportStats(),this.stat.leaveRoom(),cO.immediateReportRecords(),this.roomStreamStatus={}}resetConnection(){const e=[],t=this.streamPublishManager.getPublishedMainVideoTrackInfo();t&&e.push(t.sender);const r=this.streamPublishManager.getPublishedMainAudioTrackInfo();r&&e.push(r.sender),this.connectionsManager.destroyPeerConnection(yO.STREAM_TYPE_MAIN,e);const i=this.streamPublishManager.getPublishedAuxVideoTrackInfo();this.connectionsManager.destroyPeerConnection(yO.STREAM_TYPE_AUX,i?[i.sender]:[])}async rejoin(e,t){this.logger.info(CN,"rejoin room roomId:".concat(e," JoinConfig:").concat(JSON.stringify(t)));const r=[];let i="";this.roomId=e;try{var n,o,s,a;TA.checkJoinParams(e,t),this.mainRelayRoomSymbol&&ED.roleValidCheck4RelayRoom(this,t.role);const c=uM.init(this.identifiedID,e,t);if(this.userInfo=c,this.stat.setLocalUserInfo(c),this.resetConnection(),this.streamPublishManager.reset(),clearTimeout(this.netQualityTimer),clearTimeout(this.transportStatsTimer),this.signal)this.signal.reset();else{const e=await this.accessManager.getAccessInfo(this.clientConfig.countryCode,r);this.newSignal(e),this.signalEvent()}this.status=OC.Joining,i=await this.signal.connect(c,r),this.logger.info(CN,"rejoin, actualAcsIp:".concat(i)),await this.waitNotifyConfig(r),await this.connectionsManager.initConnectionAndSdp(this.roomId,yO.STREAM_TYPE_MAIN,{onTrackHandler:this.onTrackHandler.bind(this)}),await this.connectionsManager.initConnectionAndSdp(this.roomId,yO.STREAM_TYPE_AUX,{onTrackHandler:this.onTrackHandler.bind(this)});const u=await this.connectionsManager.modifySdpInfo(yO.STREAM_TYPE_MAIN,this.cmdMsgAbility.enable),d=await this.connectionsManager.modifySdpInfo(yO.STREAM_TYPE_AUX),l=await this.signal.join(this.userInfo,u,d,this.audioPolicy,null===(n=this.bandwidthParam)||void 0===n?void 0:n.maxBandwidth,this.connectionsManager.getPortType(),this.cmdMsgAbility.enable,this.sfuConfigs);!this.clientConfig.countryCode&&l.countryCode&&this.accessManager.setOpsUrl(l.countryCode),this.sdpRepInfo=l.sdp,l.userInfos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(e.userId,e.userEid)})),null!=l&&l.userEid&&this.stat.getMediaStat().setEncryInfo(this.userInfo.userId,l.userEid.toString());const h=String(l.roomUid);this.stat.setRoomUid(h);const f=null===(o=l.roomStreamStatus)||void 0===o?void 0:o.audience;let p;p=this.audioPolicy===IO.TOPN_AUDIOPOLICY?async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(l,r,i,n),f===YC.PAUSE&&this.userInfo.role===nM?{answerSdp:t}:await this.addSsrc4Top3(t)}:async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(l,r,i,n),{answerSdp:t}};const m=null===(s=l.negSdp.find((e=>e.type===RM.MAIN)))||void 0===s?void 0:s.sdp,g=null===(a=l.negSdp.find((e=>e.type===RM.DESKTOP)))||void 0===a?void 0:a.sdp;this.connectionsManager.setSsrcsMapping(this.sdpRepInfo),await this.connectionsManager.handleAnswerSdpFromServer(yO.STREAM_TYPE_MAIN,m,p),await this.connectionsManager.handleAnswerSdpFromServer(yO.STREAM_TYPE_AUX,g),await this.handleRoomStreamStatus(f),this.upStreamData=l.userInfos.find((e=>{var t;return e.userId===(null===(t=this.userInfo)||void 0===t?void 0:t.userId)})),this.remoteUserManager.initialize(this.userInfo.userId,l.sdp),this.stat.setSFUAddress(this.connectionsManager.getSfuInfoFromSdp(m,g)),this.signal.keepAlive(),this.status=OC.Joined,this.localRejoinFlag=!0,this.streamPublishManager.setSdpRepInfo(this.sdpRepInfo),this.statJoinRoomInfo(i,!0,r),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.transportStatsRegularReport(),this.setAudioLevelStatTimer(),ED.addConnectionCache(this.mainRelayRoomSymbol||this.clientSymbol,this.roomId,this),await this.doRefreshRoomUserInfos(this.userInfo.roomId,l.userInfos,!0),this.logger.info(CN,"rejoin, rejoin room success")}catch(jN){throw this.logger.error(CN,"rejoin room fail, error:".concat(jN)),this.stat.reportJoinInfo(null==jN?void 0:jN.code,i,!0,r,null==jN?void 0:jN.message),await TD.uploadLogFile(this),jN}}async changeStreamMuteStatusNotify(e,t,r,i){const n={"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16),videoStreams:[]};if(t===vO.TRACK_TYPE_VIDEO){const t={ssrc:0,mute:e};if(r===CC.desktop)t.ssrc=this.sdpRepInfo.desktopVideo.sendSsrcBegin;else if(t.ssrc=this.sdpRepInfo.video.sendSsrcBegin,i){const t={ssrc:this.sdpRepInfo.video.sendSsrcEnd,mute:e};n.videoStreams.push(t)}n.videoStreams.push(t)}else{const t={ssrc:this.sdpRepInfo.audio.sendSsrcBegin,mute:e};n.audioStreams=[t]}await this.signal.changeStreamStatus(n)}async setSendBitrate(e,t,r){if(!e)return void this.logger.info(CN,"sender is null");if("function"!=typeof e.getParameters)return void this.logger.info(CN,"sender not support getParameters");if("function"!=typeof e.setParameters)return void this.logger.info(CN,"sender not support setParameters");const i=e.getParameters();i.encodings.length<=0?this.logger.info(CN,"sender has no track, can not set maxBitRate"):(i.encodings[0].maxBitrate=t,await e.setParameters(i),this.logger.info(CN,"success set ".concat(r," sender maxBitrate: ").concat(t)))}static judgeNetworkQuality(e){return-1===e?EO.NETWORK_QUALITY_UNKNOW:e<1?EO.NETWORK_QUALITY_GREAT:e<3?EO.NETWORK_QUALITY_GOOD:e<6?EO.NETWORK_QUALITY_DEFECTS:e<12?EO.NETWORK_QUALITY_WEAK:e<20?EO.NETWORK_QUALITY_BAD:EO.NETWORK_QUALITY_DISCONNECT}async calcPktsLostRate(){const e=this.connectionsManager.getConnection(yO.STREAM_TYPE_MAIN);if(!e||["disconnected","failed","closed"].includes(e.connectionState))return;let t=await this.getUploadStatistic("video");if(t<0&&(t=await this.getUploadStatistic("audio")),this.pktsLostRate.up=Math.round(t),t=await this.getDownloadStatistic(vO.TRACK_TYPE_VIDEO),t<0&&(t=await this.getDownloadStatistic(vO.TRACK_TYPE_AUDIO)),t<0)return void(this.pktsLostRate.down=-1);this.pktsLostRate.preDownRate.push(t),this.pktsLostRate.preDownRate.length>3&&this.pktsLostRate.preDownRate.splice(0,1);const r=this.smoothData(this.pktsLostRate.preDownRate,.9);this.pktsLostRate.down=Math.round(r[r.length-1])}smoothData(e,t){const r=e=>e.reduce((function(e,t){return e+t}),0)/e.length,i=r(e)*t,n=[];for(let o=0;o0?n[o-1]:e[e.length-1],a=o{clearTimeout(this.netQualityTimer);let t={uploadPkgLoss:0,downloadPkgLoss:0};try{const r=this.connectionsManager.getConnection(yO.STREAM_TYPE_MAIN);if(r&&!["disconnected","failed","closed"].includes(r.connectionState)||(t={uploadPkgLoss:EO.NETWORK_QUALITY_DISCONNECT,downloadPkgLoss:EO.NETWORK_QUALITY_DISCONNECT}),t.uploadPkgLoss=e.judgeNetworkQuality(this.pktsLostRate.up),t.downloadPkgLoss=e.judgeNetworkQuality(this.pktsLostRate.down),!this.preNetQuality||this.preNetQuality.uploadPkgLoss!==t.uploadPkgLoss||this.preNetQuality.downloadPkgLoss!==t.downloadPkgLoss){const e={uplinkNetworkQuality:t.uploadPkgLoss,downlinkNetworkQuality:t.downloadPkgLoss};this.logger.info(CN,"emit:".concat(UC.NetworkQuality,", quality:").concat(JSON.stringify(e))),this.eventEmitter.emit(UC.NetworkQuality,e),this.preNetQuality=t}}finally{this.netQualityRegularReport.bind(this)}}),2e3)}validatePublishRequest(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"can not publish stream before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"can not publish stream before join room");if(this.userInfo.role===nM)throw this.logger.error(CN,"the player role can not publish stream"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"the player role can not publish stream");if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e.hasAudioTrack()||e.hasVideoTrack()||this.logger.warn(CN,"stream has no audio and video"),"local"!==e.getType())throw this.logger.error(CN,"stream type: ".concat(e.getType()," cannot publish")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"stream type: ".concat(e.getType()," cannot publish"))}async publish(e,t){try{return await this.publishImpl(e,t),void(e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_START,KC.RESULT_SUCCESS))}catch(Dw){throw e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_START,KC.RESULT_ERROR),Dw}}async publishImpl(e,t){try{if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");if(await this.publishStream(e,t),!e.isAuxiliary()){if(this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos())&&(e.hasAudioTrack()&&this.buildSendMediaStreamInfo(TC.Audio),t&&e.hasVideoTrack())){const e=this.streamPublishManager.getPublishedMainVideoTrackInfos().map((e=>e.ssrc));this.buildSendMediaStreamInfo(TC.Video,e)}}}catch(jN){throw this.logger.error(CN,"publishImpl fail, errMsg = ".concat(jN)),jN}}async publishStream(e,t){this.logger.info(CN,"publish ".concat(e.isAuxiliary()?"aux":"main"," stream")),this.validatePublishRequest(e);const r=e,i=this.streamPublishManager.generatePubInfoWhenPublish(r,t);await this.sendPublishRequest(i.allTracks2Publish),await this.updateStreamTracks(r,i),this.startStreamResolutionDetection(r),r.addClient(this)}async sendPublishRequest(e){e&&await this.sendPublishReq(e)}startStreamResolutionDetection(e){var t;if(!e||Mw.isFirefox())return;const r=e.isAuxiliary();!r&&this.resolutionChangeInfo.mainResolutionChangeTimer&&(clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer),r&&this.resolutionChangeInfo.auxResolutionChangeTimer&&(clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null),this.logger.info(CN,"startStreamResolutionDetection isAuxiliary: ".concat(r));const i=r?this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_AUX):null===(t=this.streamPublishManager)||void 0===t?void 0:t.getLocalStream(yO.STREAM_TYPE_MAIN);if(i)try{this.resolutionChangeInfo[r?"auxResolutionChangeTimer":"mainResolutionChangeTimer"]=setInterval((async()=>{const e=this.streamPublishManager.getStreamTrackInfo(i),t={"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16),videoStreams:[]};for(const n of e){if("audio"===n.type)return;if(!(r?OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(n.upstream.ssrc),"packetsSent"):OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(n.upstream.ssrc),"packetsSent")))continue;const e={resolutionId:n.resolutionId,content:n.upstream.content,streamUid:n.upstream.streamUid,ssrc:n.upstream.ssrc,mute:n.upstream.mute,width:0,height:0};this.resolutionChangeInfo.preVideoHeight.has(e.resolutionId)||this.resolutionChangeInfo.preVideoHeight.set(e.resolutionId,i.getVideoHeight(e.resolutionId));let o=!1;r?(e.height=OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(e.ssrc),"frameHeight"),e.width=OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(e.ssrc),"frameWidth")):(e.height=OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(e.ssrc),"frameHeight"),e.width=OO.getLatestValue(this.userInfo.roomId,yO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(e.ssrc),"frameWidth")),o=Math.abs(this.resolutionChangeInfo.preVideoHeight.get(e.resolutionId)-e.height)/this.resolutionChangeInfo.preVideoHeight.get(e.resolutionId)>.1,o&&(t.videoStreams.push(e),this.resolutionChangeInfo.preVideoHeight.set(e.resolutionId,e.height))}t.videoStreams.length>0&&await this.signal.changeStreamStatus(t)}),5e3)}catch(jN){throw this.logger.error(CN,"startStreamResolutionDetection, occur error: ".concat(jN)),jN}}stopStreamResolutionDetection(e){var t;if(!e)return clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer=null,clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null,void this.resolutionChangeInfo.preVideoHeight.clear();e.isAuxiliary()?(clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null):(clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer=null),null===(t=e.getStreamInfo().videoProfiles)||void 0===t||t.forEach((e=>this.resolutionChangeInfo.preVideoHeight.delete(e.resolutionId)))}async updateStreamTracks(e,t){if(!e)return;const r=e.isAuxiliary();t.tracks2UnPublish&&0!==t.tracks2UnPublish.length||t.tracks2NewPublish&&0!==t.tracks2NewPublish.length?r?await this.updateAuxStreamTrack(e,t):await this.updateMainStreamTrack(e,t):this.logger.info(CN,"update ".concat(r?"aux":"main"," streamTracks, no new publish and unpublish, so no need update sdp"))}async updateMainStreamTrack(e,t){const r=t.tracks2UnPublish.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)),i=this.removeTracksWhenPublish(r),n=t.tracks2UnPublish.filter((e=>e.type===vO.TRACK_TYPE_AUDIO)),o=this.removeTracksWhenPublish(n),s=o.length>0?o[0]:null,a=t.tracks2NewPublish.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)),c=await this.addVideoTracksWhenPublish(e,a),u=t.tracks2NewPublish.filter((e=>e.type===vO.TRACK_TYPE_AUDIO)),d=await this.addAudioTrackWhenPublish(e,u),l=t.tracks2KeepPublish.filter((e=>e.type===vO.TRACK_TYPE_AUDIO)),h=this.getKeepAudioTrackSsrcSender(l),f=t.tracks2KeepPublish.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)),p=this.getKeepVideoTracksSsrcSender(f);await this.generateNewOfferSdp(h,d,p,c,i,s),u.length>0&&await this.sendAudioMedia(e,d),a.length>0&&await this.sendVideoMedia(e,c),null==r||r.forEach((e=>{this.streamPublishManager.unPublishTrackSuccess(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO,e.upstream.streamUid.toString())})),null==n||n.forEach((e=>{this.streamPublishManager.unPublishTrackSuccess(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO,e.upstream.streamUid.toString())}))}async updateAuxStreamTrack(e,t){if(t.tracks2NewPublish&&t.tracks2NewPublish.length>0){const r=t.tracks2NewPublish&&t.tracks2NewPublish.filter((e=>e.type===vO.TRACK_TYPE_VIDEO))[0].ssrc,i=await this.connectionsManager.addTrack(yO.STREAM_TYPE_AUX,e.getVideoTrack(),e.getMediaStream());await this.connectionsManager.modifyPublishOfferSdp(yO.STREAM_TYPE_AUX,this.userInfo.userId,[r]),this.logger.info(CN,"aux send bitrate ".concat(e.getScreenSendBitrate())),await this.setSendBitrate(i,e.getScreenSendBitrate(),"auxVideo"),this.streamPublishManager.publishAuxVideoTrackOK(i,r);const n=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_AUX);n&&(n.off(eC,this.addLocalAuxStreamEndedHandler.bind(this)),n.on(eC,this.addLocalAuxStreamEndedHandler.bind(this))),await e.resumeMixScreenAudio()}else{const r=t.tracks2UnPublish;let i=0;r.forEach((e=>{i=e.ssrc,this.connectionsManager.removeTrack(yO.STREAM_TYPE_AUX,e.sender)})),await this.connectionsManager.modifyPublishOfferSdp(yO.STREAM_TYPE_AUX,this.userInfo.userId,[],0,[i]),await e.stopMixScreenAudio()}}async sendAudioMedia(e,t){if(t)try{await this.setSendBitrate(t.sender,e.getAudioSendBitrate(),"audio"),this.streamPublishManager.publishMainAudioTrackOK(t.sender,t.ssrc),this.logger.info(CN,"sendAudioMedia, send audio media successfully")}catch(jN){throw this.logger.error(CN,"sendAudioMedia, occur error: ".concat(jN)),jN}}async sendVideoMedia(e,t){if(0!==t.length)try{const r=[];t.forEach((t=>{r.push(this.setSendBitrate(t.sender,e.getVideoMaxSendBitrate(t.resolutionId),"mainVideo"))})),await Promise.all(r).then((()=>{t.forEach((e=>{this.streamPublishManager.publishMainVideoTrackOK(e.sender,e.ssrc,e.streamId)}))})),this.logger.info(CN,"sendVideoMedia, send video media successfully")}catch(jN){throw this.logger.error(CN,"sendVideoMedia, occur error: ".concat(jN)),jN}}async generateNewOfferSdp(e,t,r,i,n,o){try{const s=[];r.forEach((e=>s.push(e.ssrc))),i.forEach((e=>s.push(e.ssrc)));const a=t?t.ssrc:e?e.ssrc:null,c=[];n.forEach((e=>c.push(e.ssrc)));const u=o?o.ssrc:null,d=await this.connectionsManager.modifyPublishOfferSdp(yO.STREAM_TYPE_MAIN,this.userInfo.userId,s,a,c,u);return this.logger.info(CN,"generateNewOfferSdp successfully"),d}catch(jN){throw this.logger.error(CN,"generateNewOfferSdp, occur error: ".concat(jN)),jN}}async sendPublishReq(e){try{const t=[];e.forEach((e=>{t.push(e.upstream),this.logger.info(CN,"prepare to send publish req, streamId:".concat(e.upstream.streamUid))})),await this.signal.publish(t),this.logger.info(CN,"sendPublishReq successfully")}catch(jN){throw this.logger.error(CN,"sendPublishReq, occur error: ".concat(jN)),jN}}async addVideoTracksWhenPublish(e,t){if(0===t.length)return[];try{const r=[];for(const i of t){const t=e.getVideoTrack(i.resolutionId),n=i.ssrc,o=await this.connectionsManager.addTrack(yO.STREAM_TYPE_MAIN,t,e.getMediaStream(),n);r.push({ssrc:n,sender:o,streamId:i.upstream.streamUid.toString(),resolutionId:i.resolutionId}),this.logger.info(CN,"addVideoTracksWhenPublish, add video track of resolutionId:".concat(i.resolutionId,",")+"physical track id:".concat(t.id,", streamId: ").concat(i.upstream.streamUid," with ssrc: ").concat(n," to connection successfully"))}return r}catch(jN){throw this.logger.error(CN,"addVideoTracksWhenPublish, occur error: ".concat(jN)),jN}}async addAudioTrackWhenPublish(e,t){if(0===t.length)return null;try{const r=e.getPublishAudioTrack(),i=t[0].ssrc,n={ssrc:i,sender:await this.connectionsManager.addTrack(yO.STREAM_TYPE_MAIN,r,e.getMediaStream()),streamId:t[0].upstream.streamUid.toString(),resolutionId:null};return this.logger.info(CN,"addAudioTrackWhenPublish, add audio track for streamId: ".concat(t[0].upstream.streamUid,",")+"physical track id:".concat(null==r?void 0:r.id," to connection successfully")),n}catch(jN){throw this.logger.error(CN,"addAudioTrackWhenPublish, occur error: ".concat(jN)),jN}}removeTracksWhenPublish(e){if(0===e.length)return[];try{const t=[];return e.forEach((e=>{this.connectionsManager.removeTrack(yO.STREAM_TYPE_MAIN,e.sender),t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId}),this.logger.info(CN,"removeTracksWhenPublish, remove ".concat(e.type," track for streamId: ").concat(e.upstream.streamUid," to connection successfully"))})),t}catch(jN){throw this.logger.error(CN,"removeTracksWhenPublish, occur error: ".concat(jN)),jN}}getKeepAudioTrackSsrcSender(e){const t=[];return e.forEach((e=>{t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId})})),t.length>0?t[0]:null}getKeepVideoTracksSsrcSender(e){const t=[];return e.forEach((e=>{t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId})})),t}buildSendMediaStreamInfo(e,t){switch(e){case TC.Aux:{const e=this.streamPublishManager.generateAuxOptTag();e&&this.stat.reportStartSendMediaStream(WC.AUX,e);break}case TC.Video:{const e=this.streamPublishManager.generateMainVideoOptTags();e&&e.length>0&&e.forEach((e=>{t.find((t=>-1!=e.indexOf("".concat(t))))&&this.stat.reportStartSendMediaStream(WC.VIDEO,e)}));break}case TC.Audio:{const e=this.streamPublishManager.generateMainAudioOptTag();e&&this.stat.reportStartSendMediaStream(WC.AUDIO,e);break}}}async unpublish(e){try{return await this.unpublishImpl(e),e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_STOP,KC.RESULT_SUCCESS),void this.stopStreamResolutionDetection(e)}catch(Dw){throw e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_STOP,KC.RESULT_ERROR),Dw}}async unpublishImpl(e){if(this.userInfo.role===nM)throw this.logger.error(CN,"the player role can not unpublish stream"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"the player role can not unpublish stream");if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if("local"!==e.getType())throw this.logger.error(CN,"stream type: ".concat(e.getType()," cannot unpublish")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"stream type: ".concat(e.getType()," cannot unpublish"));try{await this.locker.lock("".concat(CN,":unpublishImpl")),await this.unPublishStream(e)}finally{this.locker.unlock("".concat(CN,":unpublishImpl"))}}async unPublishStream(e){await this.unpublishSteamAndSignalIfNeed(e,this.sendPublishRequest.bind(this))}async unpublishSteamAndSignalIfNeed(e,t){const r=e.isAuxiliary(),i=r?"aux":"main";try{this.logger.info(CN,"unpublish ".concat(i," stream:").concat(e.getId()));const n=e,o=this.streamPublishManager.generatePubInfoWhenUnPublish(n);t&&await t(o.allTracks2Publish),await this.startStreamResolutionDetection(n),await this.updateStreamTracks(n,o),n.removeClient(this),r?this.streamPublishManager.unPublishAuxStreamOK():this.streamPublishManager.unPublishMainStreamOK(),this.logger.info(CN,"unpublish ".concat(i,"stream success: ").concat(e.getId()))}catch(jN){throw this.logger.error(CN,"unpublish ".concat(i," stream, ").concat(e.getId()," occur error: ").concat(jN)),jN}}async rejoinPublishStreams(e){let t=[];for(const r of e){this.logger.info(CN,"rejoin publish ".concat(r.isAuxiliary()?"aux":"main"," stream"));const e=r;e.removeClient(this),this.validatePublishRequest(r);const i=this.streamPublishManager.generatePubInfoWhenPublish(e);await this.updateStreamTracks(e,i),e.addClient(this),t=[...t,...i.allTracks2Publish]}t=[...new Set(t)],await this.sendPublishRequest(t);for(const r of e){const e=r;await this.startStreamResolutionDetection(e)}}addLocalAuxStreamEndedHandler(e){this.streamPublishManager.isAuxVideoTrackValid(e)&&this.unpublish(this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_AUX))}async subscribeAudio(e){return await this.subscribeAudioImpl(e)}async subscribeAudioImpl(e){if(!e)throw this.logger.error(CN,"subscribeAudioImpl, userId is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userId is null");const t=new rM({type:"main",log:this.logger,userId:e,client:this,roomId:this.roomId});this.logger.info(CN,"subscribeAudioImpl begin, userId:".concat(e)),await this.subscribeImpl(t,{audio:!0,video:!1});const r=this.remoteUserManager.getUserInfoById(e,this.roomId);if(r){let e=!1;for(const t of null===(i=r.mainStream.remoteTrackInfos)||void 0===i?void 0:i.values()){var i;if(t.type===vO.TRACK_TYPE_AUDIO&&t.isSubscribed){e=!0;break}}if(e)return r.mainStream.remoteStream}}async unSubscribeAudio(e){return await this.unSubscribeAudioImpl(e)}async unSubscribeAudioImpl(e){if(!e)throw this.logger.error(CN,"unSubscribeAudioImpl, userId is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userId is null");const t=new rM({type:"main",log:this.logger,userId:e,client:this,roomId:this.roomId});this.logger.info(CN,"unSubscribeAudioImpl begin, userId:".concat(e)),await this.unsubscribeImpl(t,{audio:!0,video:!1})}startupQoSReportPlay(e,t){const r=this.startupQoSMap.get(e);if(r){const e={timestamp:r.start,traceId:r.traceId,spanId:"0.1.1",originIntfName:r.interfaceName,interfaceName:"play",source:"",target:"",resultCode:"",successFlag:"T",duration:t-r.start,async:"N",extendInfo:JSON.stringify({id:r.id,streamIds:r.streamIds})};this.stat.setFirstFrameInfo(e),r.start=t,r.interfaceName="play"}}startupQoSReportCanPlay(e){const t=XR.getCurrentTimestamp(),r=(null==e?void 0:e.id)&&this.startupQoSMap.get(null==e?void 0:e.id);if(r){const e={timestamp:r.start,traceId:r.traceId,spanId:"0.1.1.1",originIntfName:r.interfaceName,interfaceName:"canplay",source:"",target:"",resultCode:"",successFlag:"T",duration:t-r.start,async:"N",extendInfo:JSON.stringify({id:r.id,streamIds:r.streamIds})};this.stat.setFirstFrameInfo(e)}}async subscribe(e,t){return await this.subscribeImpl(e,t)}async subscribeImpl(e,t){if(this.roomStreamStatus.audience===YC.PAUSE&&this.userInfo.role===nM)throw this.logger.error(CN,"subscribeImpl, room stream status is pause"),new qc(Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED,"room stream status is ".concat(this.roomStreamStatus.audience));const r=XR.getCurrentTimestamp(),i={traceId:XR.generateRandomId(32,16),spanId:"0",originIntfName:"",interfaceName:"subscribe",id:e.getUniqueId(),start:r};if(!e)throw this.logger.error(CN,"subscribeImpl, stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");if(t||(t={video:!0,audio:!0}),t.audio||t.video){if(t.video&&![DC.ON,DC.OFF,null,void 0].includes(t.autoAdjustResolution))throw this.logger.error(CN,"the autoAdjustResolution value must be 1 or 2 or empty."),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);await this.doSubscribe(e,t,i)}}async doSubscribe(e,t,r){if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);const i=e.getUserId(),n=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN;this.logger.info(CN,"start subscribe, ".concat(i,", ").concat(n,", option: ").concat(JSON.stringify(t))),this.audioPolicy!==IO.USER_SUBSCRIBE_AUDIOPOLICY&&t.audio&&this.logger.info(CN,"doSubscribe, ".concat(this.audioPolicy," is not common audio mode, but audio option is true, reserve it"));try{await this.locker.lock("".concat(CN,":doSubscribe"));const e=this.remoteUserManager.subscribeStream(i,this.roomId,n,t,this.audioPolicy,!1,r);return await this.updateSubscribe(e,r)}catch(jN){throw this.logger.error(CN,"subscribe release lock, subscribe userId ".concat(e.getUserId()," occur error ").concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doSubscribe"))}}async batchSubscribe(e){return await this.doBatchSubscribe(e)}checkSubscribeParams(e){e.forEach((e=>{if(![DC.OFF,DC.ON,null,void 0].includes(e.autoAdjustResolution))throw this.logger.error(CN,"the autoAdjustResolution value must be 1 or 2"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!["FHD","HD","SD","LD",null,void 0].includes(e.minResolution))throw this.logger.error(CN,"the minResolution value must be 'FHD','HD','SD','LD'"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}))}async doBatchSubscribe(e){this.logger.info(CN,"doBatchSubscribe, subscribeInfos: ".concat(JSON.stringify(e)));try{this.checkSubscribeParams(e);const t=e.map((e=>({userId:e.userId,resolutionIds:e.resolutionIds,autoAdjustResolution:e.autoAdjustResolution,minResolution:e.minResolution})));await this.locker.lock("".concat(CN,":doBatchSubscribe"));const r=this.remoteUserManager.batchSubscribeMainStream(this.roomId,t);await this.updateSubscribe(r)}catch(jN){throw this.logger.error(CN,"batchSubscribe failed, ".concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doBatchSubscribe"))}}async batchDeleteUnusedSsrcInSdp(e,t,r){(t&&0!==t.length||r&&0!==r.length)&&(this.logger.info(CN,"batchDeleteUnusedSsrcInSdp, streamType: ".concat(e,", videoSsrc2Del: ").concat(t,", audioSsrc2Del:").concat(r)),await this.connectionsManager.deleteUser(e,t,r))}async enableStreamStateDetection(e,t){if(this.status!==OC.Joined)throw this.logger.error(CN,"cannot enable stream detection before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot enable stream detection before join room");if(!e)return clearTimeout(this.streamInterruptedDetectInterval),this.streamInterruptedDetectInterval=null,this.lastCycleFrameDecodedMap.clear(),void this.streamInterruptedUsersMap.clear();if(!Number.isInteger(t)||t<1||t>60)throw this.logger.error(CN,"invalid interval for enable stream detection"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e&&this.streamInterruptedDetectInterval)throw this.logger.error(CN,"cannot double enable stream detection"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot double enable stream detection");if(this.streamDetectionCriterion=t,this.lastCycleFrameDecodedMap&&0===this.lastCycleFrameDecodedMap.size){this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,null).forEach((e=>{const t=e.userId;e.mainStream&&this.lastCycleFrameDecodedMap.set(t+",0",{userId:t,decodedFrame:0}),e.auxStream&&this.lastCycleFrameDecodedMap.set(t+",1",{userId:t,decodedFrame:0})}))}await this.startStreamDetection()}async startStreamDetection(){if(!this.streamInterruptedDetectInterval){const e=1e3,t=()=>{this.streamInterruptedDetectInterval=setTimeout((async()=>{const r=await this.stat.collectReceiverDecodedFrameMap(),i=[],n=[],o=Math.round(1e3*this.streamDetectionCriterion/e);this.streamInterruptedUsersMap.forEach(((e,t)=>{r.has(t)||this.streamInterruptedUsersMap.delete(t)})),r.forEach(((e,t)=>{const r=this.lastCycleFrameDecodedMap&&this.lastCycleFrameDecodedMap.get(t);if(r&&r.decodedFrame===e.decodedFrame){const e=this.streamInterruptedUsersMap.get(t);e?this.streamInterruptedUsersMap.set(t,e+1):this.streamInterruptedUsersMap.set(t,1)}if(r&&r.decodedFrame!==e.decodedFrame){if(this.streamInterruptedUsersMap.get(t)>=o){const r=t.split(",");r[0]!==wC&&n.push({userId:r[0],isScreen:e.isAux})}this.streamInterruptedUsersMap.delete(t)}})),this.lastCycleFrameDecodedMap=r,this.streamInterruptedUsersMap&&this.streamInterruptedUsersMap.forEach(((e,t)=>{if(e===o){const e=t.split(",");e[0]!==wC&&(i.push({userId:e[0],isScreen:"1"===e[1]}),this.logger.info(CN,"stream interrupted, userId: ".concat(e[0],", isAux: ").concat(e[1])))}})),i.length>0&&this.connectState.curState===vC[yC.CONNECTED]&&(this.logger.info(CN,"find stream interrupted users, ".concat(JSON.stringify(i))),this.eventEmitter.emit(UC.StreamInterrupted,i)),n.length>0&&this.connectState.curState===vC[yC.CONNECTED]&&(this.logger.info(CN,"find stream recovered users, ".concat(JSON.stringify(n))),this.eventEmitter.emit(UC.StreamRecovered,n)),t()}),e)};t()}}async unsubscribe(e,t){return await this.unsubscribeImpl(e,t)}async unsubscribeImpl(e,t){if(this.logger.info(CN,"start unsubscribe"),this.roomStreamStatus.audience===YC.PAUSE&&this.userInfo.role===nM)throw this.logger.error(CN,"unsubscribeImpl, room stream status is pause"),new qc(Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED,"room stream status is ".concat(this.roomStreamStatus.audience));if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");const r=e.getUserId(),i=e.isAuxiliary()?yO.STREAM_TYPE_AUX:yO.STREAM_TYPE_MAIN;this.logger.info(CN,"start doUnsubscribe, ".concat(r,", ").concat(i,", option: ").concat(JSON.stringify(t)));try{const e=t||{video:!0,audio:!0};await this.locker.lock("".concat(CN,":doUnsubscribe"));const n=this.remoteUserManager.unsubscribeStream(r,this.roomId,i,e);await this.updateSubscribe(n)}catch(jN){throw this.logger.error(CN,"subscribe userId ".concat(e.getUserId()," occur error ").concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doUnsubscribe"))}}async switchRole(e,t){return await this.switchRoleImpl(e,t)}async switchRoleImpl(e,t){if(this.logger.info(CN,"switchRole from ".concat(this.userInfo.role," to ").concat(e)),this.status!==OC.Joined&&this.status!==OC.Rejoining)throw new qc(Gc.RTC_ERR_CODE_STATUS_ERROR);if(this.userInfo.role===e)throw this.logger.error(CN,"new role same with old role, no need switch."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"new role same with old role, no need switch.");ED.switchRoleParamsCheck(this,e,t);try{await this.locker.lock("".concat(CN,":_switchRoleImpl")),this.userInfo.role===iM&&e===nM&&(this.streamPublishManager.isMainStreamPublished()&&await this.unpublishSteamAndSignalIfNeed(this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN)),this.streamPublishManager.isAuxVideoTrackPublished()&&await this.unpublishSteamAndSignalIfNeed(this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_AUX)));const r=await this.signal.switchRole(e,t);this.logger.debug(CN,"swithRole resp: ".concat(JSON.stringify(r))),this.userInfo.role===nM&&e===iM&&(this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos()),this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo())),this.userInfo.role=e,e===iM&&this.roomStreamStatus.audience===YC.PAUSE&&await this.handleRoomStreamStatus(YC.NORMAL,IO.TOPN_AUDIOPOLICY===this.audioPolicy,!0),this.stat.reportSwitchRoleInfo(e,JC),this.locker.unlock("".concat(CN,":_switchRoleImpl")),this.logger.info(CN,"switchRole success")}catch(jN){throw this.locker.unlock("".concat(CN,":_switchRoleImpl")),this.logger.error(CN,"switchRole switchRole failed, errMsg = ".concat(jN)),this.stat.reportSwitchRoleInfo(e,qC),jN}}getPublishAudioSender(){var e;return null===(e=this.streamPublishManager.getPublishedMainAudioTrackInfo())||void 0===e?void 0:e.sender}getPublishedMainAudioTrackInfo(){return this.streamPublishManager.getPublishedMainAudioTrackInfo()}getPublishedMainVideoTrackInfos(){return this.streamPublishManager.getPublishedMainVideoTrackInfos()}getPublishVideoSender(e){if(e===yO.STREAM_TYPE_AUX){const e=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(e)return[e.sender]}const t=[];return this.streamPublishManager.getPublishedMainVideoTrackInfos().forEach((e=>{t.push(e.sender)})),t}getMainStreamSenderByTrack(e){if(!e)return null;const t=this.streamPublishManager.getPublishedMainVideoTrackInfos().find((t=>t.upstream.streamUid.toString()===e));return null==t?void 0:t.sender}async waitForTrackBatch(e){const t=e.map((e=>{var t,r;return(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0?1:0})).reduce(((e,t)=>e+t),0),r=e.map((e=>{var t,r;return(null===(t=e.auxStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0?1:0})).reduce(((e,t)=>e+t),0);this.logger.debug(CN,"wait for track batch begin, mainStreamCount:".concat(t,", auxStreamCount:").concat(r," "));for(let i=0;i<100;i++){if(this.computeSucceedStreamCount(yO.STREAM_TYPE_MAIN,t,e)+this.computeSucceedStreamCount(yO.STREAM_TYPE_AUX,r,e)===t+r)break;if(99===i)return void this.logger.error(CN,"waitForTrackBatch subscribe on track timeout");await XR.sleep(50)}}computeSucceedStreamCount(e,t,r){let i=0;return t&&(i=r.map((t=>this.isStreamTrackReady(e,t)?1:0)).reduce(((e,t)=>e+t),0)),i}newSignal(e){this.signal||(this.signal=new PM(this.clientConfig.appId,e,this))}async negTransportChannelHandler(e,t,r,i){if(this.cmdMsgAbility.enable)if(e.sdp.cmd){var n;if(i)return super.off(UC.CmdChannelDisconnect),iE.getLogger().debug(CN,"negTransportChannelHandler init command channel of datachannel."),this.cmdMsgAbility.cmdManager=new BD(this.eventEmitter,this.remoteUserManager),null===(n=this.cmdMsgAbility.cmdManager)||void 0===n||n.setCommandChannelParams(this.roomId,{tranportOptions:{userUid:e.userUid,sendSsrc:e.sdp.cmd.sendSsrc,receiveSsrc:e.sdp.cmd.receiveSsrc,payload:e.sdp.cmd.pt},dataChannelOptions:{connection:this.connectionsManager.getConnection(yO.STREAM_TYPE_MAIN)},msgFormat:this.cmdMsgAbility.msgFormat}),await this.connectionsManager.refreshOffer(yO.STREAM_TYPE_MAIN),void(t&&r&&super.on(UC.CmdChannelDisconnect,(i=>{i===BC.DATA_CHANNEL&&(iE.getLogger().debug(CN,"negTransportChannelHandler downgrade to webocket command channel."),this.websocketChannelInit(e,t,r))}),!1));t&&r&&(iE.getLogger().debug(CN,"negTransportChannelHandler init webocket command channel."),this.websocketChannelInit(e,t,r))}else iE.getLogger().error(CN,"negTransportChannelHandler error, cmd signal info missing.")}websocketChannelInit(e,t,r){var i;null===(i=this.cmdMsgAbility.cmdManager)||void 0===i||i.reset(),this.cmdMsgAbility.cmdManager=new UD(this.eventEmitter,this.remoteUserManager),this.cmdMsgAbility.cmdManager.setCommandChannelParams(this.roomId,{tranportOptions:{userUid:e.userUid,sendSsrc:e.sdp.cmd.sendSsrc,receiveSsrc:e.sdp.cmd.receiveSsrc,payload:e.sdp.cmd.pt},wsOptions:{bindCryptoKey:t,wsUrl:r,wsDomain:e.sdp.domain},msgFormat:this.cmdMsgAbility.msgFormat})}onTrackHandler(e,t){if(this.logger.info(CN,"peerconnection ontrack event: ".concat(e.track.kind)),e.track.kind===vO.TRACK_TYPE_VIDEO||this.audioPolicy===IO.USER_SUBSCRIBE_AUDIOPOLICY&&e.track.kind===vO.TRACK_TYPE_AUDIO){var r,i;const n=e.streams[0].id,o=this.remoteUserManager.getUserInfoByStreamId(this.roomId,n),s=t?null==o||null===(r=o.auxStream)||void 0===r?void 0:r.remoteStream:null==o||null===(i=o.mainStream)||void 0===i?void 0:i.remoteStream;s?(this.logger.info(CN,"connection.ontrack streamId=".concat(n,", hasAudio:").concat(s.hasAudioTrack()," hasVideo:").concat(s.hasVideoTrack())),s.addRemoteTrack(e.track,n)):this.logger.info(CN,"ontrack stream: ".concat(n," is not existed"))}this.logger.info("onConnection","audio policy:".concat(this.audioPolicy,",track kind:").concat(e.track.kind)),this.audioPolicy===IO.TOPN_AUDIOPOLICY&&e.track.kind===vO.TRACK_TYPE_AUDIO&&this.saveAudioStream4TopN(e)}static isStreamAdd(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return 0===r.preTracks.length&&r.curTracks.length>0}static isStreamRemove(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return r.preTracks.length>0&&0===r.curTracks.length}static isStreamUpdate(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return r.addedTracks.length>0||r.updatedTracks.length>0||r.removedTracks.length>0}static getMuteChangeStatus(t,r,i){if(!i)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=t===yO.STREAM_TYPE_MAIN?i.mainStream:i.auxStream;return e.getMediaMuteChangeFlag(n,r)}static getMediaMuteChangeFlag(t,r){const i="noTrack",n=t.preTracks.find((e=>e.type===r)),o=t.curTracks.find((e=>e.type===r)),s=n?n.mute:i,a=o?o.mute:i;return e.getMuteChangeFlag(s,a)}static getMuteChangeFlag(e,t){return e!==t?t?EN.mute:EN.unmute:EN.noChange}async updateSubscribe(t,r,i){if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe or unSubscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);if(!t||0===t.length)return null;if(!e.isSubscriptionChange(t))return this.logger.info(CN,"no need update subscription"),null;try{const e={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};await this.modifyBrowerSdp(t,e);const n={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};!i&&await this.subscribeSignal(t,n,r),this.clearResource(t);const o=await this.handleRemoteStreamsState(n.successSubscribeInfos),s={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};return(null==o?void 0:o.successSubscribeInfos)&&s.successSubscribeInfos.push(...o.successSubscribeInfos),(null==o?void 0:o.failSubscribeInfos)&&s.failSubscribeInfos.push(...o.failSubscribeInfos),(null==n?void 0:n.failSubscribeInfos)&&s.failSubscribeInfos.push(...n.failSubscribeInfos),(null==n?void 0:n.successUnsubscribeInfos)&&s.successUnsubscribeInfos.push(...n.successUnsubscribeInfos),(null==n?void 0:n.failUnsubscribeInfos)&&s.failUnsubscribeInfos.push(...n.failUnsubscribeInfos),await this.rollbackResource(s.failSubscribeInfos),this.remoteUserManager.subscribeResultCallback(s,!1),this.logger.info(CN,"updateSubscribe end. ".concat(this.getSubscribeResultString(s))),s}catch(jN){this.logger.error(CN,"updateSubscribe fail. errMsg:".concat(jN));const r=this.getSubscribeExceptionResult(t);throw await this.rollbackResource(r.failSubscribeInfos),this.remoteUserManager.subscribeResultCallback(r,!0),this.logger.info(CN,"updateSubscribe fail end. ".concat(this.getSubscribeResultString(r))),jN}}modifyBrowerSdp(t,r){const i=this.buildSubsReq(t,r),n=e.getUserUpdateInfos(i.joinUserUpdateInfos),o=this.buildDefaultSubsRep(i);this.getSubscribeResult(n,o.videoUpstreams,o.audioUpstreams,r,!1);const s=[],a=[],c=[],u=[];r.successUnsubscribeInfos.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{e.type===vO.TRACK_TYPE_VIDEO?s.push(e.cssrc):c.push(e.cssrc)})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{e.type===vO.TRACK_TYPE_VIDEO?a.push(e.cssrc):u.push(e.cssrc)}))}));const d=[];return d.push(this.generateReceiveSdp(yO.STREAM_TYPE_MAIN,r.successSubscribeInfos,s,c)),d.push(this.generateReceiveSdp(yO.STREAM_TYPE_AUX,r.successSubscribeInfos,a,u)),Promise.all(d)}getSubscribeExceptionResult(e){const t={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};return e.forEach((e=>{var r,i,n,o,s,a,c,u;const d={userId:e.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(r=e.mainStream)||void 0===r?void 0:r.remoteStream,tracks:null===(i=e.mainStream)||void 0===i?void 0:i.tracks4Subscribe},auxStream:{remoteStream:null===(n=e.auxStream)||void 0===n?void 0:n.remoteStream,tracks:null===(o=e.auxStream)||void 0===o?void 0:o.tracks4Subscribe}},l={userId:e.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(s=e.mainStream)||void 0===s?void 0:s.remoteStream,tracks:null===(a=e.mainStream)||void 0===a?void 0:a.tracks4Unsubscribe},auxStream:{remoteStream:null===(c=e.auxStream)||void 0===c?void 0:c.remoteStream,tracks:null===(u=e.auxStream)||void 0===u?void 0:u.tracks4Unsubscribe}};this.appendSubscribeResult(t.failSubscribeInfos,d),this.appendSubscribeResult(t.failUnsubscribeInfos,l)})),this.logger.info(CN,"getSubscribeExceptionResult. ".concat(this.getSubscribeResultString(t))),t}getSubscribeResultString(e){var t,r,i,n;let o;return null==e||null===(t=e.successSubscribeInfos)||void 0===t||t.forEach((e=>{o="".concat(o||""," subscribe success list: ").concat(this.getRemoteUserSubscribeInfoString(e),", ")})),null==e||null===(r=e.failSubscribeInfos)||void 0===r||r.forEach((e=>{o="".concat(o||""," subscribe failed list: ").concat(this.getRemoteUserSubscribeInfoString(e),",")})),null==e||null===(i=e.successUnsubscribeInfos)||void 0===i||i.forEach((e=>{o="".concat(o||""," unsubscribe success list: ").concat(this.getRemoteUserSubscribeInfoString(e),",")})),null==e||null===(n=e.failUnsubscribeInfos)||void 0===n||n.forEach((e=>{o="".concat(o||""," unsubscribe failed list: ").concat(this.getRemoteUserSubscribeInfoString(e))})),o}async rollbackResource(e){if(e&&0!==e.length)try{const t=[],r=[],i=[],n=[];e.forEach((e=>{var o,s,a,c;null===(o=e.mainStream)||void 0===o||null===(s=o.tracks)||void 0===s||s.forEach((e=>{e.type===vO.TRACK_TYPE_VIDEO?t.push(e.cssrc):r.push(e.cssrc)})),null===(a=e.auxStream)||void 0===a||null===(c=a.tracks)||void 0===c||c.forEach((e=>{e.type===vO.TRACK_TYPE_VIDEO?i.push(e.cssrc):n.push(e.cssrc)}))})),await this.batchDeleteUnusedSsrcInSdp(yO.STREAM_TYPE_MAIN,t,r),await this.batchDeleteUnusedSsrcInSdp(yO.STREAM_TYPE_AUX,i,n)}catch(jN){this.logger.error(CN,"rollbackResource fail, errMsg:".concat(jN))}}isNormalStateStream(e){const t=e.tracks.filter((e=>e.isTrackReady)),r=e.tracks.filter((e=>e.isTrackReady&&e.state===CO.normal));return t.length&&t.length===r.length}async handleReadyStream(e,t){var r,i,n,o;e===yO.STREAM_TYPE_MAIN&&(null===(r=t.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i?void 0:i.length)>0?await this.handleReadyStreamByType(t.userId,e,t.mainStream):e===yO.STREAM_TYPE_AUX&&(null===(n=t.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o?void 0:o.length)>0&&await this.handleReadyStreamByType(t.userId,e,t.auxStream)}async handleReadyStreamByType(e,t,r){this.logger.debug(CN,"handleReadyStreamByType, ".concat(t,", ").concat(JSON.stringify(r.tracks)));try{if(this.isNormalStateStream(r)&&(this.logger.info(CN,"emit ".concat(UC.StreamSubscribed,", userId: ").concat(e,", ").concat(t)),this.eventEmitter.emit(UC.StreamSubscribed,{stream:r.remoteStream}),t===yO.STREAM_TYPE_MAIN)){const t=setTimeout((async()=>{clearTimeout(t),this.reportMediaStatus(e,this.roomId)}),0)}const i=r.tracks.some((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.isTrackReady));for(const e of r.tracks)e.isTrackReady&&await this.handleReadyTrack(e,r.remoteStream,i)}catch(jN){this.logger.error(CN,"handleReadyStreamByType fail, errMsg:".concat(jN))}}getMediaNotifyInfo(e,t){const r=[],i=this.remoteUserManager.getAllUserStreamsByType(t,null,null);return null==i||i.forEach((i=>{if(i.userId!==e)return;const n=i.mainStream,o=null==n?void 0:n.tracks.find((e=>e.type===vO.TRACK_TYPE_AUDIO&&e.isTrackReady));if(o){const i={mediaType:vO.TRACK_TYPE_AUDIO,roomId:t,userId:e,status:o.mute?IC.MediaStatusUnavailable:IC.MediaStatusAvailable,reason:o.mute?RC.MediaUnmuted:RC.MediaMuted};r.push(i)}const s=null==n?void 0:n.tracks.find((e=>e.type===vO.TRACK_TYPE_VIDEO&&e.isTrackReady));if(s){const t={mediaType:vO.TRACK_TYPE_VIDEO,roomId:this.roomId,userId:e,status:s.mute?IC.MediaStatusUnavailable:IC.MediaStatusAvailable,reason:s.mute?RC.MediaUnmuted:RC.MediaMuted};r.push(t)}})),r}reportMediaStatus(e,t){this.getMediaNotifyInfo(e,t).forEach((t=>{const r=t.mediaType===vO.TRACK_TYPE_AUDIO?t.status===IC.MediaStatusAvailable?"UnmuteAudio":"MuteAudio":t.status===IC.MediaStatusAvailable?"UnmuteVideo":"MuteVideo";this.logger.info(CN,"emit ".concat(UC[r],", userId: ").concat(e,", type: ").concat(t.mediaType,", status: ").concat(t.status)),this.eventEmitter.emit(UC[r],t)}))}async handleReadyTrack(e,t,r){const i=e.type===vO.TRACK_TYPE_VIDEO||e.type===vO.TRACK_TYPE_AUDIO&&!r,n=[CO.remoteRejoinCache,CO.localRejoin,CO.resolutionChange].includes(e.state);i&&e.playElement&&n&&(this.logger.info(CN,"handleReadyTrack, auto play"),this.logger.info(CN,"video track.muted[".concat(e.muted,"]")),await t.play(e.playElement,{objectFit:e.objectFit,muted:e.muted,resolutionId:e.type===vO.TRACK_TYPE_VIDEO?e.trackId:null}));const o=e.type===vO.TRACK_TYPE_AUDIO,s=[CO.remoteRejoinCache,CO.localRejoin,CO.resolutionChange].includes(e.state);if(o&&e.playElement&&s){this.logger.info(CN,"audio track.muted[".concat(e.muted,"]"));const r=t.getAudioHRTCTrack();e.muted?r.muteTrack():r.unmuteTrack()}}async handleRemoteStreamsState(t){if(!t||0===t.length)return null;await this.waitForTrackBatch(t),this.logger.info(CN,"handleRemoteTracksState, waitForTrackBatch return");const r=[],i=[];for(const c of t){var n,o,s,a;const t=e.newRemoteUserSubscribeInfo(c.userId,this.roomId,null===(n=c.mainStream)||void 0===n?void 0:n.remoteStream,null===(o=c.auxStream)||void 0===o?void 0:o.remoteStream),u=e.newRemoteUserSubscribeInfo(c.userId,this.roomId,null===(s=c.mainStream)||void 0===s?void 0:s.remoteStream,null===(a=c.auxStream)||void 0===a?void 0:a.remoteStream);await this.handleRemoteStreamsStateByType(c,yO.STREAM_TYPE_MAIN,t,u),await this.handleRemoteStreamsStateByType(c,yO.STREAM_TYPE_AUX,t,u),(t.mainStream.tracks.length||t.auxStream.tracks.length)&&r.push(t),(u.mainStream.tracks.length||u.auxStream.tracks.length)&&i.push(u),this.stat.getMediaStat().setSubscribeInfo(c)}return{successSubscribeInfos:r,failSubscribeInfos:i,successUnsubscribeInfos:null,failUnsubscribeInfos:null}}isStreamTrackReady(e,t){const r=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream,i=null==r?void 0:r.remoteStream,n=null!=r&&r.tracks?Array.from(r.tracks.values()):null,o=null==n?void 0:n.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).map((e=>e.trackId)),s=null==n?void 0:n.some((e=>e.type===vO.TRACK_TYPE_AUDIO));return null==i?void 0:i.isTracksReady(o,s)}async handleRemoteStreamsStateByType(e,t,r,i){var n;const o=this.isStreamTrackReady(t,e);let s=e.mainStream,a=null===(n=e.mainStream)||void 0===n?void 0:n.tracks,c=r.mainStream,u=i.mainStream;var d;t===yO.STREAM_TYPE_AUX&&(s=e.auxStream,a=null===(d=e.auxStream)||void 0===d?void 0:d.tracks,c=r.auxStream,u=i.auxStream);let l=!1;var h,f;o?(null===(h=a)||void 0===h||h.forEach((e=>{e.isTrackReady=!0,l=!0})),a&&c.tracks.push(...a)):null===(f=a)||void 0===f||f.forEach((e=>{var t;null!==(t=s)&&void 0!==t&&t.remoteStream.isTrackReady(e.type,e.trackId)?(e.isTrackReady=!0,l=!0,c.tracks.push(e)):u.tracks.push(e)}));l&&await this.handleReadyStream(t,e)}getRemoteUserSubscribeInfoString(e){var t,r,i,n;if(!e)return"";let o,s;return null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{o="".concat(o||""," ").concat(JSON.stringify(e))})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{s="".concat(s||""," ").concat(JSON.stringify(e))}))," userId:".concat(e.userId,", mainTracks:").concat(o,", auxTracks:").concat(s," ")}releaseTrack(e,t){t.type===vO.TRACK_TYPE_VIDEO?(e.stop({audio:!1,video:!0,resolutionIds:[t.trackId]}),e.removeRemoteVideoTrack(t.trackId),this.logger.info(CN,"releaseTrack ".concat(t.type))):(e.stop({audio:!0}),e.removeRemoteAudioTrack(),this.logger.info(CN,"releaseTrack ".concat(t.type)))}clearResource(e){try{null==e||e.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Unsubscribe)||void 0===r||r.forEach((t=>{this.stat.getMediaStat().deleteSubscribeInfo(e.userInfo.userId,yO.STREAM_TYPE_MAIN,t.trackId),this.releaseTrack(e.mainStream.remoteStream,t)})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n||n.forEach((t=>{this.stat.getMediaStat().deleteSubscribeInfo(e.userInfo.userId,yO.STREAM_TYPE_AUX,t.trackId),this.releaseTrack(e.auxStream.remoteStream,t)}))}))}catch(jN){this.logger.error(CN,"clearResource error: ".concat(jN))}}async generateReceiveSdp(e,t,r,i){this.logger.info(CN,"generateReceiveSdp, stream type: ".concat(e,", removeVideoSsrcs: ").concat(r,", removeAudioSsrcs: ").concat(i));const n=t.some((t=>{var r;const i=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return(null==i||null===(r=i.tracks)||void 0===r?void 0:r.length)>0})),o=!!r.length||!!i.length;if(!n&&!o)return null;o&&await this.connectionsManager.deleteUser(e,r,i);const s=new Map;for(const u of t){var a,c;const t=e===yO.STREAM_TYPE_MAIN?null===(a=u.mainStream)||void 0===a?void 0:a.tracks:null===(c=u.auxStream)||void 0===c?void 0:c.tracks;if(t&&!(t.length<1))for(const r of t){this.logger.info(CN,"generateReceiveSdp, userId : ".concat(u.userId,", stream type: ").concat(e,", track type: ").concat(r.type,", ssrc: ").concat(r.cssrc));const t={streamId:r.trackId};r.type===vO.TRACK_TYPE_VIDEO?t.videoSsrc=r.cssrc:t.audioSsrc=r.cssrc,s.has(u.userId)?s.get(u.userId).push(t):s.set(u.userId,[t])}}await this.connectionsManager.addUserBatch(e,s)}static getWatchType4Ops(e){return 0===e?"cancel_watch":1===e?"watch":"batch_watch"}static isSubscriptionChange(e){return e.some((e=>{var t,r,i,n,o,s,a,c;return(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Subscribe)||void 0===r?void 0:r.length)>0||(null===(i=e.mainStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n?void 0:n.length)>0||(null===(o=e.auxStream)||void 0===o||null===(s=o.tracks4Subscribe)||void 0===s?void 0:s.length)>0||(null===(a=e.auxStream)||void 0===a||null===(c=a.tracks4Unsubscribe)||void 0===c?void 0:c.length)>0}))}appendSubscribeResult(e,t){var r,i,n,o;if(t&&(null!==(r=t.mainStream)&&void 0!==r&&null!==(i=r.tracks)&&void 0!==i&&i.length||null!==(n=t.auxStream)&&void 0!==n&&null!==(o=n.tracks)&&void 0!==o&&o.length)){const r=e.find((e=>e.userId===t.userId&&e.roomId===t.roomId));var s,a;if(r)null!==(s=r.mainStream)&&void 0!==s&&s.tracks?r.mainStream.tracks.push(...t.mainStream.tracks):r.mainStream=t.mainStream,null!==(a=r.auxStream)&&void 0!==a&&a.tracks?r.auxStream.tracks.push(...t.auxStream.tracks):r.auxStream=t.auxStream;else e.push(t)}}buildSubsReq(t,r){const i=[],n=[],o=[];return t.forEach((t=>{if(t.curUserState===bO.NotJoin){var s,a,c,u,d,l;const i=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(s=t.mainStream)||void 0===s?void 0:s.remoteStream,null===(a=t.auxStream)||void 0===a?void 0:a.remoteStream);null===(c=t.mainStream)||void 0===c||null===(u=c.tracks4Unsubscribe)||void 0===u||u.forEach((e=>{i.mainStream.tracks.push(e)})),null===(d=t.auxStream)||void 0===d||null===(l=d.tracks4Unsubscribe)||void 0===l||l.forEach((e=>{i.auxStream.tracks.push(e)})),this.appendSubscribeResult(r.successUnsubscribeInfos,i)}else{var h,f,p,m;o.push(t),null===(h=t.mainStream)||void 0===h||null===(f=h.allSubscribeTracks)||void 0===f||f.forEach((r=>{e.getUserTrackSubscribeInfo(t.userInfo,i,n,r)})),null===(p=t.auxStream)||void 0===p||null===(m=p.allSubscribeTracks)||void 0===m||m.forEach((r=>{e.getUserTrackSubscribeInfo(t.userInfo,i,n,r)}))}})),{videoSubscribeInfos:i,audioSubscribeInfos:n,joinUserUpdateInfos:o}}async subscribeSignal(t,r,i){const n=this.buildSubsReq(t,r);if(!e.isSubscriptionChange(n.joinUserUpdateInfos))return;const o=e.getWatchType4Ops(n.videoSubscribeInfos.length);let s;this.logger.info(CN,"subscribeSignal, fullVideoSubscribeInfos: ".concat(JSON.stringify(n.videoSubscribeInfos)," ,")+"fullAudioSubscribeInfos: ".concat(JSON.stringify(n.audioSubscribeInfos)));let a=null;const c=XR.getCurrentTimestamp();if(i){const e={timestamp:i.start,traceId:i.traceId,spanId:"0",originIntfName:"",interfaceName:"subscribe",source:"",target:"",resultCode:"",successFlag:"T",duration:c-i.start,async:"N",extendInfo:JSON.stringify({id:i.id})};this.stat.setFirstFrameInfo(e)}try{a=this.status!==OC.Leaving?await this.signal.subscribe(n.videoSubscribeInfos,n.audioSubscribeInfos,o):this.buildDefaultSubsRep(n)}catch(Dw){throw s=Dw,Dw}finally{if(i){const e=XR.getCurrentTimestamp(),t={timestamp:c,traceId:i.traceId,spanId:"0.1",originIntfName:i.interfaceName,interfaceName:"subscribeSignal",source:"",target:"",resultCode:"",successFlag:s?"F":"T",duration:e-c,async:"N",extendInfo:JSON.stringify({id:i.id,streamIds:i.streamIds})};this.stat.setFirstFrameInfo(t),i.interfaceName="subscribeSignal",i.start=e,this.startupQoSMap.set(i.id,i)}}a.audioUpstreams||a.videoUpstreams||this.logger.error(CN,"subscribeSignal, subscribe stream subscribed no result record, subsResult:".concat(JSON.stringify(a)));const u=e.getUserUpdateInfos(n.joinUserUpdateInfos);this.getSubscribeResult(u,a.videoUpstreams,a.audioUpstreams,r)}buildDefaultSubsRep(e){const t=[];e.videoSubscribeInfos.forEach((e=>{t.push({cSsrcId:e.cSsrcId,code:0,pSsrcId:e.pSsrcId,pStreamUid:e.pStreamUid,pUserId:e.pUserId,pUserUid:e.pUserUid})}));const r=[];return e.audioSubscribeInfos.forEach((e=>{r.push({cSsrcId:e.cSsrcId,code:0,pSsrcId:e.pSsrcId,pStreamUid:e.pStreamUid,pUserId:e.pUserId,pUserUid:e.pUserUid})})),{audioUpstreams:r,videoUpstreams:t}}static getUserTrackSubscribeInfo(e,t,r,i){const n={pSsrcId:i.pssrc,cSsrcId:i.cssrc,pStreamUid:parseInt(i.trackId),pUserId:e.userId,pUserUid:e.userUid};i.type===vO.TRACK_TYPE_AUDIO?r.push(n):(n.mediaData={width:i.width,height:i.height,maxFps:60},i.autoAdjustResolution===DC.ON&&(n.minReceiveContent=bN[i.minResolution]),t.push(n))}static getUserUpdateInfos(e){return e.filter((e=>{var t,r,i,n,o,s,a,c;return(null===(t=e.mainStream)||void 0===t||null===(r=t.allSubscribeTracks)||void 0===r?void 0:r.length)>0||(null===(i=e.mainStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n?void 0:n.length)>0||(null===(o=e.auxStream)||void 0===o||null===(s=o.allSubscribeTracks)||void 0===s?void 0:s.length)>0||(null===(a=e.auxStream)||void 0===a||null===(c=a.tracks4Unsubscribe)||void 0===c?void 0:c.length)>0}))}getSubscribeResult(e,t,r,i,n){const o=new Map;null==t||t.forEach((e=>{const t=e.pUserId+"#"+this.roomId,r=o.get(t);if(r)r.tracks.push(e);else{const r={userId:e.pUserId,userUid:e.pStreamUid,tracks:[e]};o.set(t,r)}})),null==r||r.forEach((e=>{const t=e.pUserId+"#"+this.roomId,r=o.get(t);if(r)r.tracks.push(e);else{const r={userId:e.pUserId,userUid:e.pStreamUid,tracks:[e]};o.set(t,r)}})),e.forEach((e=>{this.getStreamSubscribeResult(e,!0,o,i)})),e.forEach((e=>{this.getStreamSubscribeResult(e,!1,o,i)})),this.logger.info(CN,"isRealSubsAction: ".concat(n,", getSubscribeResult success, ").concat(this.getSubscribeResultString(i)))}getStreamSubscribeResult(t,r,i,n){var o,s,a,c;if(!r)return this.handleUnsubscribeReq(yO.STREAM_TYPE_MAIN,t,n),void this.handleUnsubscribeReq(yO.STREAM_TYPE_AUX,t,n);const u=n.successSubscribeInfos,d=n.failSubscribeInfos,l=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(o=t.mainStream)||void 0===o?void 0:o.remoteStream,null===(s=t.auxStream)||void 0===s?void 0:s.remoteStream),h=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(a=t.mainStream)||void 0===a?void 0:a.remoteStream,null===(c=t.auxStream)||void 0===c?void 0:c.remoteStream),f=t.userInfo.userId+"#"+this.roomId,p=i.get(f);var m,g,_,S;if(!p&&this.hasTrackSignalReq(t))return d.push({userId:t.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(m=t.mainStream)||void 0===m?void 0:m.remoteStream,tracks:null===(g=t.mainStream)||void 0===g?void 0:g.tracks4Subscribe},auxStream:{remoteStream:null===(_=t.auxStream)||void 0===_?void 0:_.remoteStream,tracks:null===(S=t.auxStream)||void 0===S?void 0:S.tracks4Subscribe}}),void this.logger.error(CN,"subscribe user ".concat(t.userInfo.userId,", isSubscribe: ").concat(r," subscribed failed,mcs not response"));this.getTracksSubscribeResults(r,t,p,l,h),this.appendToSubscribeResult(l,u,h,d)}appendToSubscribeResult(e,t,r,i){var n,o,s,a,c,u,d,l;((null===(n=e.mainStream)||void 0===n||null===(o=n.tracks)||void 0===o?void 0:o.length)>0||(null===(s=e.auxStream)||void 0===s||null===(a=s.tracks)||void 0===a?void 0:a.length)>0)&&this.appendSubscribeResult(t,e),((null===(c=r.mainStream)||void 0===c||null===(u=c.tracks)||void 0===u?void 0:u.length)>0||(null===(d=r.auxStream)||void 0===d||null===(l=d.tracks)||void 0===l?void 0:l.length)>0)&&this.appendSubscribeResult(i,r)}static newRemoteUserSubscribeInfo(e,t,r,i){return{userId:e,roomId:t,mainStream:{remoteStream:r,tracks:[]},auxStream:{remoteStream:i,tracks:[]}}}handleUnsubscribeReq(e,t,r){const i=e===yO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream,n=null==i?void 0:i.tracks4Unsubscribe;if(null!=n&&n.length){var o,s,a,c,u;const d=null===(o=i.tracks4Subscribe)||void 0===o?void 0:o.some((e=>e.state===CO.remoteRejoinCache)),l=r.successSubscribeInfos.find((e=>e.userId===t.userInfo.userId&&e.roomId===t.userInfo.roomId)),h=e===yO.STREAM_TYPE_MAIN?null==l||null===(s=l.mainStream)||void 0===s?void 0:s.tracks:null==l||null===(a=l.auxStream)||void 0===a?void 0:a.tracks,f=!h||0===(null==h?void 0:h.filter((e=>e.state===CO.remoteRejoinCache)).length),p={userId:t.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(c=t.mainStream)||void 0===c?void 0:c.remoteStream,tracks:e===yO.STREAM_TYPE_MAIN?n:[]},auxStream:{remoteStream:null===(u=t.auxStream)||void 0===u?void 0:u.remoteStream,tracks:e===yO.STREAM_TYPE_AUX?n:[]}};this.logger.info(CN,"handleUnsubscribeReq, hasSubscribeReq:".concat(d,", allSubscribeReqFailed:").concat(f)),d&&f?this.appendSubscribeResult(r.failUnsubscribeInfos,p):this.appendSubscribeResult(r.successUnsubscribeInfos,p)}}hasTrackSignalReq(e){var t,r,i,n;return(null===(t=e.mainStream)||void 0===t||null===(r=t.allSubscribeTracks)||void 0===r?void 0:r.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).length)>0||(null===(i=e.auxStream)||void 0===i||null===(n=i.allSubscribeTracks)||void 0===n?void 0:n.filter((e=>e.type===vO.TRACK_TYPE_VIDEO)).length)>0}getTracksSubscribeResults(e,t,r,i,n){var o,s,a,c;const u=e?null===(o=t.mainStream)||void 0===o?void 0:o.tracks4Subscribe:null===(s=t.mainStream)||void 0===s?void 0:s.tracks4Unsubscribe;null==u||u.forEach((o=>{this.getTrackSubscribeResult(e,t.userInfo.userId,o,yO.STREAM_TYPE_MAIN,r,i,n)}));const d=e?null===(a=t.auxStream)||void 0===a?void 0:a.tracks4Subscribe:null===(c=t.auxStream)||void 0===c?void 0:c.tracks4Unsubscribe;null==d||d.forEach((o=>{this.getTrackSubscribeResult(e,t.userInfo.userId,o,yO.STREAM_TYPE_AUX,r,i,n)}))}getTrackSubscribeResult(e,t,r,i,n,o,s){var a;const c=i===yO.STREAM_TYPE_MAIN?s.mainStream:s.auxStream,u=i===yO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,d=null==n||null===(a=n.tracks)||void 0===a?void 0:a.find((e=>e.cSsrcId===r.cssrc));d?0!==d.code?(c.tracks.push(r),this.logger.error(CN,"isSubscribe:".concat(e,", subscribe user ").concat(t," ").concat(i," streamUid:").concat(d.pStreamUid," subscribed failed,code:").concat(d.code))):u.tracks.push(r):this.logger.error(CN,"isSubscribe:".concat(e,", subscribe user ").concat(t,", ").concat(i,"\n track req id: ").concat(r.trackId,", ssrc ").concat(r.cssrc," subscribed failed,mcs not response"))}async updateUserList(e){this.logger.info(CN,"updateUserList start");try{e.infos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(String(e.userId),String(e.userEid))})),await this.locker.lock("".concat(CN,":updateUserList"));const t=this.remoteUserManager.updateUserListInfo(this.roomId,e.infos);if(this.logger.info(CN,"updateUserList , begin"),!t||0===t.length)return void this.logger.error(CN,"updateUserList , userUpdateInfos is null");t.forEach((e=>{if(e.isUserNameChanged&&(this.logger.info(CN,"emit ".concat(UC.UserNameChanged,", ").concat(e.userInfo.userId,"}")),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:e.userInfo.userId,userName:e.userInfo.nickname})),e.preUserState===bO.NotJoin&&e.curUserState===bO.Joined)this.logger.info(CN,"emit ".concat(UC.PeerJoin,", ").concat(e.userInfo.userId,":").concat(e.userInfo.nickname)),this.eventEmitter.emit(UC.PeerJoin,{userId:e.userInfo.userId,userName:e.userInfo.nickname,roomId:e.userInfo.roomId,relayRoomId:e.userInfo.relaySrcRoomId});else if(e.preUserState===bO.Joined&&e.curUserState===bO.NotJoin){var t,r,i,n;(null===(t=e.mainStream)||void 0===t||null===(r=t.removedTracks)||void 0===r?void 0:r.length)>0&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(e.userInfo.userId,", ").concat(yO.STREAM_TYPE_MAIN)),this.eventEmitter.emit(UC.StreamRemoved,{stream:e.mainStream.remoteStream})),(null===(i=e.auxStream)||void 0===i||null===(n=i.removedTracks)||void 0===n?void 0:n.length)>0&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(e.userInfo.userId,", ").concat(yO.STREAM_TYPE_AUX)),this.eventEmitter.emit(UC.StreamRemoved,{stream:e.auxStream.remoteStream})),this.logger.info(CN,"emit ".concat(UC.PeerLeave,", ").concat(e.userInfo.userId)),this.eventEmitter.emit(UC.PeerLeave,{userId:e.userInfo.userId,userName:e.userInfo.nickname,roomId:e.userInfo.roomId,relayRoomId:e.userInfo.relaySrcRoomId,reason:MC.HRTC_LEAVE_REASON_USER_LEAVE_ROOM}),this.stat.getMediaStat().updateAudioStreamInfos(e.userInfo.userId,"removed")}})),await this.updateSubscribe(t)}catch(jN){this.logger.error(CN,"updateUserList occur exception ".concat(jN))}finally{this.locker.unlock("".concat(CN,":updateUserList"))}}async refreshRemoteStreamList(e){this.logger.info(CN,"refreshRemoteStreamList start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};e.allAudioStreams=e.allAudioStreams.filter((e=>"cmd"!==e.content));const r=this.remoteUserManager.refreshRemoteStreamList(t,e.allVideoStreams,e.allAudioStreams);if(this.logger.info(CN,"refreshRemoteStreamList begin"),!r||0===r.length)return void this.logger.error(CN,"refreshRemoteStreamList , userUpdateInfos is null");const i=r.find((t=>t.userInfo.userId===e.userId));this.updateSingleUser(i),await this.updateSubscribe(r)}catch(jN){this.logger.error(CN,"refreshRemoteStreamList occur exception ".concat(jN))}}updateSingleUser(t){var r,i;t.isUserNameChanged&&(this.logger.info(CN,"emit ".concat(UC.UserNameChanged,", ").concat(t.userInfo.userId,"}")),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:t.userInfo.userId,userName:t.userInfo.nickname})),t.preUserState===bO.NotJoin&&t.curUserState===bO.Joined&&(this.logger.info(CN,"emit ".concat(UC.PeerJoin,", ").concat(t.userInfo.userId,":").concat(t.userInfo.nickname)),this.eventEmitter.emit(UC.PeerJoin,{userId:t.userInfo.userId,userName:t.userInfo.nickname,roomId:t.userInfo.roomId,relayRoomId:t.userInfo.relaySrcRoomId}));const n=null===(r=t.mainStream)||void 0===r?void 0:r.remoteStream;n&&(e.isStreamAdd(yO.STREAM_TYPE_MAIN,t)?(this.logger.info(CN,"emit ".concat(UC.StreamAdded,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamAdded,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"add",n)):e.isStreamRemove(yO.STREAM_TYPE_MAIN,t)?(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamRemoved,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"removed",n)):e.isStreamUpdate(yO.STREAM_TYPE_MAIN,t)&&(this.logger.info(CN,"emit ".concat(UC.StreamUpdated,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamUpdated,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"update",n)));const o=null===(i=t.auxStream)||void 0===i?void 0:i.remoteStream;o&&(e.isStreamAdd(yO.STREAM_TYPE_AUX,t)?(this.logger.info(CN,"emit ".concat(UC.StreamAdded,", ").concat(t.userInfo.userId,", ").concat(o.getType(),"}")),this.eventEmitter.emit(UC.StreamAdded,{stream:o})):e.isStreamRemove(yO.STREAM_TYPE_AUX,t)&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(t.userInfo.userId,", ").concat(o.getType(),"}")),this.eventEmitter.emit(UC.StreamRemoved,{stream:o}))),t.preUserState===bO.Joined&&t.curUserState===bO.NotJoin&&(this.logger.info(CN,"emit ".concat(UC.PeerLeave,", ").concat(t.userInfo.userId)),this.eventEmitter.emit(UC.PeerLeave,{userId:t.userInfo.userId,userName:t.userInfo.nickname,roomId:t.userInfo.roomId,relayRoomId:t.userInfo.relaySrcRoomId,reason:MC.HRTC_LEAVE_REASON_USER_LEAVE_ROOM}),this.stat.getMediaStat().updateAudioStreamInfos(t.userInfo.userId,"removed")),this.handleMuteStatus(t)}updateAudioStreamInfo(e,t,r){var i;if("add"===t)null!==(i=r.getStreamInfo())&&void 0!==i&&i.audioProfile&&this.stat.getMediaStat().updateAudioStreamInfos(e,"add");else if("removed"===t)this.stat.getMediaStat().updateAudioStreamInfos(e,"removed");else{var n;null!==(n=r.getStreamInfo())&&void 0!==n&&n.audioProfile?this.stat.getMediaStat().updateAudioStreamInfos(e,"add"):this.stat.getMediaStat().updateAudioStreamInfos(e,"removed")}}remoteUserDisconnectNotify(e){e&&this.logger.info(CN,"remoteDisconnectNotify, userId:".concat(e.userId))}remoteUserReconnectNotify(e){if(!e)return;this.logger.info(CN,"remoteReconnectNotify, userId:".concat(e.userId));const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};this.remoteUserManager.remoteUserReconnect(t,e.videoStreams,e.audioStreams)}updateAppData(e){const t=e.userId,r=e.appData.nickname;t&&e.userId!==this.userInfo.userId&&(this.remoteUserManager.updateUserName(t,this.roomId,r),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:t,userName:r}))}async updateRemoteStream(e){this.logger.info(CN,"updateRemoteStream start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null},r=this.remoteUserManager.updateRemoteStream(t,e.videoStreams,e.audioStreams);if(this.logger.info(CN,"updateRemoteStream , begin"),!r)return void this.logger.error(CN,"updateRemoteStream , userUpdateInfos is null");this.handleMuteStatus(r)}catch(jN){this.logger.error(CN,"updateRemoteStream occur exception ".concat(jN))}}handleMuteStatus(t){this.logger.info(CN,"handleMuteStatus begin");const r=e.getMuteChangeStatus(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO,t);r!==EN.noChange&&(this.emitMediaStatusChange(t.userInfo.userId,t.userInfo.roomId,vO.TRACK_TYPE_AUDIO,r),r===EN.unmute?this.stat.getMediaStat().updateAudioStreamInfos(this.userInfo.userId,"add"):this.stat.getMediaStat().updateAudioStreamInfos(this.userInfo.userId,"removed"));const i=e.getMuteChangeStatus(yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_VIDEO,t);i!==EN.noChange&&this.emitMediaStatusChange(t.userInfo.userId,t.userInfo.roomId,vO.TRACK_TYPE_VIDEO,i)}async removeRemoteStream(e){this.logger.info(CN,"removeRemoteStream start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};e.allAudioStreams=e.allAudioStreams.filter((e=>"cmd"!==e.content));const r=this.remoteUserManager.refreshRemoteStreamList(t,e.allVideoStreams,e.allAudioStreams);if(this.logger.info(CN,"removeRemoteStream begin"),!r||0===r.length)return void this.logger.error(CN,"removeRemoteStream , userUpdateInfos is null");const i=r.find((t=>t.userInfo.userId===e.userId));this.updateSingleUser(i),await this.updateSubscribe(r)}catch(jN){this.logger.error(CN,"removeRemoteStream occur exception ".concat(jN))}}emitMediaStatusChange(e,t,r,i){const n={roomId:t,userId:e,status:i===EN.unmute?IC.MediaStatusAvailable:IC.MediaStatusUnavailable,reason:i===EN.unmute?RC.MediaUnmuted:RC.MediaMuted},o=r===vO.TRACK_TYPE_AUDIO?i===EN.unmute?"UnmuteAudio":"MuteAudio":i===EN.unmute?"UnmuteVideo":"MuteVideo";this.logger.info(CN,"emit ".concat(UC[o],", userId: ").concat(e,", type: ").concat(r,", status: ").concat(n.status)),this.eventEmitter.emit(UC[o],n)}waitNotifyConfig(e){return new Promise(((t,r)=>{const i={id:e.length+1,domain:"",start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"configNotify",rspCode:"",errMsg:""};let n=null;this.waitConfigCallbackFunc=()=>{clearTimeout(n),t(),i.delay_ms=XR.getCurrentTimestamp()-i.start_ms,i.rspCode="OK",e.push(i)},this.validSignatureFunc=e=>{clearTimeout(n),r(new qc(e.code,e.message))},n=setTimeout((()=>{this.logger.error(CN,"wait config timeout"),i.rspCode="".concat(Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL),i.errMsg=Jc[Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL],i.delay_ms=XR.getCurrentTimestamp()-i.start_ms,e.push(i),t()}),fA)}))}handleConfigNotifyBody(e){const{controlDisconnectTimeout:t="30",controlHoldTimeout:r="120",controlPingPeriod:i="5"}=e.appConfigs||{};this.sfuConfigs={};for(const o of IA)Object.prototype.hasOwnProperty.call(e.appConfigs,o)&&(this.sfuConfigs[o]=e.appConfigs[o]);const n={heartBeatRetryTimes:parseInt(t)/parseInt(i)||mA,connectionTimeout:parseInt(r)||gA,heartBeatPeriod:parseInt(i)||pA};this.waitConfigCallbackFunc&&this.waitConfigCallbackFunc(),this.stat.setTraceInfo(e.traceId),TD.setLogServerConfigs(e.logServerConfigs),this.signal.setConfigParams(n)}async uploadLog(e){await TD.uploadLogFile(this,e)}async handleWatchMsg(e){if(null!=e)try{const t=e,r=t.videoSsrcIds,i=t.audioSsrcIds;if(this.sdpRepInfo.cmd&&(null==i?void 0:i.length)>0&&0===i.filter((e=>this.sdpRepInfo.cmd.sendSsrc!==e)).length)return;const n=r.filter((e=>this.sdpRepInfo.video.sendSsrcRange.find((t=>e===t)))),o=r.filter((e=>this.sdpRepInfo.desktopVideo.sendSsrcRange.find((t=>e===t)))),s=[],a=[],c={mainStreamVideoTracks2Update:{},mainStreamAudioTracks2Update:{},auxStreamTracks2Update:{}},u=this.streamPublishManager.generatePubInfoWhenWatch(yO.STREAM_TYPE_MAIN,n,i||[],vO.TRACK_TYPE_VIDEO);if(await this.publishWhenWatch(yO.STREAM_TYPE_MAIN,u),n&&n.length>0&&(null==u||u.tracks2NewPublish.forEach((e=>{r.find((t=>t===e.ssrc))&&s.push({ssrcId:e.ssrc,status:0})})),null==u||u.tracks2KeepPublish.forEach((e=>{s.push({ssrcId:e.ssrc,status:0})})),c.mainStreamVideoTracks2Update=u),i&&i.length>0){const e=this.streamPublishManager.generatePubInfoWhenWatch(yO.STREAM_TYPE_MAIN,[],i);await this.publishWhenWatch(yO.STREAM_TYPE_MAIN,e),null==e||e.tracks2NewPublish.forEach((e=>{i.find((t=>t===e.ssrc))&&a.push({ssrcId:e.ssrc,status:0})})),null==e||e.tracks2KeepPublish.forEach((e=>{a.push({ssrcId:e.ssrc,status:0})})),c.mainStreamAudioTracks2Update=e}if(o&&o.length>0){const e=this.streamPublishManager.generatePubInfoWhenWatch(yO.STREAM_TYPE_AUX,o,[]);await this.publishWhenWatch(yO.STREAM_TYPE_AUX,e),null==e||e.tracks2NewPublish.forEach((e=>{r.find((t=>t===e.ssrc))&&s.push({ssrcId:e.ssrc,status:0})})),null==e||e.tracks2KeepPublish.forEach((e=>{s.push({ssrcId:e.ssrc,status:0})})),c.auxStreamTracks2Update=e}this.logger.info(CN,"handle watch success, videoSsrcs: ".concat(JSON.stringify(r),", audioSsrcs: ").concat(JSON.stringify(i)));const d=this.stat.getSpanId(t["x-nuwa-span-id"]),l=XR.generateRandomId(16,16);this.stat.setParentSpanId(l,d);const h={type:"WATCH_STREAM_NOTIFY",requestId:t.requestId,traceId:t.traceId,version:t.version,videoSsrcIds:s,audioSsrcIds:a,"x-nuwa-trace-id":t["x-nuwa-trace-id"],"x-nuwa-span-id":l};await this.signal.pushStreamResponse(h),this.reportMediaStreamInfo(c,s),this.logger.info(CN,"handleWatchMsg success")}catch(jN){this.logger.error(CN,"handleWatchMsg occur error ".concat(jN))}else this.logger.error(CN,"message is null")}reportMediaStreamInfo(e,t){var r,i,n,o;if(null!==(r=e.mainStreamVideoTracks2Update)&&void 0!==r&&null!==(i=r.tracks2NewPublish)&&void 0!==i&&i.find((e=>e.type===vO.TRACK_TYPE_VIDEO))){this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos())&&this.buildSendMediaStreamInfo(TC.Video,t)}if(null!==(n=e.auxStreamTracks2Update)&&void 0!==n&&null!==(o=n.tracks2NewPublish)&&void 0!==o&&o.filter((e=>e.type===vO.TRACK_TYPE_VIDEO))){this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo())&&this.buildSendMediaStreamInfo(TC.Aux)}}async publishWhenWatch(e,t){if(!t||0===t.tracks2NewPublish.length&&0===t.tracks2KeepPublish.length&&0===t.tracks2UnPublish.length)return void this.logger.info(CN,"handleWatchMsg, watched track no update");const r=this.streamPublishManager.getLocalStream(e);await this.sendPublishRequest(t.allTracks2Publish),await this.startStreamResolutionDetection(r),await this.updateStreamTracks(r,t),this.logger.info(CN,"handleWatchMsg, published stream")}setCameraCaptureReport(e,t){this.stat.setCameraInfo(e,t)}signalEvent(){this.signal.on(bC.watchStreamNotify,(e=>{this.handleWatchMsg(e)})),this.signal.on(bC.pushStreamNotify,(e=>{this.refreshRemoteStreamList(e)})),this.signal.on(bC.stopPushStreamNotify,(e=>{this.removeRemoteStream(e)})),this.signal.on(bC.changeStreamStatusNotify,(e=>{this.updateRemoteStream(e)})),this.signal.on(bC.appDataChangeNotify,(e=>{this.updateAppData(e)})),this.signal.on(bC.disconnectNotify,(e=>{this.remoteUserDisconnectNotify(e)})),this.signal.on(bC.reconnectNotify,(e=>{this.remoteUserReconnectNotify(e)})),this.signal.on(bC.configNotify,(e=>{this.handleConfigNotifyBody(e)})),this.signal.on(bC.top3AudioVolumeNotify,(e=>{this.handleMaxVolumeNotify(e)})),this.signal.on(bC.statusChangeNotify,(async e=>{await this.updateUserList(e)})),this.signal.on(bC.uploadLogNotify,(async e=>{await this.uploadLog(e)})),this.signal.on(bC.publishStatusNotify,(e=>{this.handlePublishStatusNotify(e)})),this.signal.on(dM.Reconnected,(async()=>{await this.refreshRoomUserInfos()})),this.signal.on(dM.SessionUnavailable,(async()=>{this.logger.info(CN,"".concat(dM.SessionUnavailable));await this.rejoinLoop(120)})),this.signal.on(dM.ConnectionUnavailable,(async()=>{this.logger.info(CN,"".concat(dM.ConnectionUnavailable));await this.rejoinLoop(120)})),this.signal.on(dM.AuthenticateFail,(async()=>{this.logger.info(CN,"".concat(dM.AuthenticateFail)),this.doLeaveRoom()})),this.signal.on(dM.SignatureExpired,(e=>{this.handleNotifySignatureExpired(e)})),this.signal.on(UC.ConnectionStateChanged,(e=>{this.handleNotifyConnectStateChange(e)})),this.signal.on(UC.NetworkQuality,(e=>{this.eventEmitter.emit(UC.NetworkQuality,e)})),this.signal.on(dM.ClientBanned,(()=>{this.kickRoom()})),this.signal.on(bC.roomStreamStatusNotify,(e=>{this.handleNotifyRoomStreamStatus(e)}))}kickRoom(){this.eventEmitter.emit(UC.ClientBanned,{userId:this.userInfo.userId}),this.cleanup(),this.cleanTransportStats(),this.stat.leaveRoom(),cO.immediateReportRecords(),this.logger.info(CN,"kick leave success")}async refreshRoomUserInfos(){const e=await this.signal.queryRoomUsers(null);await this.doRefreshRoomUserInfos(this.roomId,e.userInfos,!1)}async doRefreshRoomUserInfos(e,t,r){try{this.logger.debug(CN,"doRefreshRoomUserInfos, begin");const i=this.remoteUserManager.refreshRemoteUserList(e,t,r);if(!i)return null;i.forEach((e=>{this.updateSingleUser(e)})),await this.updateSubscribe(i)}catch(jN){this.logger.error(CN,"doRefreshRoomUserInfos, error:".concat(jN))}}async rejoinLoop(e){if(this.isLoopRejoining)this.logger.info(CN,"rejoinLoop, isLoopRejoining so return");else try{this.isLoopRejoining=!0;const t=async e=>await this.handleRejoin(e),r=e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_STATUS_ERROR;return await mP.callWithRetryTimes(t,!1,e,RN,r)}catch(jN){this.logger.error(CN,"rejoinLoop, rejoin room failed, leave room, error:".concat(jN)),this.localRejoinFlag||(this.connectState={prevState:vC[yC.RECONNECTING],curState:vC[yC.DISCONNECTED]},this.eventEmitter.emit(UC.ConnectionStateChanged,this.connectState));try{await this.leaveImpl()}catch(jN){this.logger.error(CN,"rejoinLoop, leave failed, error:".concat(jN))}}finally{this.isLoopRejoining=!1}}async handleRejoin(e){if(this.logger.info(CN,"handleRejoin, client status: ".concat(this.status,", tryNumber:").concat(e)),this.status===OC.Idle)throw this.logger.error(CN,"handleRejoin, status:".concat(OC.Idle)),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"handleRejoin but status is Idle");if(this.isSignatureExpired){if(this.signatureExpiredRejoinTimeout)return void this.logger.info(CN,"signature expired, try rejoin, timer already exists");this.signatureExpiredRejoinTimeout=setTimeout((()=>{throw this.logger.error(CN,"handleRejoin, signature expired and retry limit, exit"),this.cleanup(),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"handleRejoin but signature expired")}),2e4)}try{await this.locker.lock("".concat(CN,":handleRejoin")),this.status=OC.Rejoining,await this.rejoin(this.roomId,uM.transLocalUserToJoinConfig(this.userInfo)),this.getSessionStatus()===OC.Joined&&(this.logger.info(CN,"handleRejoin, rejoin room success"),this.isSignatureExpired=!1,clearTimeout(this.signatureExpiredRejoinTimeout),this.signatureExpiredRejoinTimeout=void 0,this.connectState={prevState:vC[yC.RECONNECTING],curState:vC[yC.CONNECTED]},this.eventEmitter.emit(UC.ConnectionStateChanged,this.connectState),await this.rejoinPublish(),this.localRejoinFlag=!1)}finally{this.locker.unlock("".concat(CN,":handleRejoin"))}}async rejoinPublish(){this.logger.info(CN,"rejoin publish stream"),this.connectState.prevState=vC[yC.DISCONNECTED];const e=[],t=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN),r=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_AUX);t&&e.push(t),r&&e.push(r),e.length>0&&await this.rejoinPublishStreams(e)}handleNotifySignatureExpired(e){this.logger.warn(CN,"handleNotifySignatureExpired");const t={code:0,reason:""};"reconnect"===e.type?(this.logger.warn(CN,"reconnect but signature expired"),t.code=Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]):this.isLoopRejoining?(this.logger.warn(CN,"rejoin but signature expired"),this.isSignatureExpired=!0,t.code=Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]):(t.code=Gc.RTC_ERR_CODE_SIGNATURE_INVALID,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_INVALID]),this.validSignatureFunc&&this.validSignatureFunc(t),this.validSignatureFunc=void 0;const r={errorCode:"".concat(t.code),errorMsg:t.reason};this.eventEmitter.emit(UC.SignatureExpired,r)}handleNotifyConnectStateChange(e){this.logger.info(CN,"ConnectStateChange"),this.eventEmitter.emit(UC.ConnectionStateChanged,e),this.connectState.curState=e.curState}cleanNetworkStatistic(){this.preNetQuality=null,this.downLinkData=null,this.upLinkData=null}cleanup(){var e,t,r;null===(e=this.signal)||void 0===e||e.disconnect(),this.signal=void 0,this.resetConnection(),null===(t=this.remoteUserManager)||void 0===t||t.clear(this.roomId);const i=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN);if(i){i.removeClient(this)}this.streamPublishManager.reset(),clearTimeout(this.streamInterruptedDetectInterval),clearTimeout(this.rtcStatsInterval),clearTimeout(this.netQualityTimer),clearTimeout(this.transportStatsTimer),OO.reset(),this.cleanNetworkStatistic(),this.streamInterruptedDetectInterval=null,this.rtcStatsInterval=null,this.lastCycleFrameDecodedMap.clear(),this.streamInterruptedUsersMap.clear(),this.startupQoSMap.clear(),this.status=OC.Idle,this.locker.clear(),clearInterval(this.audioLevelTimer),ED.stopRelayConnection(this,this.roomId),null===(r=this.cmdMsgAbility.cmdManager)||void 0===r||r.reset(),this.isSignatureExpired=!1,clearTimeout(this.signatureExpiredRejoinTimeout),this.signatureExpiredRejoinTimeout=void 0}async addSsrc4Top3(e){var t;return this.audioStreams4TopN.close(),await this.addSsrc2SdpBatch(e,null===(t=this.sdpRepInfo.audio)||void 0===t?void 0:t.topNSsrcBegin)}setAudioLevelStatTimer(){this.audioLevelTimer&&clearInterval(this.audioLevelTimer),this.logger.info(CN,"setAudioLevelStatTimer"),this.audioLevelTimer=setInterval((()=>{try{this.audioStreams4TopN.getAudioLevel().forEach((e=>{const t=Math.round(100*e.level);this.stat.getMediaStat().updateAudioLevel({type:"remotetop3",level:t,ssrc:e.ssrc})}));const e=this.remoteUserManager.getAllUserStreamsByType(this.roomId,yO.STREAM_TYPE_MAIN,vO.TRACK_TYPE_AUDIO),t=[];e.forEach((e=>{const r=e.mainStream.tracks.find((e=>e.isTrackReady&&e.type===vO.TRACK_TYPE_AUDIO&&e.isSubscribed));r&&t.push({userId:e.userId,ssrc:r.cssrc})}));for(const n of t){const e=this.remoteUserManager.getUserInfoById(n.userId,this.roomId),t=Math.round(100*e.mainStream.remoteStream.getAudioLevel());this.stat.getMediaStat().updateAudioLevel({type:"remote",level:t,ssrc:n.ssrc,userId:n.userId})}const r=this.streamPublishManager.getLocalStream(yO.STREAM_TYPE_MAIN),i=Math.round(100*(r?r.getAudioLevel():0));this.stat.getMediaStat().updateAudioLevel({type:"local",level:i})}catch(jN){this.logger.error(CN,"setAudioLevelStatTimer, occur error: ".concat(jN))}}),this.audioLevelInterval)}async addSsrc2SdpBatch(e,t){if(!t)return null;const r={answerSdp:e},i=await this.connectionsManager.addTopAudioUserBatch(r.answerSdp,t,3,((e,t)=>{this.audioStreams4TopN.addAudioStream(e,t)}));return this.stat.getMediaStat().setStartSsrc(t),i}async saveAudioStream4TopN(e){this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, save audio stream, streamId: ".concat(e.streams[0].id));if(null!=this.audioStreams4TopN.getAudioStream(e.streams[0].id)){this.audioStreams4TopN.updateAudioStream(e.streams[0].id,e.track),this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, save audio stream ok, streamId: ".concat(e.streams[0].id));try{await this.audioStreams4TopN.play(e.streams[0].id),this.audioStreams4TopN.setAudioVolume4Id(e.streams[0].id,this.topNAudioVolume),this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, auto play audio success, streamId: ".concat(e.streams[0].id))}catch(e){this.logger.error(CN,"AudioPolicy:TOPN_AUDIOPOLICY, auto play audio fail, ".concat(null==e?void 0:e.message,", streamId: ").concat(e.streams[0].id))}}else this.logger.error(CN,"AudioPolicy:TOPN_AUDIOPOLICY, audio stream of streamId: ".concat(e.streams[0].id," not exist"))}handleMaxVolumeNotify(e){try{e.topUserAudios&&e.topUserAudios.length>0?(this.top3VolumeUserIds.length=0,e.topUserAudios.forEach((e=>{e.volume=100*(60-(e.volume>60?60:e.volume))/60,this.top3VolumeUserIds.push({user_id:e.userId,volume:e.volume})})),this.audioPolicy===IO.TOPN_AUDIOPOLICY&&this.eventEmitter.emit(UC.VolumeIndicator,{userVolumeInfos:this.top3VolumeUserIds})):this.logger.error(CN,"handleMaxVolumeNotify error,topUserAudios is null")}catch(Dw){this.logger.error(CN,"handleMaxVolumeNotify error ".concat(null==Dw?void 0:Dw.message))}}handlePublishStatusNotify(e){try{e.urlStatus&&(this.logger.info(CN,"emit ".concat(UC.LiveStreamingUpdated)),this.eventEmitter.emit(UC.LiveStreamingUpdated,e.urlStatus))}catch(Dw){this.logger.error(CN,"handlePublishStatusNotify error ".concat(Dw))}}setVolume4TopThree(e){this.setVolume4TopThreeImpl(e)}setVolume4TopThreeImpl(e){this.logger.debug(CN,"setVolume4TopThreeImpl volume: "+e),e>100||e<0||this.audioPolicy===IO.TOPN_AUDIOPOLICY&&(this.topNAudioVolume=e,this.audioStreams4TopN.setAudioVolume(e))}muteAudio4TopThree(e){this.muteAudio4TopThreeImpl(e)}muteAudio4TopThreeImpl(e){this.logger.debug(CN,"muteAudio4TopThree enable: "+e),this.audioPolicy===IO.TOPN_AUDIOPOLICY&&this.audioStreams4TopN.muteAudio(e)}async setAudioOutput4TopThree(e){this.audioPolicy===IO.TOPN_AUDIOPOLICY&&await this.audioStreams4TopN.setAudioOutput(e)}isTopNAudioMuted(){return this.isTopNAudioMutedImpl()}isTopNAudioMutedImpl(){let e=!1;return this.audioPolicy===IO.TOPN_AUDIOPOLICY&&(e=this.audioStreams4TopN.isAudioMuted(),this.logger.debug(CN,"isTopNAudioMutedImpl : "+e)),e}async changeUserName(e){return await this.changeUserNameImpl(e)}async changeUserNameImpl(e){try{if(TA.checkUserName(e),this.userInfo.role===nM)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"player can not change user name");return await this.signal.appData(this.userInfo.appData,"nickname",e),this.userInfo.appData.nickname=e,!0}catch(jN){return this.logger.error(CN,"changeUserNameImpl, error:".concat(jN)),!1}}reportAudioMuteInfo(e,t){this.stat.reportAudioMuteInfo(e,t)}reportVideoMuteInfo(e,t){this.stat.reportVideoMuteInfo(e,t)}async startLiveStreaming(e,t,r,i){return await this.startLiveStreamingImpl(e,t,r,i)}async startLiveStreamingImpl(e,t,r,i){if(this.logger.info(CN,"startLiveStreaming: publishConfig: ".concat(JSON.stringify(r),", userConfig: ").concat(JSON.stringify(i))),!(t&&e&&r&&i))throw this.logger.error(CN,"startLiveStreaming failed for parameter error: empty parameter"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(this.status!==OC.Joined||this.userInfo.role!==iM)throw this.logger.error(CN,"startLiveStreaming failed for permission not allowed"),new qc(Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION);const n=this.getLiveStreamingUserInfos(i,99===r.template);if(0===n.length)throw this.logger.error(CN,"startLiveStreaming failed for parameter error:".concat(JSON.stringify(i))),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);try{await this.signal.startLiveStreaming(e,t,r,n),this.logger.info(CN,"startLiveStreaming success, taskId: ".concat(e,", url: ").concat(t))}catch(jN){throw this.logger.error(CN,"startLiveStreaming failed: ".concat(jN)),jN}}getLiveStreamingUserInfos(e,t){if(!e||0===e.length)return null;const r=[],i=this.userInfo.userId;return e.forEach((e=>{const n={userId:e.userId,audioStreams:[],videoStreams:[],layouts:[]};if(t&&!e.layouts)throw this.logger.error(CN,"getLiveStreamingUserInfos, layouts is null when template=99"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);e.userId===i?this.getLocalLiveStreamingUserInfos(e,n,t):this.getRemoteLiveStreamingUserInfos(e,n,t),(n.audioStreams.length||n.videoStreams.length)&&r.push(n)})),this.logger.info(CN,"getLiveStreamingUserInfos, publishInfos : ".concat(JSON.stringify(r))),r}getLocalLiveStreamingUserInfos(t,r,i){const n=this.streamPublishManager.getPublishedMainStreamInfos();if(t.audio){var o;const e=null==n||null===(o=n.find((e=>e.type===vO.TRACK_TYPE_AUDIO)))||void 0===o?void 0:o.ssrc;e&&r.audioStreams.push(e)}if(!t.resolutionIds||0===t.resolutionIds.length)return;const s=this.streamPublishManager.getPublishedAuxVideoTrackInfo();t.resolutionIds.forEach((o=>{var a;const c=null==n||null===(a=n.find((e=>e.resolutionId===o)))||void 0===a?void 0:a.ssrc;c?e.updateSlidePublishInfo(t,r,c,o,i):(null==s?void 0:s.resolutionId)===o&&e.updateSlidePublishInfo(t,r,s.ssrc,o,i)}))}static getSsrcLayout(e,t){return{alpha:t.alpha,localX:t.localX,localY:t.localY,renderMode:t.renderMode,ssrc:e,subBackGroundColor:t.subBackGroundColor,subHeight:t.subHeight,subWidth:t.subWidth,zorder:t.zorder}}getRemoteLiveStreamingUserInfos(t,r,i){const n=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,null),o=null==n?void 0:n.find((e=>e.userId===t.userId));if(o){if(t.audio){var s,a,c;const e=null===(s=o.mainStream)||void 0===s||null===(a=s.tracks)||void 0===a||null===(c=a.find((e=>e.type===vO.TRACK_TYPE_AUDIO)))||void 0===c?void 0:c.pssrc;e&&r.audioStreams.push(e)}if(!t.resolutionIds||0===t.resolutionIds.length)return;for(const n of t.resolutionIds){var u,d,l;const s=null===(u=o.mainStream)||void 0===u||null===(d=u.tracks)||void 0===d||null===(l=d.find((e=>e.trackId===n)))||void 0===l?void 0:l.pssrc;if(s)e.updateSlidePublishInfo(t,r,s,n,i);else{var h,f,p;const s=null===(h=o.auxStream)||void 0===h||null===(f=h.tracks)||void 0===f||null===(p=f.find((e=>e.trackId===n)))||void 0===p?void 0:p.pssrc;s&&e.updateSlidePublishInfo(t,r,s,n,i)}}}}static updateSlidePublishInfo(t,r,i,n,o){if(r.videoStreams.push(i),o&&t.layouts){const o=t.layouts.find((e=>e.resolutionId===n));if(o){const t=e.getSsrcLayout(i,o);r.layouts.push(t)}}}async updateLiveStreaming(e,t,r,i){return await this.updateLiveStreamingImpl(e,t,r,i)}async updateLiveStreamingImpl(e,t,r,i){if(this.logger.info(CN,"updateLiveStreaming: publishConfig: ".concat(JSON.stringify(r),", userConfig: ").concat(JSON.stringify(i))),!(t&&e&&r&&i))throw this.logger.error(CN,"updateLiveStreaming failed for parameter error: empty param"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(this.status!==OC.Joined||this.userInfo.role!==iM)throw this.logger.error(CN,"updateLiveStreaming failed for permission not allowed"),new qc(Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION);const n=this.getLiveStreamingUserInfos(i,99===r.template);try{await this.signal.updateLiveStreaming(e,r,n),this.logger.info(CN,"updateLiveStreaming success, taskId: ".concat(e,", url: ").concat(t))}catch(jN){throw this.logger.error(CN,"updateLiveStreaming failed: ".concat(jN)),jN}}async stopLiveStreaming(e){return await this.stopLiveStreamingImpl(e)}async stopLiveStreamingImpl(e){if(this.logger.info(CN,"stopLiveStreaming: taskId: ".concat(e)),!e)throw this.logger.error(CN,"stopLiveStreaming failed for parameter error: taskId is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);try{await this.signal.stopLiveStreaming(e),this.logger.info(CN,"stopLiveStreaming success, taskId: ".concat(e))}catch(jN){throw this.logger.error(CN,"stopLiveStreaming failed: ".concat(jN)),jN}}setProxyServer(e){RA.setPorxyServer(e)}setTurnServer(e){var t;null===(t=this.connectionsManager)||void 0===t||t.setTurnServer(e)}async addMultiRoomMediaRelay(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"addMultiRoomMediaRelay failed for not joined room."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);TA.checkSrcMultiRoomInfo(e.srcRoomRelayInfo);for(const n of e.dstRoomRelayInfo)TA.checkDstMultiRoomInfo(n,this.userInfo.role);const t=new Map;e.dstRoomRelayInfo.forEach((e=>{t.set(e.roomId,e.role)}));const r=await this.signal.mediaRelay(e,!0,this.userInfo),i=[];return r.addResult.forEach((async e=>{i.push({roomId:e.roomId,result:e.resultCode,msg:e.resultMessage}),0===e.resultCode?this.userInfo.addRelayInfo(e.roomId,t.get(e.roomId)):this.logger.error(CN,"addMultiRoomMediaRelay failed, roomId: ".concat(e.roomId,", resultCode: ").concat(e.resultCode,", errMsg: ").concat(e.resultMessage)),this.stat.reportRelayJoinInfo({code:e.resultCode,acsAddr:"",requestId:r.requestId,traceId:r.traceId,roomId:e.roomId,role:t.get(e.roomId),roomUid:e.roomUid,failMessage:e.resultMessage})})),i}async stopMultiRoomMediaRelay(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"stopMultiRoomMediaRelay failed for not joined room."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);let t;if(e&&e.dstRoomRelayInfo&&0!==e.dstRoomRelayInfo.length){TA.checkSrcMultiRoomInfo(e.srcRoomRelayInfo);for(const t of e.dstRoomRelayInfo)TA.checkDstMultiRoomInfo(t,this.userInfo.role);t=e}else t={dstRoomRelayInfo:this.userInfo.getRelayInfos()};const r=await this.signal.mediaRelay(t,!1,this.userInfo),i=[];return r.addResult.forEach((async e=>{i.push({roomId:e.roomId,result:e.resultCode,msg:e.resultMessage}),0===e.resultCode?this.userInfo.removeRelayInfo(e.roomId):this.logger.error(CN,"stopMultiRoomMediaRelay failed, roomId: ".concat(e.roomId,", resultCode: ").concat(e.resultCode,", errMsg: ").concat(e.resultMessage)),this.stat.reportRelayLeavInfo({code:e.resultCode,requestId:r.requestId,traceId:r.traceId,roomId:e.roomId,roomUid:e.roomUid})})),i}addRelayClient(e){return ED.addRelayConnection(this,e)}async stopRelayClient(e){const t=ED.getRelayConnection(this,e);t&&await t.leave()}enableCommandMsg(e,t){if(this.status!==OC.Idle&&e)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call enableCommandMsg interface before join room first.");var r;e?this.cmdMsgAbility.msgFormat=(null==t?void 0:t.msgFormat)===VC.ARRAY_BUFFER?VC.ARRAY_BUFFER:VC.STRING:(null===(r=this.cmdMsgAbility.cmdManager)||void 0===r||r.reset(),this.cmdMsgAbility.cmdManager=null);return this.cmdMsgAbility.enable=e,!0}sendCommandMsg(e,t){var r;if(!this.cmdMsgAbility.enable)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call enableCommandMsg interface before join room first.");if(this.status!==OC.Joined)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call this interface after joined room.");if((null===(r=this.userInfo)||void 0===r?void 0:r.roleSignalType)!==oM.JOINER)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"only joiner can send comand message.");return TA.checkCmdMsgValid(e),this.cmdMsgAbility.cmdManager.sendCommandMsg(e,t,this.roomId)}async handleNotifyRoomStreamStatus(e){const{audienceState:t}=e;this.logger.info(CN,"handleNotifyRoomStreamStatus handle room stream status : "+t+" role:"+this.userInfo.role),await this.handleRoomStreamStatus(t,IO.TOPN_AUDIOPOLICY===this.audioPolicy&&this.userInfo.role===nM&&YC.NORMAL===t)}async handleRoomStreamStatus(e,t,r){this.logger.info(CN,"handle room stream status : "+e),this.roomStreamStatus={audience:e};try{if(this.userInfo.role===nM&&e===YC.PAUSE){this.logger.info(CN,"player handle room stream status : "+e);const t=this.remoteUserManager.getAllSubscribedUpdateInfos4Unsubscribe(this.roomId);await this.updateSubscribe(t,null,!0),IO.TOPN_AUDIOPOLICY===this.audioPolicy&&(this.logger.info(CN,"player handle room stream status : "+e+" and topN unsubscribeUsersAudio"),await this.unsubscribeUsersAudio()),this.logger.info(CN,"player handle room stream status : "+e+" and clear intervals"),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.setAudioLevelStatTimer()}t&&(this.logger.info(CN,"".concat(this.userInfo.role," handle room stream status : ")+e+" and topN addSsrc4Top3"),this.remoteUserManager.enableTopThreeAudioMode(this.roomId),await this.connectionsManager.generateAndSetOfferSdpByHandler(yO.STREAM_TYPE_MAIN),await this.connectionsManager.generateAndSetAnswerSdpByHandler(yO.STREAM_TYPE_MAIN,this.addSsrc4Top3.bind(this))),(r||this.userInfo.role===nM&&[YC.PAUSE,YC.NORMAL].includes(e))&&(this.logger.info(CN,"eventEmitter RoomStreamStatus : "+e),this.eventEmitter.emit(UC.RoomStreamStatus,e))}catch(Dw){this.logger.error(CN,"RoomStreamStatus : "+e+" error:"+Dw)}}renewSignature(e,t){if("string"!=typeof e||"string"!=typeof t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"ctime or signature must be string");const r=uM.renewSignature(this.identifiedID,e,t);var i;return r?(this.userInfo=r,null===(i=this.signal)||void 0===i||i.refreshUserInfo(r),this.logger.info(CN,"renewSignature success"),!0):(this.logger.info(CN,"renewSignature fail"),!1)}},n(TN.prototype,"enableTopThreeAudioMode",[VD],Object.getOwnPropertyDescriptor(TN.prototype,"enableTopThreeAudioMode"),TN.prototype),n(TN.prototype,"switchAudioMode",[YD],Object.getOwnPropertyDescriptor(TN.prototype,"switchAudioMode"),TN.prototype),n(TN.prototype,"getConnectionState",[jD],Object.getOwnPropertyDescriptor(TN.prototype,"getConnectionState"),TN.prototype),n(TN.prototype,"setNetworkBandwidth",[FD],Object.getOwnPropertyDescriptor(TN.prototype,"setNetworkBandwidth"),TN.prototype),n(TN.prototype,"join",[HD],Object.getOwnPropertyDescriptor(TN.prototype,"join"),TN.prototype),n(TN.prototype,"enableRtcStats",[KD],Object.getOwnPropertyDescriptor(TN.prototype,"enableRtcStats"),TN.prototype),n(TN.prototype,"leave",[zD],Object.getOwnPropertyDescriptor(TN.prototype,"leave"),TN.prototype),n(TN.prototype,"publish",[WD],Object.getOwnPropertyDescriptor(TN.prototype,"publish"),TN.prototype),n(TN.prototype,"publishImpl",[GD],Object.getOwnPropertyDescriptor(TN.prototype,"publishImpl"),TN.prototype),n(TN.prototype,"unpublish",[JD],Object.getOwnPropertyDescriptor(TN.prototype,"unpublish"),TN.prototype),n(TN.prototype,"subscribeAudio",[qD],Object.getOwnPropertyDescriptor(TN.prototype,"subscribeAudio"),TN.prototype),n(TN.prototype,"unSubscribeAudio",[XD],Object.getOwnPropertyDescriptor(TN.prototype,"unSubscribeAudio"),TN.prototype),n(TN.prototype,"subscribe",[QD],Object.getOwnPropertyDescriptor(TN.prototype,"subscribe"),TN.prototype),n(TN.prototype,"batchSubscribe",[$D],Object.getOwnPropertyDescriptor(TN.prototype,"batchSubscribe"),TN.prototype),n(TN.prototype,"unsubscribe",[ZD],Object.getOwnPropertyDescriptor(TN.prototype,"unsubscribe"),TN.prototype),n(TN.prototype,"switchRole",[eN],Object.getOwnPropertyDescriptor(TN.prototype,"switchRole"),TN.prototype),n(TN.prototype,"refreshRemoteStreamList",[tN],Object.getOwnPropertyDescriptor(TN.prototype,"refreshRemoteStreamList"),TN.prototype),n(TN.prototype,"updateRemoteStream",[rN],Object.getOwnPropertyDescriptor(TN.prototype,"updateRemoteStream"),TN.prototype),n(TN.prototype,"removeRemoteStream",[iN],Object.getOwnPropertyDescriptor(TN.prototype,"removeRemoteStream"),TN.prototype),n(TN.prototype,"handleWatchMsg",[nN],Object.getOwnPropertyDescriptor(TN.prototype,"handleWatchMsg"),TN.prototype),n(TN.prototype,"refreshRoomUserInfos",[oN],Object.getOwnPropertyDescriptor(TN.prototype,"refreshRoomUserInfos"),TN.prototype),n(TN.prototype,"setVolume4TopThree",[sN],Object.getOwnPropertyDescriptor(TN.prototype,"setVolume4TopThree"),TN.prototype),n(TN.prototype,"muteAudio4TopThree",[aN],Object.getOwnPropertyDescriptor(TN.prototype,"muteAudio4TopThree"),TN.prototype),n(TN.prototype,"setAudioOutput4TopThree",[cN],Object.getOwnPropertyDescriptor(TN.prototype,"setAudioOutput4TopThree"),TN.prototype),n(TN.prototype,"isTopNAudioMuted",[uN],Object.getOwnPropertyDescriptor(TN.prototype,"isTopNAudioMuted"),TN.prototype),n(TN.prototype,"changeUserName",[dN],Object.getOwnPropertyDescriptor(TN.prototype,"changeUserName"),TN.prototype),n(TN.prototype,"startLiveStreaming",[lN],Object.getOwnPropertyDescriptor(TN.prototype,"startLiveStreaming"),TN.prototype),n(TN.prototype,"updateLiveStreaming",[hN],Object.getOwnPropertyDescriptor(TN.prototype,"updateLiveStreaming"),TN.prototype),n(TN.prototype,"stopLiveStreaming",[fN],Object.getOwnPropertyDescriptor(TN.prototype,"stopLiveStreaming"),TN.prototype),n(TN.prototype,"setProxyServer",[pN],Object.getOwnPropertyDescriptor(TN.prototype,"setProxyServer"),TN.prototype),n(TN.prototype,"setTurnServer",[mN],Object.getOwnPropertyDescriptor(TN.prototype,"setTurnServer"),TN.prototype),n(TN.prototype,"addMultiRoomMediaRelay",[gN],Object.getOwnPropertyDescriptor(TN.prototype,"addMultiRoomMediaRelay"),TN.prototype),n(TN.prototype,"stopMultiRoomMediaRelay",[_N],Object.getOwnPropertyDescriptor(TN.prototype,"stopMultiRoomMediaRelay"),TN.prototype),n(TN.prototype,"addRelayClient",[SN],Object.getOwnPropertyDescriptor(TN.prototype,"addRelayClient"),TN.prototype),n(TN.prototype,"stopRelayClient",[vN],Object.getOwnPropertyDescriptor(TN.prototype,"stopRelayClient"),TN.prototype),n(TN.prototype,"enableCommandMsg",[yN],Object.getOwnPropertyDescriptor(TN.prototype,"enableCommandMsg"),TN.prototype),n(TN.prototype,"renewSignature",[IN],Object.getOwnPropertyDescriptor(TN.prototype,"renewSignature"),TN.prototype),TN);var wN,kN,ON,PN,MN,DN,NN,UN,xN,LN,BN;const VN=new(wN=fP("default$setLogLevel#void#LogLevel"),kN=hP("default$checkSystemRequirements#Promise#boolean"),ON=fP("default$isScreenShareSupported#boolean"),PN=hP("default$getDevices#Promise"),MN=hP("default$getCameras#Promise"),DN=hP("default$getMicrophones#Promise"),NN=hP("default$getSpeakers#Promise"),UN=fP("default$setParameter#boolean#string#string"),xN=fP("default$createClient#Client#ClientConfig"),LN=fP("default$createStream#LocalStream#StreamConfig"),n((BN=class extends $P{constructor(){super({logger:!0,stat:!0}),i(this,"VERSION",uA),this.stat.setDeviceStatusInfo(),this.stat.setDeviceUserAgent()}setLogLevel(e){iE.setAllLogLevel(e)}async checkSystemRequirements(e){return await Mw.checkSystemRequirements(e)}isScreenShareSupported(){return Mw.isRTCScreenShareSupported()}async getDevices(){return await AC()}async getCameras(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"videoinput"===e.kind));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}async getMicrophones(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"audioinput"===e.kind&&"communications"!==e.deviceId&&"default"!==e.deviceId));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}async getSpeakers(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"audiooutput"===e.kind));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}setParameter(e,t){return SO.setParameter(e,t)}createClient(e){return TA.checkAppid(e.appId),TA.checkCountryCode(e.countryCode),e.domain&&TA.checkDomain(e.domain),new AN(e)}createStream(e){if(e.screen){if(e.videoSource||e.audioSource){if(!0===e.video||!0===e.audio)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION)}else if(!this.isScreenShareSupported())throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"screen share is not supported")}else{if(!0!==e.video&&!0!==e.audio&&!e.videoSource&&!e.audioSource)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);if((!0===e.video||!0===e.audio)&&(e.videoSource||e.audioSource))throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION)}return new tM(e)}getInfo(){return{moduleName:"default"}}}).prototype,"setLogLevel",[wN],Object.getOwnPropertyDescriptor(BN.prototype,"setLogLevel"),BN.prototype),n(BN.prototype,"checkSystemRequirements",[kN],Object.getOwnPropertyDescriptor(BN.prototype,"checkSystemRequirements"),BN.prototype),n(BN.prototype,"isScreenShareSupported",[ON],Object.getOwnPropertyDescriptor(BN.prototype,"isScreenShareSupported"),BN.prototype),n(BN.prototype,"getDevices",[PN],Object.getOwnPropertyDescriptor(BN.prototype,"getDevices"),BN.prototype),n(BN.prototype,"getCameras",[MN],Object.getOwnPropertyDescriptor(BN.prototype,"getCameras"),BN.prototype),n(BN.prototype,"getMicrophones",[DN],Object.getOwnPropertyDescriptor(BN.prototype,"getMicrophones"),BN.prototype),n(BN.prototype,"getSpeakers",[NN],Object.getOwnPropertyDescriptor(BN.prototype,"getSpeakers"),BN.prototype),n(BN.prototype,"setParameter",[UN],Object.getOwnPropertyDescriptor(BN.prototype,"setParameter"),BN.prototype),n(BN.prototype,"createClient",[xN],Object.getOwnPropertyDescriptor(BN.prototype,"createClient"),BN.prototype),n(BN.prototype,"createStream",[LN],Object.getOwnPropertyDescriptor(BN.prototype,"createStream"),BN.prototype),BN),YN={};return YN.VERSION=VN.VERSION,YN.setLogLevel=VN.setLogLevel,YN.checkSystemRequirements=VN.checkSystemRequirements,YN.isScreenShareSupported=VN.isScreenShareSupported,YN.getDevices=VN.getDevices,YN.getCameras=VN.getCameras,YN.getMicrophones=VN.getMicrophones,YN.getSpeakers=VN.getSpeakers,YN.setParameter=VN.setParameter,YN.createClient=VN.createClient,YN.createStream=VN.createStream,YN})); +function(e){var t=r,i=t.lib,n=i.WordArray,o=i.Hasher,s=t.algo,a=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),c=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),u=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),l=n.create([0,1518500249,1859775393,2400959708,2840853838]),h=n.create([1352829926,1548603684,1836072691,2053994217,0]),f=s.RIPEMD160=o.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var i=t+r,n=e[i];e[i]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var o,s,f,y,I,T,R,E,b,C,A,w=this._hash.words,k=l.words,O=h.words,P=a.words,M=c.words,D=u.words,N=d.words;for(T=o=w[0],R=s=w[1],E=f=w[2],b=y=w[3],C=I=w[4],r=0;r<80;r+=1)A=o+e[t+P[r]]|0,A+=r<16?p(s,f,y)+k[0]:r<32?m(s,f,y)+k[1]:r<48?g(s,f,y)+k[2]:r<64?_(s,f,y)+k[3]:S(s,f,y)+k[4],A=(A=v(A|=0,D[r]))+I|0,o=I,I=y,y=v(f,10),f=s,s=A,A=T+e[t+M[r]]|0,A+=r<16?S(R,E,b)+O[0]:r<32?_(R,E,b)+O[1]:r<48?g(R,E,b)+O[2]:r<64?m(R,E,b)+O[3]:p(R,E,b)+O[4],A=(A=v(A|=0,N[r]))+C|0,T=C,C=b,b=v(E,10),E=R,R=A;A=w[1]+f+b|0,w[1]=w[2]+y+C|0,w[2]=w[3]+I+T|0,w[3]=w[4]+o+R|0,w[4]=w[0]+s+E|0,w[0]=A},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process();for(var n=this._hash,o=n.words,s=0;s<5;s++){var a=o[s];o[s]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}return n},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function p(e,t,r){return e^t^r}function m(e,t,r){return e&t|~e&r}function g(e,t,r){return(e|~t)^r}function _(e,t,r){return e&r|t&~r}function S(e,t,r){return e^(t|~r)}function v(e,t){return e<>>32-t}t.RIPEMD160=o._createHelper(f),t.HmacRIPEMD160=o._createHmacHelper(f)}(),r.RIPEMD160)}(JT)),QT(),$T||($T=1,function(e,t){var r;e.exports=(r=hT(),DT(),QT(),function(){var e=r,t=e.lib,i=t.Base,n=t.WordArray,o=e.algo,s=o.SHA1,a=o.HMAC,c=o.PBKDF2=i.extend({cfg:i.extend({keySize:4,hasher:s,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,i=a.create(r.hasher,e),o=n.create(),s=n.create([1]),c=o.words,u=s.words,d=r.keySize,l=r.iterations;c.length>>2]|=n<<24-o%4*8,e.sigBytes+=n},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},r.pad.Ansix923)}(IR)),TR||(TR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.Iso10126={pad:function(e,t){var i=4*t,n=i-e.sigBytes%i;e.concat(r.lib.WordArray.random(n-1)).concat(r.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},r.pad.Iso10126)}(RR)),ER||(ER=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.Iso97971={pad:function(e,t){e.concat(r.lib.WordArray.create([2147483648],1)),r.pad.ZeroPadding.pad(e,t)},unpad:function(e){r.pad.ZeroPadding.unpad(e),e.sigBytes--}},r.pad.Iso97971)}(bR)),CR||(CR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.ZeroPadding={pad:function(e,t){var r=4*t;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){var t=e.words,r=e.sigBytes-1;for(r=e.sigBytes-1;r>=0;r--)if(t[r>>>2]>>>24-r%4*8&255){e.sigBytes=r+1;break}}},r.pad.ZeroPadding)}(AR)),wR||(wR=1,function(e,t){var r;e.exports=(r=hT(),oR(),r.pad.NoPadding={pad:function(){},unpad:function(){}},r.pad.NoPadding)}(kR)),OR||(OR=1,function(e,t){var r;e.exports=(r=hT(),oR(),function(e){var t=r,i=t.lib.CipherParams,n=t.enc.Hex;t.format.Hex={stringify:function(e){return e.ciphertext.toString(n)},parse:function(e){var t=n.parse(e);return i.create({ciphertext:t})}}}(),r.format.Hex)}(PR)),MR||(MR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.BlockCipher,i=e.algo,n=[],o=[],s=[],a=[],c=[],u=[],d=[],l=[],h=[],f=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,i=0;for(t=0;t<256;t++){var p=i^i<<1^i<<2^i<<3^i<<4;p=p>>>8^255&p^99,n[r]=p,o[p]=r;var m=e[r],g=e[m],_=e[g],S=257*e[p]^16843008*p;s[r]=S<<24|S>>>8,a[r]=S<<16|S>>>16,c[r]=S<<8|S>>>24,u[r]=S,S=16843009*_^65537*g^257*m^16843008*r,d[p]=S<<24|S>>>8,l[p]=S<<16|S>>>16,h[p]=S<<8|S>>>24,f[p]=S,r?(r=m^e[e[e[_^m]]],i^=e[e[i]]):r=i=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],m=i.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,i=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],s=0;s6&&s%r==4&&(u=n[u>>>24]<<24|n[u>>>16&255]<<16|n[u>>>8&255]<<8|n[255&u]):(u=n[(u=u<<8|u>>>24)>>>24]<<24|n[u>>>16&255]<<16|n[u>>>8&255]<<8|n[255&u],u^=p[s/r|0]<<24),o[s]=o[s-r]^u);for(var a=this._invKeySchedule=[],c=0;c>>24]]^l[n[u>>>16&255]]^h[n[u>>>8&255]]^f[n[255&u]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,c,u,n)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,d,l,h,f,o),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,i,n,o,s,a){for(var c=this._nRounds,u=e[t]^r[0],d=e[t+1]^r[1],l=e[t+2]^r[2],h=e[t+3]^r[3],f=4,p=1;p>>24]^n[d>>>16&255]^o[l>>>8&255]^s[255&h]^r[f++],g=i[d>>>24]^n[l>>>16&255]^o[h>>>8&255]^s[255&u]^r[f++],_=i[l>>>24]^n[h>>>16&255]^o[u>>>8&255]^s[255&d]^r[f++],S=i[h>>>24]^n[u>>>16&255]^o[d>>>8&255]^s[255&l]^r[f++];u=m,d=g,l=_,h=S}m=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^r[f++],g=(a[d>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&u])^r[f++],_=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[f++],S=(a[h>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&l])^r[f++],e[t]=m,e[t+1]=g,e[t+2]=_,e[t+3]=S},keySize:8});e.AES=t._createHelper(m)}(),r.AES)}(DR)),xR(),LR||(LR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=i.RC4=t.extend({_doReset:function(){for(var e=this._key,t=e.words,r=e.sigBytes,i=this._S=[],n=0;n<256;n++)i[n]=n;n=0;for(var o=0;n<256;n++){var s=n%r,a=t[s>>>2]>>>24-s%4*8&255;o=(o+i[n]+a)%256;var c=i[n];i[n]=i[o],i[o]=c}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=o.call(this)},keySize:8,ivSize:0});function o(){for(var e=this._S,t=this._i,r=this._j,i=0,n=0;n<4;n++){r=(r+e[t=(t+1)%256])%256;var o=e[t];e[t]=e[r],e[r]=o,i|=e[(e[t]+e[r])%256]<<24-8*n}return this._i=t,this._j=r,i}e.RC4=t._createHelper(n);var s=i.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)o.call(this)}});e.RC4Drop=t._createHelper(s)}(),r.RC4)}(BR)),VR||(VR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=[],o=[],s=[],a=i.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,r=0;r<4;r++)e[r]=16711935&(e[r]<<8|e[r]>>>24)|4278255360&(e[r]<<24|e[r]>>>8);var i=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],n=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,r=0;r<4;r++)c.call(this);for(r=0;r<8;r++)n[r]^=i[r+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),l=u>>>16|4294901760&d,h=d<<16|65535&u;for(n[0]^=u,n[1]^=l,n[2]^=d,n[3]^=h,n[4]^=u,n[5]^=l,n[6]^=d,n[7]^=h,r=0;r<4;r++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),n[0]=r[0]^r[5]>>>16^r[3]<<16,n[1]=r[2]^r[7]>>>16^r[5]<<16,n[2]=r[4]^r[1]>>>16^r[7]<<16,n[3]=r[6]^r[3]>>>16^r[1]<<16;for(var i=0;i<4;i++)n[i]=16711935&(n[i]<<8|n[i]>>>24)|4278255360&(n[i]<<24|n[i]>>>8),e[t+i]^=n[i]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var i=e[r]+t[r],n=65535&i,a=i>>>16,c=((n*n>>>17)+n*a>>>15)+a*a,u=((4294901760&i)*i|0)+((65535&i)*i|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.Rabbit=t._createHelper(a)}(),r.Rabbit)}(YR)),jR||(jR=1,function(e,t){var r;e.exports=(r=hT(),ET(),OT(),rR(),oR(),function(){var e=r,t=e.lib.StreamCipher,i=e.algo,n=[],o=[],s=[],a=i.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var n=0;n<4;n++)c.call(this);for(n=0;n<8;n++)i[n]^=r[n+4&7];if(t){var o=t.words,s=o[0],a=o[1],u=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),l=u>>>16|4294901760&d,h=d<<16|65535&u;for(i[0]^=u,i[1]^=l,i[2]^=d,i[3]^=h,i[4]^=u,i[5]^=l,i[6]^=d,i[7]^=h,n=0;n<4;n++)c.call(this)}},_doProcessBlock:function(e,t){var r=this._X;c.call(this),n[0]=r[0]^r[5]>>>16^r[3]<<16,n[1]=r[2]^r[7]>>>16^r[5]<<16,n[2]=r[4]^r[1]>>>16^r[7]<<16,n[3]=r[6]^r[3]>>>16^r[1]<<16;for(var i=0;i<4;i++)n[i]=16711935&(n[i]<<8|n[i]>>>24)|4278255360&(n[i]<<24|n[i]>>>8),e[t+i]^=n[i]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,r=0;r<8;r++)o[r]=t[r];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0>>0?1:0)|0,this._b=t[7]>>>0>>0?1:0,r=0;r<8;r++){var i=e[r]+t[r],n=65535&i,a=i>>>16,c=((n*n>>>17)+n*a>>>15)+a*a,u=((4294901760&i)*i|0)+((65535&i)*i|0);s[r]=c^u}e[0]=s[0]+(s[7]<<16|s[7]>>>16)+(s[6]<<16|s[6]>>>16)|0,e[1]=s[1]+(s[0]<<8|s[0]>>>24)+s[7]|0,e[2]=s[2]+(s[1]<<16|s[1]>>>16)+(s[0]<<16|s[0]>>>16)|0,e[3]=s[3]+(s[2]<<8|s[2]>>>24)+s[1]|0,e[4]=s[4]+(s[3]<<16|s[3]>>>16)+(s[2]<<16|s[2]>>>16)|0,e[5]=s[5]+(s[4]<<8|s[4]>>>24)+s[3]|0,e[6]=s[6]+(s[5]<<16|s[5]>>>16)+(s[4]<<16|s[4]>>>16)|0,e[7]=s[7]+(s[6]<<8|s[6]>>>24)+s[5]|0}e.RabbitLegacy=t._createHelper(a)}(),r.RabbitLegacy)}(FR)),r)}(uT);const HR=window.crypto||window.webkitCrypto||window.mozCrypto||window.oCrypto||window.msCrypto,KR={Mac:/(mac os x)\s+([\w_]+)/,Windows:/(windows nt)\s+([\w.]+)/,Ios:/(i(?:pad|phone|pod)).*cpu(?: i(?:pad|phone|pod))? os (\d+(?:[.|_]\d+)+)/,Android:/(android)\s+([\d.]+)/,Ipad:/(ipad).*os\s([\d_]+)/,Iphone:/(iphone\sos)\s([\d_]+)/,Linux:/(x11;)\s(linux)\s(x86_64|mips64|aarch64)/,ChromiumOS:/(x11;)\s(cros)\s(x86_64|mips64|aarch64)\s([\w.]+)\)/},zR=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","-","_"];let WR,GR;const JR="CommonUtil";class qR{constructor(){this.uuidCount=0,this.timeDiff=0,this.platform=(()=>{const e=navigator.userAgent.toLowerCase(),t=e.match(/(micromessenger)\/([\w.()]+)/i),r=t?"-WeChat".concat(t[2]):"";for(const i in KR)if(Object.prototype.hasOwnProperty.call(KR,i)){const t=e.match(KR[i]);if(t)return GR="Ios"===i?t[2].replace(/_/g,"."):"Linux"===i?t[3]:"ChromiumOS"===i?t[4]:t[2],WR=["Ios","Ipad","Iphone"].includes(i)?"IOS":i,i+GR+r}return"unknown"})(),this.userAgent=(()=>{const e=navigator.userAgent.match(/(chrome|safari|firefox|microMessenger)\/(\d+(\.\d+)*)/i);return e?"".concat(e[1],"-").concat(e[2]):""})()}async sleep(e){return new Promise((t=>{const r=setTimeout((()=>{clearTimeout(r),t()}),e)}))}getDeviceID(){return this.deviceID||(this.deviceID=this.generateStandardUuid()),this.deviceID}generateStandardUuid(){let e;if(HR&&(e="function"==typeof HR.randomUUID?HR.randomUUID():""),!e){let t=(new Date).getTime();window.performance&&"function"==typeof window.performance.now&&(t+=performance.now()),e="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/[x]/g,(()=>{const e=(t+16*this.getRandom())%16|0;return t=Math.floor(t/16),e.toString(16)}))}return e}static getRandomArray(e){const t=new Uint8Array(e);return HR&&HR.getRandomValues(t),t}getRandom(){return qR.getRandomArray(1)[0]/256}getRandomUint32(){const e=qR.getRandomArray(4);return new DataView(e.buffer).getUint32(0)}generateUuid(e){let t="";const r=qR.getRandomArray(33),i=e?22:33;for(let s=0;s>=6;let o=this.uuidCount.toString(16);for(let s=3-o.length;s>0;s--)o="0"+o;return this.uuidCount>4094?this.uuidCount=0:this.uuidCount++,"".concat(t).concat(n).concat(o)}generateRandomId(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:62,r="";const i=qR.getRandomArray(e);for(let n=0;n=0?p:-p,g=(p<=0?"+":"-")+(m<10?"0".concat(m):"".concat(m))+":00";return{year:"".concat(t),month:"".concat(i),day:"".concat(o),hour:"".concat(a),min:"".concat(u),sec:"".concat(l),millsec:f,zoneOff:g}}adjustTimeByOffset(e){return e-this.timeDiff}convertString2Timestamp(e){return new Date(e).getTime()}generateStreamId(){return"2xxxxxxx-8xxx-xxxx-yxxx-xxxx".replace(/[xy]/g,(e=>{const t=16*this.getRandom()|0;return("x"==e?t:3&t|8).toString(16)}))}isWKWebview(){return/I.*-WeChat.*/gi.test(this.platform)}isAppleDevice(){return/^(Mac|I).*/gi.test(this.platform)}isSafari(){return this.isAppleDevice()&&/Safari/i.test(this.getUserAgent())}isMobileDevice(){return!/^(Mac|Windows).*/gi.test(this.platform)}isMobileWeChatBrowser(){return this.isMobileDevice()&&/.*MicroMessenger.*/gi.test(navigator.userAgent)}isSupportConstraints(e){var t;return!!(null===(t=navigator.mediaDevices)||void 0===t?void 0:t.getSupportedConstraints())[e]}async calculateSha256(e){return new Promise((t=>{const r=new FileReader;r.onloadend=e=>{if(e.target.readyState==FileReader.DONE){const r=uT.exports.lib.WordArray.create(e.target.result),i=uT.exports.SHA256(r).toString();t(i)}},r.readAsArrayBuffer(e)}))}getValue(e,t){return e||t}shieldIpAddress(e){return e?e.replace(/\b(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\b/g,"$1.*.*.$2"):null}shieldUrlParameters(e){if(!e)return e;const t=e.match(/([^?|=|&]+)=([^&]+)/g);return t&&t.forEach((t=>{const r=/([^=]*)=(.*)/g.exec(t);e=e.replace(t,"".concat(r[1],"=").concat(this.secretString(r[2])))})),e}shieldNickname(e){if(!e)return e;let t="";for(let r=0;r{r.includes(t)&&(r=r.replace(e.pattern,e.newString))}));const n=XR.getCurrentTime(),o=["".concat(n.year,"-").concat(n.month,"-").concat(n.day," ").concat(n.hour,":").concat(n.min,":").concat(n.sec,".").concat(n.millsec),e];Object.entries($R($R({},i),{},{tag:t,msg:r})).forEach((e=>{let[t,r]=e;"string"==typeof r&&o.push("[".concat(t,": ").concat(r,"]"))}));const s=o.join(" ");for(this.logBuffer.push(s);this.logBuffer.length>=this.logBufferSize;)this.logBuffer.shift();const a=["".concat(n.year,"-").concat(n.month,"-").concat(n.day," ").concat(n.hour,":").concat(n.min,":").concat(n.sec,".").concat(n.millsec)];eg.indexOf(iE.logLevel)>=eg.indexOf(e)&&console[e](a+" [HRTC] "+"[".concat(e,"] [").concat(t,"] [").concat(r,"]"))}clearLogs(){this.logBuffer=[]}setLogBufferSize(e){this.logBufferSize=e}getLogBufferSize(){return this.logBufferSize}getLogBuffer(){return this.logBuffer}}class iE{static getLogger(e){const t=e||ZR;if(!eE.has(t)){const e=new rE;return eE.set(t,e),e}return eE.get(t)}static setAllLogLevel(e){if(!(eg.indexOf(e)>=0))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"log level is invalid");iE.logLevel=e}static addPrivacyString(e){if(!e)return;if(tE.has(e))return;const t=XR.secretString(e);if(!t)return;const r=e.replaceAll(/([\^|\$|\\|\.|\*|\+|\?|\(|\)|\[|\]|\{|\}|\|])/g,"\\$1"),i={pattern:new RegExp("\\b"+r+"\\b","g"),newString:t};tE.set(e,i)}static async getLogFile(e,t){const r=e.logger,i=XR.getCurrentTime(),n="".concat(i.year,"-").concat(i.month,"-").concat(i.day,"T").concat(i.hour,":").concat(i.min,":").concat(i.sec).concat(i.zoneOff),o="".concat(i.year,"-").concat(i.month,"-").concat(i.day,"T").concat(i.hour,".").concat(i.min,".").concat(i.sec).concat(i.zoneOff.replace(":",".")),s=iE.getLogger(),a=r.getLogBuffer(),c=s.getLogBuffer();if(0===a.length&&0===c.length)return null;const u=e.getInfo(),d="".concat(u.userName,"_").concat(u.userId,"##").concat(u.domain,"##").concat(u.appId,"##").concat(o),l=XR.getDeviceID(),h=encodeURIComponent("".concat(t,"##").concat(l,"##").concat(u.appId,"##").concat(n)),f=new m_,p=f.folder("".concat(u.userName,"_").concat(u.userId,"##").concat(u.roomId,"##").concat(u.domain,"##").concat(u.appId));p.file("".concat(d,".log"),"".concat(a.join("\n"))),p.file("hrtc##".concat(n,".log"),"".concat(c.join("\n")));const m=await f.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:9}});return{sha256:await XR.calculateSha256(m),length:m.size,content:m,urlFileNameEncode:h}}}i(iE,"logLevel",eg[3]);var nE=en,oE=vs,sE=d,aE=J,cE=H,uE=to,dE=Hc,lE=Xr,hE=oE&&oE.prototype;if(nE({target:"Promise",proto:!0,real:!0,forced:!!oE&&sE((function(){hE.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=uE(this,aE("Promise")),r=cE(e);return this.then(r?function(r){return dE(t,e()).then((function(){return r}))}:e,r?function(r){return dE(t,e()).then((function(){throw r}))}:e)}}),cE(oE)){var fE=aE("Promise").prototype.finally;hE.finally!==fE&&lE(hE,"finally",fE,{unsafe:!0})}var pE=Se,mE=Ue,gE=L,_E=li,SE=TypeError,vE=function(e){return function(t,r,i,n){pE(r);var o=mE(t),s=gE(o),a=_E(o),c=e?a-1:0,u=e?-1:1;if(i<2)for(;;){if(c in s){n=s[c],c+=u;break}if(c+=u,e?c<0:a<=c)throw SE("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=u)c in s&&(n=r(n,s[c],c,o));return n}},yE={left:vE(!1),right:vE(!0)}.left,IE=ie,TE=tn;en({target:"Array",proto:!0,forced:!jh("reduce")||!TE&&IE>79&&IE<83},{reduce:function(e){var t=arguments.length;return yE(this,e,t,t>1?arguments[1]:void 0)}});var RE=m,EE=Se,bE=Mt,CE=function(){for(var e=bE(this),t=EE(e.add),r=0,i=arguments.length;r1?arguments[1]:void 0);return!BE(r,(function(e,r){if(!i(e,e,t))return r()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var VE=J,YE=m,jE=Se,FE=Mt,HE=lo,KE=to,zE=NE,WE=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{filter:function(e){var t=FE(this),r=zE(t),i=HE(e,arguments.length>1?arguments[1]:void 0),n=new(KE(t,VE("Set"))),o=jE(n.add);return WE(r,(function(e){i(e,e,t)&&YE(o,n,e)}),{IS_ITERATOR:!0}),n}});var GE=Mt,JE=lo,qE=NE,XE=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{find:function(e){var t=GE(this),r=qE(t),i=JE(e,arguments.length>1?arguments[1]:void 0);return XE(r,(function(e,r){if(i(e,e,t))return r(e)}),{IS_ITERATOR:!0,INTERRUPTED:!0}).result}});var QE=J,$E=m,ZE=Se,eb=Mt,tb=to,rb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{intersection:function(e){var t=eb(this),r=new(tb(t,QE("Set"))),i=ZE(t.has),n=ZE(r.add);return rb(e,(function(e){$E(i,t,e)&&$E(n,r,e)})),r}});var ib=m,nb=Se,ob=Mt,sb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isDisjointFrom:function(e){var t=ob(this),r=nb(t.has);return!sb(e,(function(e,i){if(!0===ib(r,t,e))return i()}),{INTERRUPTED:!0}).stopped}});var ab=J,cb=m,ub=Se,db=H,lb=Mt,hb=qa,fb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isSubsetOf:function(e){var t=hb(this),r=lb(e),i=r.has;return db(i)||(r=new(ab("Set"))(e),i=ub(r.has)),!fb(t,(function(e,t){if(!1===cb(i,r,e))return t()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var pb=m,mb=Se,gb=Mt,_b=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{isSupersetOf:function(e){var t=gb(this),r=mb(t.has);return!_b(e,(function(e,i){if(!1===pb(r,t,e))return i()}),{INTERRUPTED:!0}).stopped}});var Sb=en,vb=Mt,yb=$c,Ib=NE,Tb=hc,Rb=w([].join),Eb=[].push;Sb({target:"Set",proto:!0,real:!0,forced:!0},{join:function(e){var t=vb(this),r=Ib(t),i=void 0===e?",":yb(e),n=[];return Tb(r,Eb,{that:n,IS_ITERATOR:!0}),Rb(n,i)}});var bb=J,Cb=lo,Ab=m,wb=Se,kb=Mt,Ob=to,Pb=NE,Mb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{map:function(e){var t=kb(this),r=Pb(t),i=Cb(e,arguments.length>1?arguments[1]:void 0),n=new(Ob(t,bb("Set"))),o=wb(n.add);return Mb(r,(function(e){Ab(o,n,i(e,e,t))}),{IS_ITERATOR:!0}),n}});var Db=Se,Nb=Mt,Ub=NE,xb=hc,Lb=TypeError;en({target:"Set",proto:!0,real:!0,forced:!0},{reduce:function(e){var t=Nb(this),r=Ub(t),i=arguments.length<2,n=i?void 0:arguments[1];if(Db(e),xb(r,(function(r){i?(i=!1,n=r):n=e(n,r,r,t)}),{IS_ITERATOR:!0}),i)throw Lb("Reduce of empty set with no initial value");return n}});var Bb=Mt,Vb=lo,Yb=NE,jb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{some:function(e){var t=Bb(this),r=Yb(t),i=Vb(e,arguments.length>1?arguments[1]:void 0);return jb(r,(function(e,r){if(i(e,e,t))return r()}),{IS_ITERATOR:!0,INTERRUPTED:!0}).stopped}});var Fb=J,Hb=m,Kb=Se,zb=Mt,Wb=to,Gb=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{symmetricDifference:function(e){var t=zb(this),r=new(Wb(t,Fb("Set")))(t),i=Kb(r.delete),n=Kb(r.add);return Gb(e,(function(e){Hb(i,r,e)||Hb(n,r,e)})),r}});var Jb=J,qb=Se,Xb=Mt,Qb=to,$b=hc;en({target:"Set",proto:!0,real:!0,forced:!0},{union:function(e){var t=Xb(this),r=new(Qb(t,Jb("Set")))(t);return $b(e,qb(r.add),{that:r}),r}});const Zb="player-state-change",eC="screen-sharing-stopped",tC="audio-mixing-finished",rC="audio-mixing-played",iC="player-state-trace",nC=["camera-capture"],oC={CameraCapture:nC[0]},sC={low:{sampleRate:16e3,channelCount:1,bitrate:24e3},standard:{sampleRate:48e3,channelCount:1,bitrate:4e4},high:{sampleRate:48e3,channelCount:1,bitrate:128e3}},aC=["low","standard","high"],cC={"90p_1":{width:160,height:90,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"90p_2":{width:120,height:90,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"120p_1":{width:160,height:120,frameRate:15,minBitrate:64e3,maxBitrate:12e4},"120p_2":{width:120,height:120,frameRate:15,minBitrate:64e3,maxBitrate:11e4},"180p_1":{width:320,height:180,frameRate:15,minBitrate:8e4,maxBitrate:32e4},"180p_2":{width:240,height:180,frameRate:15,minBitrate:8e4,maxBitrate:17e4},"180p_3":{width:180,height:180,frameRate:15,minBitrate:64e3,maxBitrate:13e4},"240p_1":{width:320,height:240,frameRate:15,minBitrate:1e5,maxBitrate:4e5},"240p_2":{width:240,height:240,frameRate:15,minBitrate:8e4,maxBitrate:32e4},"270p_1":{width:480,height:270,frameRate:15,minBitrate:16e4,maxBitrate:6e5},"300p_1":{width:400,height:300,frameRate:15,minBitrate:2e5,maxBitrate:5e5},"360p_1":{width:640,height:360,frameRate:15,minBitrate:2e5,maxBitrate:8e5},"360p_2":{width:480,height:360,frameRate:15,minBitrate:2e5,maxBitrate:7e5},"360p_3":{width:360,height:360,frameRate:15,minBitrate:15e4,maxBitrate:6e5},"450p_1":{width:800,height:450,frameRate:15,minBitrate:3e5,maxBitrate:95e4},"480p_1":{width:640,height:480,frameRate:15,minBitrate:25e4,maxBitrate:9e5},"480p_2":{width:480,height:480,frameRate:15,minBitrate:2e5,maxBitrate:8e5},"540p_1":{width:960,height:540,frameRate:15,minBitrate:4e5,maxBitrate:1e6},"630p_1":{width:1120,height:630,frameRate:15,minBitrate:45e4,maxBitrate:115e4},"720p_1":{width:1280,height:720,frameRate:15,minBitrate:5e5,maxBitrate:15e5},"720p_2":{width:960,height:720,frameRate:15,minBitrate:45e4,maxBitrate:11e5},"1080p_1":{width:1920,height:1080,frameRate:15,minBitrate:6e5,maxBitrate:2e6},"1080p_2":{width:1440,height:1080,frameRate:15,minBitrate:55e4,maxBitrate:17e5}},uC=["90p_1","90p_2","120p_1","120p_2","180p_1","180p_2","180p_3","240p_1","240p_2","270p_1","300p_1","360p_1","360p_2","360p_3","450p_1","480p_1","480p_2","540p_1","630p_1","720p_1","720p_2","1080p_1","1080p_2"],dC={"720p":{width:1280,height:720,frameRate:15,bitrate:12e5},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e6}},lC=["720p","1080p"],hC="inbound-rtp-audio",fC="inbound-rtp-video",pC="outbound-rtp-audio",mC="outbound-rtp-video",gC="remote-inbound-rtp-audio",_C="remote-inbound-rtp-video";let SC=function(e){return e[e.IDLE=0]="IDLE",e[e.INIT=1]="INIT",e[e.PLAY=2]="PLAY",e[e.PAUSE=3]="PAUSE",e}({});const vC=["IDLE","DISCONNECTED","CONNECTING","RECONNECTING","CONNECTED"];let yC=function(e){return e[e.IDLE=0]="IDLE",e[e.DISCONNECTED=1]="DISCONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.RECONNECTING=3]="RECONNECTING",e[e.CONNECTED=4]="CONNECTED",e}({}),IC=function(e){return e[e.MediaStatusAvailable=1]="MediaStatusAvailable",e[e.MediaStatusUnavailable=2]="MediaStatusUnavailable",e}({}),TC=function(e){return e[e.BackgroundMusic=1]="BackgroundMusic",e[e.Audio=2]="Audio",e[e.Video=3]="Video",e[e.Aux=4]="Aux",e}({}),RC=function(e){return e[e.MediaOffline=0]="MediaOffline",e[e.MediaMuted=1]="MediaMuted",e[e.MediaUnmuted=2]="MediaUnmuted",e}({});const EC=new Set(["TOP_AUDIO"]);let bC=function(e){return e.configNotify="NOTIFY_CONFIG",e.watchStreamNotify="WATCH_STREAM_NOTIFY",e.disconnectNotify="DISCONNECT_NOTIFY",e.pushStreamNotify="PUSH_STREAM_NOTIFY",e.reconnectNotify="RECONNECT_NOTIFY",e.stopPushStreamNotify="STOP_PUSH_STREAM_NOTIFY",e.changeStreamStatusNotify="CHANGE_STREAM_STATUS_NOTIFY",e.appDataChangeNotify="APP_DATA_NOTIFY",e.top3AudioVolumeNotify="TOP_AUDIO",e.statusChangeNotify="NOTIFY_STATUS",e.publishStatusNotify="PUBLISH_STATUS_NOTIFY",e.uploadLogNotify="UPLOAD_LOG_NOTIFY",e.roomStreamStatusNotify="ROOM_STREAM_STATUS_NOTIFY",e}({}),CC=function(e){return e.main="main",e.middle1="middle1",e.middle2="middle2",e.middle3="middle3",e.middle4="middle4",e.slides="slides",e.desktop="desktop",e}({});async function AC(){return new Promise(((e,t)=>{navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices||t(new qc(Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES)),navigator.mediaDevices.enumerateDevices().then((r=>{r&&0!==r.length?e(r):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES))})).catch((e=>{t(e)}))}))}const wC="0",kC=-1e3;let OC=function(e){return e[e.Idle=0]="Idle",e[e.Joining=1]="Joining",e[e.Joined=2]="Joined",e[e.Leaving=3]="Leaving",e[e.Rejoining=4]="Rejoining",e}({}),PC=function(e){return e[e.DEFAULT_BANDWIDTH_4M=4096e3]="DEFAULT_BANDWIDTH_4M",e[e.MIN_BAND_WIDTH=3072]="MIN_BAND_WIDTH",e[e.MAX_BAND_WIDTH=51200]="MAX_BAND_WIDTH",e}({}),MC=function(e){return e[e.HRTC_LEAVE_REASON_USER_LEAVE_ROOM=0]="HRTC_LEAVE_REASON_USER_LEAVE_ROOM",e[e.HRTC_LEAVE_REASON_SERVER_ERROR=1]="HRTC_LEAVE_REASON_SERVER_ERROR",e[e.HRTC_LEAVE_REASON_BREAKDOWN=2]="HRTC_LEAVE_REASON_BREAKDOWN",e[e.HRTC_LEAVE_REASON_SERVICE_UNREACHABLE=3]="HRTC_LEAVE_REASON_SERVICE_UNREACHABLE",e[e.HRTC_LEAVE_REASON_INTERNAL_ERROR=4]="HRTC_LEAVE_REASON_INTERNAL_ERROR",e[e.HRTC_LEAVE_REASON_KICKED_OFF=5]="HRTC_LEAVE_REASON_KICKED_OFF",e[e.HRTC_LEAVE_REASON_SIGNATURE_EXPIRED=6]="HRTC_LEAVE_REASON_SIGNATURE_EXPIRED",e[e.HRTC_LEAVE_REASON_RECONNECT_FAILED=7]="HRTC_LEAVE_REASON_RECONNECT_FAILED",e[e.HRTC_LEAVE_REASON_NETWORK_TEST=8]="HRTC_LEAVE_REASON_NETWORK_TEST",e[e.HRTC_LEAVE_REASON_USER_REMOVED=9]="HRTC_LEAVE_REASON_USER_REMOVED",e[e.HRTC_LEAVE_REASON_ROOM_DISMISSED=10]="HRTC_LEAVE_REASON_ROOM_DISMISSED",e}({}),DC=function(e){return e[e.ON=1]="ON",e[e.OFF=2]="OFF",e}({}),NC=function(e){return e[e.portNormal=1]="portNormal",e[e.portReduce=2]="portReduce",e}({});const UC={Error:"Error",StreamAdded:"stream-added",StreamRemoved:"stream-removed",StreamUpdated:"stream-updated",StreamSubscribed:"stream-subscribed",ClientBanned:"client-banned",NetworkQuality:"network-quality",ConnectionStateChanged:"connection-state-changed",PeerJoin:"peer-join",PeerLeave:"peer-leave",MuteAudio:"mute-audio",UnmuteAudio:"unmute-audio",MuteVideo:"mute-video",UnmuteVideo:"unmute-video",LogUploaded:"log-upload-result",SignatureExpired:"signature-expired",CameraChanged:"camera-changed",RecordingDeviceChanged:"recording-device-changed",PlaybackDeviceChanged:"playback-device-changed",StreamInterrupted:"stream-interrupted",StreamRecovered:"stream-recovered",VolumeIndicator:"volume-indicator",UserNameChanged:"remote-user-name-changed",BatchSubscribeFailed:"batch-subscribe-failed",LiveStreamingUpdated:"live-streaming-updated",RtcStats:"rtc-stats",CmdMsgReceived:"cmd-msg-received",CmdChannelEstablished:"cmd-channel-established",CmdChannelDisconnect:"cmd-channel-disconnect",MediaConnectionStateChanged:"media-connection-state-changed",TransportProtocolChanged:"transport-protocol-changed",TransportStats:"transport-stats",RoomStreamStatus:"room-stream-status"};let xC=function(e){return e[e.NON_ENCRYPTION=0]="NON_ENCRYPTION",e[e.ENCRYPTION_FRAME_SDK=1]="ENCRYPTION_FRAME_SDK",e[e.ENCRYPTION_FRAME_APP=2]="ENCRYPTION_FRAME_APP",e[e.ENCRYPTION_E2E_WITHOUT_MEDIA=3]="ENCRYPTION_E2E_WITHOUT_MEDIA",e}({}),LC=function(e){return e.Connected="CONNECTED",e.Reconnecting="RECONNECTING",e.DisConnected="DISCONNECTED",e}({}),BC=function(e){return e.WEBSOCKET="WebSocket",e.DATA_CHANNEL="DataChannel",e}({}),VC=function(e){return e[e.ARRAY_BUFFER=0]="ARRAY_BUFFER",e[e.STRING=1]="STRING",e}({}),YC=function(e){return e[e.PAUSE=0]="PAUSE",e[e.NORMAL=1]="NORMAL",e}({}),jC=function(e){return e[e.NET_OR_SERVERIP_ERROR=1]="NET_OR_SERVERIP_ERROR",e[e.ROOM_NOT_AVAILABLE=2]="ROOM_NOT_AVAILABLE",e[e.SERVER_ERROR=3]="SERVER_ERROR",e[e.SERVER_NO_RESPONSE=4]="SERVER_NO_RESPONSE",e[e.AUTHENTICATION_FAILED=5]="AUTHENTICATION_FAILED",e[e.RETRY_AUTHENTICATION=6]="RETRY_AUTHENTICATION",e[e.SYNCHRONIZE_FAILED=7]="SYNCHRONIZE_FAILED",e[e.URL_ERROR=8]="URL_ERROR",e[e.TERMINAL_ERROR=9]="TERMINAL_ERROR",e}({}),FC=function(e){return e[e.LEAVE_ROOM_SUCCESS=0]="LEAVE_ROOM_SUCCESS",e[e.LEAVE_ROOM_ERROR=1]="LEAVE_ROOM_ERROR",e}({}),HC=function(e){return e[e.ACTION_START=0]="ACTION_START",e[e.ACTION_STOP=1]="ACTION_STOP",e}({}),KC=function(e){return e[e.RESULT_SUCCESS=0]="RESULT_SUCCESS",e[e.RESULT_ERROR=1]="RESULT_ERROR",e}({}),zC=function(e){return e[e.OUTPUT_AUDIO=0]="OUTPUT_AUDIO",e[e.INPUT_AUDIO=1]="INPUT_AUDIO",e[e.INPUT_VIDEO=2]="INPUT_VIDEO",e}({}),WC=function(e){return e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.AUX=2]="AUX",e}({}),GC=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.FAIL=1]="FAIL",e}({});const JC=0,qC=1;let XC=function(e){return e[e.SIGNAL=0]="SIGNAL",e[e.MEDIA=1]="MEDIA",e}({}),QC=function(e){return e[e.CLOSED=0]="CLOSED",e[e.CONNECTED=1]="CONNECTED",e}({}),$C=function(e){return e[e.EVENT_JOIN_ROOM=1]="EVENT_JOIN_ROOM",e[e.EVENT_LEAVE_ROOM=2]="EVENT_LEAVE_ROOM",e[e.EVENT_WATCH=3]="EVENT_WATCH",e[e.EVENT_OPT_AUDIO=5]="EVENT_OPT_AUDIO",e[e.EVENT_SWITCH_NET=6]="EVENT_SWITCH_NET",e[e.EVENT_OPT_VIDEO=7]="EVENT_OPT_VIDEO",e[e.EVENT_SWITCH_DEVICE=9]="EVENT_SWITCH_DEVICE",e[e.EVENT_DNS_TIME=10]="EVENT_DNS_TIME",e[e.EVENT_SWITCH_ROLE=11]="EVENT_SWITCH_ROLE",e[e.EVENT_SEND_MEDIA=12]="EVENT_SEND_MEDIA",e[e.EVENT_START_MEDIA=13]="EVENT_START_MEDIA",e[e.EVENT_SEND_AUX_STREAM=14]="EVENT_SEND_AUX_STREAM",e[e.EVENT_SUBSCIBE=16]="EVENT_SUBSCIBE",e[e.EVENT_CONNECT_OTHER_ROOM=17]="EVENT_CONNECT_OTHER_ROOM",e[e.EVENT_CONNECTION_CHANNEL_STATUS=18]="EVENT_CONNECTION_CHANNEL_STATUS",e[e.EVENT_SET_UP_STREAM=19]="EVENT_SET_UP_STREAM",e[e.EVENT_SET_AUDIO_POLICY=20]="EVENT_SET_AUDIO_POLICY",e}({}),ZC=function(e){return e[e.QoS_UP_STREAM_VIDEO=1001]="QoS_UP_STREAM_VIDEO",e[e.QoS_DOWN_STREAM_VIDEO=1002]="QoS_DOWN_STREAM_VIDEO",e[e.QoS_UP_STREAM_AUDIO=1003]="QoS_UP_STREAM_AUDIO",e[e.QoS_DOWN_STREAM_AUDIO=1004]="QoS_DOWN_STREAM_AUDIO",e[e.QoS_AUX_UP_STREAM_VIDEO=1005]="QoS_AUX_UP_STREAM_VIDEO",e[e.QoS_AUX_DOWN_STREAM_VIDEO=1006]="QoS_AUX_DOWN_STREAM_VIDEO",e[e.QoS_DOWN_STREAM_AUDIO_STAT=1007]="QoS_DOWN_STREAM_AUDIO_STAT",e[e.QoS_UP_STREAM_VIDEO_SUM=1011]="QoS_UP_STREAM_VIDEO_SUM",e[e.QoS_DOWN_STREAM_VIDEO_SUM=1012]="QoS_DOWN_STREAM_VIDEO_SUM",e[e.QoS_UP_STREAM_AUDIO_SUM=1013]="QoS_UP_STREAM_AUDIO_SUM",e[e.QoS_DOWN_STREAM_AUDIO_SUM=1014]="QoS_DOWN_STREAM_AUDIO_SUM",e}({}),eA=function(e){return e[e.DEVICE_RT_SYSTEM=2001]="DEVICE_RT_SYSTEM",e[e.DEVICE_RT_CAMERA=2002]="DEVICE_RT_CAMERA",e[e.DEVICE_RT_SPEAKER=2003]="DEVICE_RT_SPEAKER",e[e.DEVICE_RT_MICROPHONE=2004]="DEVICE_RT_MICROPHONE",e}({}),tA=function(e){return e[e.DEVICE_STATUS_SPEAKER=3001]="DEVICE_STATUS_SPEAKER",e[e.DEVICE_STATUS_CAMERA=3002]="DEVICE_STATUS_CAMERA",e[e.DEVICE_STATUS_MICROPHONE=3003]="DEVICE_STATUS_MICROPHONE",e[e.DEVICE_STATUS_DEVICE_CHANGE=3004]="DEVICE_STATUS_DEVICE_CHANGE",e[e.DEVICE_STATUS_ERROR=3005]="DEVICE_STATUS_ERROR",e[e.DEVICE_STATUS_MEDIA_QUALITY=3006]="DEVICE_STATUS_MEDIA_QUALITY",e[e.DEVICE_STATUS_USERAGENT=3007]="DEVICE_STATUS_USERAGENT",e}({}),rA=function(e){return e[e.SIGNAL_REQUEST=401]="SIGNAL_REQUEST",e[e.SIGNAL_RESPONSE=402]="SIGNAL_RESPONSE",e}({}),iA=function(e){return e[e.API_CALL=501]="API_CALL",e[e.CALLBACK_API=502]="CALLBACK_API",e}({}),nA=function(e){return e[e.FirstFrame=606]="FirstFrame",e}({}),oA=function(e){return e[e.TraceNuwa=2998]="TraceNuwa",e}({}),sA=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.FAIL=1]="FAIL",e}({});const aA=["watch","batch_watch","cancel_watch"];let cA=function(e){return e[e.SUCCESS=0]="SUCCESS",e[e.NETWORK_CONNECT_ERROR=1]="NETWORK_CONNECT_ERROR",e[e.CLIENT_NOT_IDEL=2]="CLIENT_NOT_IDEL",e[e.SERVER_ERROR=3]="SERVER_ERROR",e[e.INTERNAL_ERROR=9]="INTERNAL_ERROR",e}({});const uA="2.0.9.302",dA="ac7b7a8",lA="v3",hA=5e3,fA=1e4,pA=5,mA=6,gA=120,_A="https://logservice.hicloud.com:443",SA="1090",vA=4,yA=["webCongestionAlgorithm"],IA=["webLowLatency"];let TA=!0,RA=!0;function EA(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function bA(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),n.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function CA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(TA=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function AA(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(RA=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function wA(){if("object"==typeof window){if(TA)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function kA(e,t){RA&&console.warn(e+" is deprecated, please use "+t+" instead.")}function OA(e){return"[object Object]"===Object.prototype.toString.call(e)}function PA(e){return OA(e)?Object.keys(e).reduce((function(t,r){const i=OA(e[r]),n=i?PA(e[r]):e[r],o=i&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[r]:n})}),{}):e}function MA(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?MA(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{MA(e,e.get(t),r)}))})))}function DA(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&MA(e,r,n)}))})),n}const NA=wA;function UA(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{r=r.filter((e=>"videoinput"===e.kind));let s=r.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&r.length&&t.includes("back")&&(s=r[r.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),NA("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return NA("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function xA(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function LA(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else bA(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function BA(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function VA(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(n(t)))},r])})).then(r,i)}}function YA(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>DA(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),bA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>DA(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function jA(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function FA(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return jA(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function HA(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function KA(e,t){bA(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var zA=Object.freeze({__proto__:null,shimMediaStream:xA,shimOnTrack:LA,shimGetSendersWithDtmf:BA,shimGetStats:VA,shimSenderReceiverGetStats:YA,shimAddTrackRemoveTrackWithNative:jA,shimAddTrackRemoveTrack:FA,shimPeerConnection:HA,fixNegotiationNeeded:KA,shimGetUserMedia:UA,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function WA(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){kA("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function GA(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function JA(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(Aw){if("TypeError"!==Aw.name)throw Aw;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,o)}}function qA(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function XA(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),bA(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function QA(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){kA("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function $A(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ZA(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function ew(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function tw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function rw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var iw=Object.freeze({__proto__:null,shimOnTrack:GA,shimPeerConnection:JA,shimSenderGetStats:qA,shimReceiverGetStats:XA,shimRemoveStream:QA,shimRTCDataChannel:$A,shimAddTransceiver:ZA,shimGetParameters:ew,shimCreateOffer:tw,shimCreateAnswer:rw,shimGetUserMedia:WA,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function nw(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function ow(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function sw(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function aw(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(cw(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function cw(e){return e&&void 0!==e.video?Object.assign({},e,{video:PA(e.video)}):e}function uw(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;rt.generateCertificate})}function dw(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function lw(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function hw(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var fw=Object.freeze({__proto__:null,shimLocalStreamsAPI:nw,shimRemoteStreamsAPI:ow,shimCallbacksAPI:sw,shimGetUserMedia:aw,shimConstraints:cw,shimRTCIceServerUrls:uw,shimTrackEventTransceiver:dw,shimCreateOfferLegacy:lw,shimAudioContext:hw}),pw={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let i=8;i0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let o=3;o{r.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let n=0;return r.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const u=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));u.length>0&&u[0].length>1&&u[0][0]===a&&(c=u[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=d}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const o=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let t=0;t(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Sw(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=mw.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=mw.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=mw.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return r.apply(this,arguments)}}function vw(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},bA(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function yw(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function Iw(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Tw(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Rw(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var Ew=Object.freeze({__proto__:null,shimRTCIceCandidate:_w,shimMaxMessageSize:Sw,shimSendThrowTypeError:vw,shimConnectionState:yw,removeExtmapAllowMixed:Iw,shimAddIceCandidateNullOrEmpty:Tw,shimParameterlessSetLocalDescription:Rw});const bw=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=wA,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=EA(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=EA(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=EA(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Ew,extractVersion:EA,disableLog:CA,disableWarnings:AA,sdp:gw};switch(i.browser){case"chrome":if(!zA||!HA||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=zA,Tw(e,i),Rw(e),UA(e,i),xA(e),HA(e,i),LA(e),FA(e,i),BA(e),VA(e),YA(e),KA(e,i),_w(e),yw(e),Sw(e,i),vw(e),Iw(e,i);break;case"firefox":if(!iw||!JA||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=iw,Tw(e,i),Rw(e),WA(e,i),JA(e,i),GA(e),QA(e),qA(e),XA(e),$A(e),ZA(e),ew(e),tw(e),rw(e),_w(e),yw(e),Sw(e,i),vw(e);break;case"safari":if(!fw||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=fw,Tw(e,i),Rw(e),uw(e),lw(e),sw(e),nw(e),ow(e),dw(e),aw(e),hw(e),_w(e),Sw(e,i),vw(e),Iw(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});window.AudioContext=window.AudioContext||window.webkitAudioContext,window.RTCPeerConnection=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;class Cw{static async checkSystemRequirements(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!window||!navigator)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"window or navigator error");if("chrome"===bw.browserDetails.browser&&Cw.getBrowserVersion()<67)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"browser not support: ".concat(navigator.userAgent));if(!("WebSocket"in window))throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"WebSocket error");if(!window.RTCPeerConnection)throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection Object not exist");let t=null;try{let e=new RTCPeerConnection;t=await e.createOffer({offerToReceiveAudio:!1,offerToReceiveVideo:!0}),Cw.isChrome()&&!/H264/i.test(t.sdp)&&(e.close(),e=new RTCPeerConnection,t=await e.createOffer({offerToReceiveAudio:!1,offerToReceiveVideo:!0})),e.close()}catch(jN){throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection construct error: ".concat(jN.message))}if(t&&!/H264/i.test(t.sdp))throw new qc(Gc.RTC_ERR_CODE_WEBRTC_UNSUPPORTED,"RTCPeerConnection unsupport AVC codec.");if(!("mediaDevices"in navigator))throw new qc(Gc.RTC_ERR_CODE_MEDIA_UPSTREAM_UNSUPPORTED,"navigator.mediaDevices is not supported");return!XR.isMobileWeChatBrowser()||!e||await Cw.checkwWeChatSupported()}static async checkwWeChatSupported(){let e=[".*(iphone|ipad).*OS\\s1[4-9]_.*MicroMessenger.*",".*huawei.*(TBS|XWEB).*MicroMessenger.*",".*honor.*(TBS|XWEB).*MicroMessenger.*"];if(localStorage){const r=JSON.parse(localStorage.getItem("supportDeviceWhiteList")||"{}");var t;if(XR.getCurrentTimestamp()-parseInt(r.expire||"0")<=3e4)e=r.rules;else null===(t=localStorage)||void 0===t||t.removeItem("supportDeviceWhiteList")}if(Cw.checkSupportByRegexRules(e))return!0;const r={rules:[".*(iphone|ipad).*MicroMessenger.*",".*huawei.*(TBS|XWEB).*MicroMessenger.*",".*honor.*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; V.*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; (C?P|OPPO).*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; (Redmi|MI).*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; SM-.*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; M2.*(TBS|XWEB).*MicroMessenger.*",".*Linux; Android.*; RMX.*(TBS|XWEB).*MicroMessenger.*"]};if(r){var i;const e=r;if(e.expire=XR.getCurrentTimestamp(),null===(i=localStorage)||void 0===i||i.setItem("supportDeviceWhiteList",JSON.stringify(e)),Cw.checkSupportByRegexRules(e.rules)&&this.checkIOSVersion())return!0}else{var n;null===(n=localStorage)||void 0===n||n.removeItem("supportDeviceWhiteList")}throw new Error("browser not support")}static checkIOSVersion(){const e=navigator.userAgent;if(/(iPhone|iPad|iPod|iOS)/i.test(e)){const t=e.match(/OS (\d+)_(\d+)_?(\d+)?/);if(t&&parseFloat(t[1]+"."+t[2])<14.3)throw new Error("browser not support,iOS system is earlier than or equal to 14.3")}return!0}static checkSupportByRegexRules(e){const t=navigator.userAgent;let r=!1;for(const i of e){if(new RegExp(i,"ig").test(t)){r=!0;break}}return r}static isRTCScreenShareSupported(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}static isChrome(){return"chrome"===bw.browserDetails.browser}static isFirefox(){return"firefox"===bw.browserDetails.browser}static getBrowserVersion(){if("safari"===bw.browserDetails.browser){const e=/.*Version\/(\d+).*/gi.exec(navigator.userAgent);if(e&&2===e.length)return parseInt(e[1])}return"chrome"===bw.browserDetails.browser?bw.browserDetails.version||91:bw.browserDetails.version}static isOnlySupportUnfiedPlan(){let e=!0;if("chrome"===bw.browserDetails.browser){e=Cw.getBrowserVersion()>90}else"safari"===bw.browserDetails.browser&&(e=bw.browserDetails.supportsUnifiedPlan);return e}static getBrowserInfo(){return"".concat(bw.browserDetails.browser.toLowerCase(),"-").concat(Cw.getBrowserVersion())}}var Aw=function(e){return function(t){return function(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}(t)===e}},ww=Aw("function"),kw=Aw("object"),Ow=Aw("array"),Pw=Aw("string"),Mw=Aw("number"),Dw=Aw("boolean"),Nw=Aw("undefined"),Uw=Aw("null");function xw(e){return xw="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xw(e)}function Lw(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Bw(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r=0&&i.length===Math.floor(i.length)&&i.length3&&void 0!==arguments[3]&&arguments[3];e.addEventListener?e.addEventListener(t,r,i):e.attachEvent("on".concat(t),r)}var Mk=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Gw(e.split("?"),2),i=r[0],n=r[1];if(!n)return e;var o=n.split("&").filter((function(e){return!ak(t,e.split("=")[0].toLocaleLowerCase())}));return o.length?"".concat(i,"?").concat(o.join("&")):i},Dk=function(e){var t={};e.includes("#")&&(e=e.split("#")[0]);var r=e.split("?")[1];if(!r)return t;for(var i=r.split("&"),n=0;n0&&void 0!==arguments[0]&&arguments[0];Lw(this,e),this.isH5=r,this.waitTime=0,this.waitTimeFlagTime=0,this.waitTimeFlag=!0,this.accessTime=Ik(),this.config={defaultCookie:{},useCookie:!0,isInit:!1,usedPageUrl:!0,intervalTime:18e5,batchSend:!1},this.globals={idsite:"",title:xk.title,id:"unknown",rid:"unknown",idts:Ik(),idvc:0,idn:"",di:{sessionId:"unknown"},refts:Ik(),viewts:Ik(),CXX:"",uid:"",cvar:""},this.customData={},ck(Nk,(function(e,r){t[r]=e})),Pk(Lk,"beforeunload",this.beforeUnloadHandler.bind(this)),Pk(xk,"visibilitychange",this.stateChanged.bind(this)),this.updateSessionId()}return Vw(e,[{key:"updateSessionId",value:function(){var e=Ek("sessionId");e&&e.sessionId&&(this.globals.di.sessionId=e.sessionId)}},{key:"beforeUnloadHandler",value:function(){this.config.isInit&&this.config.useCookie&&kk(this.getStoreName(nk),Ik(),31536e6,"/"),this.stateChanged()}},{key:"getStoreName",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ek,r=arguments.length>2?arguments[2]:void 0;return e&&this.globals.idsite?"".concat(t).concat(e,"_").concat(this.globals.idsite,"_").concat((r||location.host).replace(/\./g,"_")):""}},{key:"handleSessionId",value:function(){var e=this.getStoreName("idn"),t=wk(e);t||(t=lk()),this.globals.idn=t,this.config.useCookie&&kk(e,t,this.config.intervalTime,"/")}},{key:"stateChanged",value:function(){"visible"===xk.visibilityState&&this.updateSessionId(),"hidden"===xk.visibilityState&&this.config.batchSend&&this.batchSendNow(),this.waitTimeFlag?this.waitTime+=Ik()-(this.waitTimeFlagTime||this.accessTime):this.waitTimeFlagTime=Ik(),this.waitTimeFlag=!this.waitTimeFlag}},{key:"getData",value:function(e,t,r){var i=Lk.navigator.userAgent,n=this.globals,o=n.id,s=n.rid,a=n.di,c=n.CXX,u=n.idsite,d=n.uid,l=n.cvar,h=n.idts,f=n.idvc,p=n.idn,m=n.refts,g=n.viewts;return{type:e,vf:o,rid:s,nsid:a.sessionId,rt:t.eventTime,ut:i.match(/AppleWebKit.*Mobile.*/)?-1!==dk(i," wv")?2:1:0,cxx:c,idsite:u,suid:d,cvar:t.cvar||l,idts:h,idvc:f,idn:p,refts:m,viewts:g,hsv:hk,data:r}}},{key:"getFinalSendData",value:function(e){var t=new Date,r=this.globals,i=r.title,n=r.id,o=r.idsite,s=r.cvar,a=r.idts,c=r.idvc,u=r.idn,d=r.refts,l=r.viewts,h=r.rid,f=r.di,p=this.config.usedPageUrl,m={idsite:encodeURIComponent(o),rec:"1",r:"886244",h:t.getHours(),m:t.getMinutes(),s:t.getSeconds(),url:encodeURIComponent(this.deleteUrlQuery(p?Lk.location.href:"/",fk)),_id:encodeURIComponent(n),_rid:encodeURIComponent(h),_nsid:encodeURIComponent(f.sessionId),_idts:a,_idvc:c,_idn:u,urlref:this.deleteUrlQuery(xk.referrer,fk),_refts:d,_viewts:l,scd:"24",vpr:"".concat(Lk.screen.width," X ").concat(Lk.screen.height),cvar:kw(e.cvar||s)?encodeURIComponent(JSON.stringify(e.cvar||s)):encodeURIComponent(e.cvar||s),pdf:"1",qt:"0",data:this.isH5?JSON.stringify(e):encodeURIComponent(JSON.stringify(e))};return e.type===Zw||e.type===$w?uk({link:encodeURIComponent(i)},m):uk({action_name:encodeURIComponent(i)},m)}},{key:"initCookie",value:function(e){this.config.isInit=!0;var t=this.config,r=t.useCookie,i=t.defaultCookie.domain;if(r){if(i){var n=this.getStoreName(rk,ek),o=this.getStoreName(ik,ek);Ok(n),Ok(o)}var s=this.getStoreName(rk,ek,i),a=this.getStoreName(ik,ek,i),c=wk(s),u=wk(a);e&&e(s,c,a,u,i),c||(Ck.isSupport()&&Ck.get(s)?(c=Ck.get(s),u=Ck.get(a)||Ik()):(c=lk(),u=Ik()),kk(s,c,31536e6,"/",i),kk(a,u,31536e6,"/",i)),this.globals.id=c,this.globals.idts=u||Ik();var d=this.getStoreName("refts"),l=wk(d);l||xk.referrer&&(l=Ik(),kk(d,l,15552e6,"/")),this.globals.refts=l||Ik();var h=this.getStoreName(nk),f=wk(h);this.globals.viewts=f||Ik();var p=this.getStoreName("idvc"),m=wk(p);m=m?Number(m)+1:Ck.isSupport()&&Ck.get(p)?Number(Ck.get(p))+1:1,kk(p,m,31536e6,"/"),this.globals.idvc=m,Ck.isSupport()&&!Ck.get(s)&&(Ck.set(s,c),Ck.set(a,u),Ck.set(p,m))}else this.globals.id="unknown",this.globals.idts=Ik(),this.globals.refts=Ik(),this.globals.viewts=Ik(),this.globals.idvc=0;this.handleSessionId()}},{key:"setIdsite",value:function(e){return Pw(e)?new RegExp("^[a-zA-Z0-9_./][A-Za-z0-9_./]*$").test(e)?(this.globals.idsite=e,this.initCookie(),this):(console.error("idsite is invalid."),this):(console.error("idsite type should be string."),this)}},{key:"setAutoTrack",value:function(e,t,r){var i=this;if(!kw(e))return this;var n=function(t,r){var n=new t(i);n.init(e),r&&r(n)};if(t)n(t,r);else if(Lk.HAAutoTracker)n(Lk.HAAutoTracker,r);else{var o=Ik();!function(e,t){var r=Uk.createElement("script");r.type="text/javascript",r.readyState?r.onreadystatechange=function(){"loaded"!==r.readyState&&"complete"!==r.readyState||(r.onreadystatechange=null,t())}:r.onload=t,r.src=e,Uk.getElementsByTagName("head")[0].appendChild(r)}(e.autotracker_url||pk,(function(){var e=Ik();Tk("[load+excute] HAWebSDK autotracker module use ".concat(e-o," ms.")),n(Lk.HAAutoTracker,r)}))}return this}}]),e}(),Vk=function(){function e(t,r,i){Lw(this,e),this.core=t,this.dataType=r,this.serverUrl=i,this.state=0,this.keys=[],this.queue=[],this.intervalID=null}return Vw(e,[{key:"isH5",value:function(){return!0===this.core.isH5||void 0!==Rk().haGetDeviceInfo}},{key:"init",value:function(){var e=this;this.core.config.batchSend?(ck(["batchSend"],(function(t){var r=e[t];e[t]=function(){0===this.state?r.apply(this,arguments):this.queue.push([t,arguments])}})),!this.intervalID&&this.core.config.batchSend.interval&&(this.intervalID=setInterval((function(){e.batchSend()}),this.core.config.batchSend.interval))):this.intervalID&&clearInterval(this.intervalID)}},{key:"batchSend",value:function(){var e=this,t=this.getEventsToSendFromStorage();0!==t.length&&(this.state=1,this.onReport(this.core.getFinalSendData(t),(function(t){e.state=0,200===t.status?(e.core.config.batchSend.retryTimes=10,ck(e.keys,(function(e){Ck.remove(e)})),e.keys=[],e.batchSend(),e.queue.length>0&&(e[e.queue[0][0]].apply(e,e.queue[0][1]),e.queue=e.queue.splice(0,1))):e.core.config.batchSend.retryTimes<=1?e.intervalID&&clearInterval(e.intervalID):e.core.config.batchSend.retryTimes--}),!0))}},{key:"onceSend",value:function(e,t){this.onReport(this.core.getFinalSendData(e),t,!1)}},{key:"addToStorage",value:function(e,t){try{var r=JSON.stringify(e);if(Rk().haEncrypt){var i=Ik();r=Rk().haEncrypt(r);var n=Ik();Tk("data encrypt use ".concat(n-i," ms. encrypted data: ").concat(r))}Ck.set(this.core.getStoreName(lk(),tk),r)}catch(r){r.message===ok&&(this.onceSend(e,t),this.batchSend())}}},{key:"getEventsToSendFromStorage",value:function(){var e=[],t=0;if(this.isH5())for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];return Lw(this,r),(e=t.call(this,i)).config.linker={},e.config.serverUrl="",e.config.requestMode="",e.config.isImg=!1,e.config.debugMode=!1,e.config.customUrlParams={},e.config.defaultHeaders={"Content-type":"application/x-www-form-urlencoded;charset=UTF-8"},e.defaultSender=new Vk(Kw(e)),e.reportMap={},Pk(Yk,"click",e.hrefIntercept.bind(Kw(e)),!0),e}return Vw(r,[{key:"urlAddLinker",value:function(e,t){if(!e)return e;var r=e.split("#"),i=r[0],n=r[1]?"#".concat(r[1]):"",o=i.replace(/(https|http):\/\/([^/?]+)(.*)/,"$2"),s=!1;if(this.config.linker.exclude&&(s=this.config.linker.exclude.includes(o)),this.config.linker.domains&&!s&&this.config.linker.domains.filter((function(e){return new RegExp("".concat(e,"$"),"i").test(o)})).length){t&&t.preventDefault();var a=this.getStoreName(rk,ek,this.config.defaultCookie.domain),c={ts:Ik(),id:wk(a)};this.config.linker.ext&&(c.ext=this.config.linker.ext),i=dk(i,"?")>-1?"".concat(i,"&ha_linker=").concat(jk.btoa(JSON.stringify(c))).concat(n):"".concat(i,"?ha_linker=").concat(jk.btoa(JSON.stringify(c))).concat(n)}return i}},{key:"hrefIntercept",value:function(e){var t=e.target||e.srcElement;if("a"!==mk(t)){var r=yk(t);if(!r)return;t=r}var i=t.getAttribute("href");i&&(i=this.urlAddLinker(i,e),dk(i,"ha_linker")>-1&&jk.open(i,t.getAttribute("target")||"_self"))}},{key:"initCookie",value:function(){var e=this;Ww(Fw(r.prototype),"initCookie",this).call(this,(function(t,r,i,n,o){var s=Dk(Yk.location.href).ha_linker;if(s)try{var a=JSON.parse(jk.atob(s));!(Ik()-a.ts>(a.ext||1e4))&&a.id&&(r||(r=a.id,kk(t,r,31536e6,"/",o),n=Ik(),kk(i,n,31536e6,"/",o)),e.globals.rid=a.id)}catch(e){console.error("Invalid linker:"+e)}}))}},{key:"getSender",value:function(){var e=this,t=null;return ck(this.reportMap,(function(r){r.url===e.config.serverUrl&&(t=r.sender)})),t||this.defaultSender}},{key:"push",value:function(){for(var e=arguments,t=this,r=function(){var r=e[i],n=r.shift();setTimeout((function(){try{Pw(n)?t[n].apply(t,r):t.apply(t,r)}catch(e){console.error("Invalid method:"+n+", please check!")}}),0)},i=0;i0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1?arguments[1]:void 0;this.config.serverUrl=e;var r=e;return Nw(t)||(r=t),this.reportMap[r]||(this.reportMap[r]={url:e,sender:new Vk(this,r,e)},this.config.batchSend&&this.reportMap[r].sender.init()),this}},{key:"setTitle",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.title=e,this}},{key:"setUserAccount",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.id=e,this}},{key:"setCXX",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.CXX=e,this}},{key:"setUid",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.uid=e,this}},{key:"setPageData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this.globals.cvar=e,this}},{key:"setCustomData",value:function(e){return kw(e)||ww(e)?this.customData=e:console.error("The arguments of the setCustomData() method is invalid."),this}},{key:"setHttpHeader",value:function(e){return kw(e)?(uk(this.config.defaultHeaders,e),this):(console.error("custom header type should be object."),this)}},{key:"setIsUseCookie",value:function(e){if(!Dw(e))return console.error("useCookie type should be boolean"),this;if(this.config.useCookie=e,!this.config.useCookie){var t=Yk.cookie.split("; "),r=/^(HW_)(id|idts|idvc|idn|viewts|refts)_/;ck(t,(function(e){var t=e.split("=");r.test(t[0])&&Ok(t[0])})),this.initCookie()}return this}},{key:"setReportMethod",value:function(e){return Dw(e)?(this.config.isImg=e,this):(console.error("isImg type should be boolean."),this)}},{key:"setSessionTimeoutDuration",value:function(e){return Mw(e)?(this.config.intervalTime=e,this):(console.error("intervalTime type should be number."),this)}},{key:"setDebugMode",value:function(e){return Dw(e)?(this.config.debugMode=e,this):(console.error("debugMode type should be boolean"),this)}},{key:"setCustomUrlParams",value:function(e){if(!kw(e))return console.error("customUrlParams type should be object"),this;for(var t in e){if(ak(["x_hasdk_debug","url","_id","_idts","_idvc","h","m","s","_rid"],t))return console.error("customUrlParams can'n include x_hasdk_debug, url, _id, _idts, _idvc, h, m, s, _rid"),this;var r=e[t];if(!r||!Mw(r)&&!Pw(r))return console.error("customUrlParams object value should be number or string"),this;if(!new RegExp("^[a-zA-Z0-9_./][A-Za-z0-9_./]*$").test(t)||!new RegExp("^[a-zA-Z_0-9_./][A-Za-z0-9_./]*$").test(r))return console.error("customUrlParams object include invalid key or value"),this;uk(this.config.customUrlParams,Yw({},t,r))}return this}},{key:"setIstUseUrl",value:function(e){return Dw(e)?(this.config.usedPageUrl=e,this):(console.error("usedPageUrl type should be boolean."),this)}},{key:"setRequestMode",value:function(e){return"ajax"!==e||_k()?"beacon"!==e||vk()?(ak(["beacon","ajax","img"],e)&&(this.config.requestMode=e),this):(console.error("navigator.sendBeacon() is not supported."),this):(console.error("XMLHttpRequest is not supported."),this)}},{key:"setBatchSend",value:function(e){if(!Ck.isSupport())return console.error("localStorage is not supported, so batch send is not supported."),this;if(!_k())return console.error("XMLHttpRequest is not supported, so batch send is not supported."),this;var t={timeout:6e3,interval:6e3,maxLength:6,retryTimes:10};return Dw(e)&&e?this.config.batchSend=t:kw(e)&&(this.config.batchSend=uk(t,e)),ck(this.reportMap,(function(e){e.sender&&e.sender.init()})),this}},{key:"batchSendNow",value:function(){return ck(this.reportMap,(function(e){e.sender&&e.sender.batchSend()})),this}},{key:"setLinker",value:function(e){return kw(e)?Ow(e.domains)?e.exclude&&!Ow(e.exclude)?(console.error("custom exclude type should be Array."),this):(this.config.linker=e,this):(console.error("custom domains type should be Array."),this):(console.error("custom linker type should be object."),this)}},{key:"setUrlLinker",value:function(e){return this.urlAddLinker(e)}},{key:"setCookie",value:function(e){return kw(e)?(this.config.defaultCookie=e,this):(console.error("custom cookie type should be object."),this)}}]),r}(),Hk=document,Kk=window,zk=Hk.documentElement,Wk=Hk.body,Gk=document,Jk=window,qk=function(e){jw(r,Fk);var t=zw(r);function r(){var e;return Lw(this,r),(e=t.call(this)).config.baseinfotypeSwitch1=!1,e.switch1Num=0,e.config.baseinfotypeSwitch2=!1,e.switch2Num=0,e}return Vw(r,[{key:"setBaseinfotypeSwitch",value:function(e){return Dw(e)?(this.config.baseinfotypeSwitch1=e,e&&0===this.switch1Num&&(this.switch1Num++,Pk(Gk,"DOMContentLoaded",this.reportPageEntryEvent.bind(this))),this):(console.error("baseinfotypeSwitch1 type should be boolean."),this)}},{key:"setWindowCloseSwitch",value:function(e){return Dw(e)?(this.config.baseinfotypeSwitch2=e,e&&0===this.switch2Num&&(this.switch2Num++,Pk(Jk,"beforeunload",this.reportPageCloseEvent.bind(this))),this):(console.error("baseinfotypeSwitch2 type should be boolean."),this)}},{key:"sendPageinfo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.waitTime=0,this.waitTimeFlagTime=0,this.waitTimeFlag=!0,this.accessTime=Ik(),this.config.baseinfotypeSwitch1=!0,this.reportPageEntryEvent(e,t),this}},{key:"sendPageClose",value:function(){return this.config.baseinfotypeSwitch2=!0,this.reportPageCloseEvent(),this}},{key:"sendData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s={eventTime:Ik(),eventName:e,eventLabel:t,customData:r,cvar:i};return this.execReport(Qw,s,n,o),this}},{key:"sendClickData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s={eventTime:Ik(),eventName:e,eventLabel:t,customData:r,cvar:i};return this.execReport(Zw,s,n,o),this}},{key:"bindclick",value:function(e,t,r,i,n){var o=this,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],a=e===Gk?Gk:Gk.getElementById(e);return a?(Pk(a,t,(function(t){var c=t.screenX,u=t.screenY,d=t.clientX,l=t.clientY,h=Kk.innerHeight||zk.clientHeight||Wk.clientHeight||0,f=Kk.innerWidth||zk.clientWidth||Wk.clientWidth||0,p={eventTime:Ik(),elementId:e,cls:a.className,data:r,cvar:i,position:{res:"".concat(c,"X").concat(u),vpr:"".concat(d,"X").concat(l),doc:"".concat(f,"X").concat(h)}};o.execReport($w,p,n,s)})),this):this}},{key:"reportPageEntryEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.execReport(Xw,{eventTime:Ik()},e,t)}},{key:"reportPageCloseEvent",value:function(){this.execReport(Xw,{eventTime:Ik()})}},{key:"execReport",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this.handleSessionId();var n=this.getEventData(e,t),o=this.getSender();this.config.batchSend&&!i?(n.dataType=o.dataType,o.addToStorage(n,r)):o.onceSend(n,r)}},{key:"getEventData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.currentUrl,i=void 0===r?Jk.location.href:r,n={url:Mk(this.config.usedPageUrl?i:"/",fk),title:this.globals.title,at:this.accessTime,rf:Mk(Gk.referrer,fk)};return e===Xw?(n.res="".concat(Jk.screen.width," X ").concat(Jk.screen.height),n.cwt=t.eventTime,n.dt=this.waitTime):e===Qw||e===Zw?(n.en=t.eventName,n.el=t.eventLabel,n.cd=t.customData):e===$w&&(n.ei=t.elementId===Gk?"#document":t.elementId,n.ec=t.cls,n.ps=t.position,n.data=t.data||""),this.getData(e,t,n)}}]),r}(),Xk=Ik(),Qk=new qk,$k=Ik();Tk("[excute] hawebsdk use ".concat($k-Xk," ms."));class Zk{static checkStringParameter(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3?arguments[3]:void 0;if(!e&&0===r)return;if("string"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid type: ".concat(e));const n=this.getStringBytes(e);if(n>t||n?@[\\]^_{}|~,]{1,128}$")}static checkRoomId(e){this.checkStringParameter(e,64,1,"^[a-zA-Z0-9-_]{1,64}$")}static checkUserId(e){this.checkStringParameter(e,64,1,"^[a-zA-Z0-9-_]{1,64}$")}static checkUserName(e){this.checkStringParameter(e,256,0)}static checkUserRole(e){if("number"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid parameter: ".concat(e));this.checkStringParameter("".concat(e),1,1,"^[0|2]$")}static checkSFUResourceType(e){if(null!=e){if("number"!=typeof e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramter: ".concat(e));this.checkStringParameter("".concat(e),1,1,"^[0|1|2|3]$")}}static checkResourceTags(e){if(null!=e&&(!Array.isArray(e)||e.filter((e=>"string"!=typeof e)).length>0))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramter of resourceTags: ".concat(e))}static checkUserInfo(e){if("object"!=typeof e)throw this.logger.error("ParameterValidator","userInfo type invalid "),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userInfo type invalid");this.checkUserId(e.userId),this.checkUserName(e.userName),this.checkUserRole(e.role),this.checkUserOptionInfo(e.optionInfo)}static checkJoinParams(e,t){this.checkRoomId(e),this.checkUserInfo(t)}static getStringBytes(e){if(!e)return 0;if("string"!=typeof e)return e.byteLength;let t=0;if(window.TextEncoder){return t=(new TextEncoder).encode(e).length,t}const r=e.length;for(let i=0;i255?t+=3:t++;return t}static checkUserOptionInfo(e){if(e&&![!0,!1,null,void 0].includes(e.recordPlaceholder))throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid parameter: ".concat(e.recordPlaceholder))}static checkSrcMultiRoomInfo(e){if(!e.authorization||!e.ctime||"0"!==e.userId)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramters: ".concat(e.authorization," ").concat(e.ctime," ").concat(e.userId))}static checkDstMultiRoomInfo(e,t){this.checkRoomId(e.roomId),this.checkUserRole(t);const r=e.role>=t;if(!e.authorization||!e.ctime||!r)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid paramters: ".concat(e.authorization," ").concat(e.ctime," ").concat(e.role))}static checkCmdMsgValid(e){const t=Zk.getStringBytes(e);if(t>32768)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid msg length: ".concat(t))}}i(Zk,"logger",iE.getLogger());var eO=new class{setPorxyServer(e){Zk.checkStringParameter(e,256,1);const t=/(.*:\/\/)?([^:]+):?(.*)?/.exec(e);let r=e;/^((\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))(\.|$)){4}$/.test(t[2])?t[1]||(r="http://".concat(t[2]).concat(t[3]?":":"").concat(t[3]||"")):t[1]||(r="https://".concat(t[2]).concat(t[3]?":":"").concat(t[3]||"")),this.proxyServer=r}getProxyServer(){return this.proxyServer}};const tO={},rO={grs_sdk_global_route_config_hwrtc:{applications:[],services:[{name:"com.huawei.cloud.videortn",routeBy:"ser_country>geo_ip",servings:[{countryOrAreaGroup:"DR1",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-drcn.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR2",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-dra.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR3",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-dre.platform.dbankcloud.com"}},{countryOrAreaGroup:"DR4",addresses:{GLOBAL:"wss://rtc.platform.dbankcloud.com",ROOT:"wss://rtc-drru.platform.dbankcloud.com"}}],countryOrAreaGroups:[]}],countryOrAreaGroups:[{id:"DR1",name:"China",countriesOrAreas:["CN"],description:"China zone"},{id:"DR2",name:"Asian-African-Latin American",countriesOrAreas:["AE","AF","AG","AI","AM","AO","AQ","AR","AS","AW","AZ","BB","BD","BF","BH","BI","BJ","BL","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CC","CD","CF","CG","CI","CK","CL","CM","CO","CR","CU","CV","CX","DJ","DM","DO","DZ","EC","EG","EH","ER","ET","FJ","FK","FM","GA","GD","GE","GF","GH","GM","GN","GP","GQ","GS","GT","GU","GW","GY","HK","HM","HN","HT","ID","IN","IO","IQ","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LK","LR","LS","LY","MA","MG","MH","ML","MM","MN","MO","MP","MQ","MR","MS","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NP","NR","NU","OM","PA","PE","PF","PG","PH","PK","PN","PR","PS","PW","PY","QA","RE","RW","SA","SB","SC","SD","SG","SH","SL","SN","SO","SR","SS","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TT","TV","TW","TZ","UG","UY","UZ","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"],description:"Asian-African-Latin American zone"},{id:"DR3",name:"Europe",countriesOrAreas:["AD","AL","AN","AT","AU","AX","BA","BE","BG","BQ","CA","CH","CW","CY","CZ","DE","DK","EE","ES","FI","FO","FR","GB","GG","GI","GL","GR","HR","HU","IE","IL","IM","IS","IT","JE","LI","LT","LU","LV","MC","MD","ME","MF","MK","MT","NL","NO","NZ","PL","PM","PT","RO","RS","SE","SI","SJ","SK","SM","SX","TR","UA","UM","US","VA","VC","XK","YK"],description:"Europe zone"},{id:"DR4",name:"Russia",countriesOrAreas:["RU"],description:"Russia zone"},{id:"DR5",name:"A2",countriesOrAreas:["IR"],description:"A2 zone"}]},grs_sdk_global_route_config_rtcha:{applications:[],services:[{name:"com.huawei.cloud.hianalytics",routeBy:"ser_country",servings:[{countryOrAreaGroup:"DR1",addresses:{ROOT:"https://metrics1.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR2",addresses:{ROOT:"https://metrics3.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR3",addresses:{ROOT:"https://metrics2.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR4",addresses:{ROOT:"https://metrics5.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR5",addresses:{ROOT:"https://metrics4.data.hicloud.com:6447"}}],countryOrAreaGroups:[]},{name:"com.huawei.cloud.hianalytics.aspg",routeBy:"ser_country",servings:[{countryOrAreaGroup:"DR1",addresses:{ROOT:"https://metrics1.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR2",addresses:{ROOT:"https://metrics-dra.dt.hicloud.com:6447"}},{countryOrAreaGroup:"DR3",addresses:{ROOT:"https://metrics2.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR4",addresses:{ROOT:"https://metrics5.data.hicloud.com:6447"}},{countryOrAreaGroup:"DR5",addresses:{ROOT:"https://metrics4.data.hicloud.com:6447"}}],countryOrAreaGroups:[]}],countryOrAreaGroups:[{id:"DR1",name:"China",countriesOrAreas:["CN"],description:"China zone"},{id:"DR2",name:"Asian-African-Latin American",countriesOrAreas:["AE","AF","AG","AI","AM","AO","AQ","AR","AS","AW","AZ","BB","BD","BF","BH","BI","BJ","BL","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CC","CD","CF","CG","CI","CK","CL","CM","CO","CR","CU","CV","CX","DJ","DM","DO","DZ","EC","EG","EH","ER","ET","FJ","FK","FM","GA","GD","GE","GF","GH","GM","GN","GP","GQ","GS","GT","GU","GW","GY","HK","HM","HN","HT","ID","IN","IO","IQ","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LK","LR","LS","LY","MA","MG","MH","ML","MM","MN","MO","MP","MQ","MR","MS","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NP","NR","NU","OM","PA","PE","PF","PG","PH","PK","PN","PR","PS","PW","PY","QA","RE","RW","SA","SB","SC","SD","SG","SH","SL","SN","SO","SR","SS","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TT","TV","TW","TZ","UG","UY","UZ","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"],description:"Asian-African-Latin American zone"},{id:"DR3",name:"Europe",countriesOrAreas:["AD","AL","AN","AT","AU","AX","BA","BE","BG","BQ","CA","CH","CW","CY","CZ","DE","DK","EE","ES","FI","FO","FR","GB","GG","GI","GL","GR","HR","HU","IE","IL","IM","IS","IT","JE","LI","LT","LU","LV","MC","MD","ME","MF","MK","MT","NL","NO","NZ","PL","PM","PT","RO","RS","SE","SI","SJ","SK","SM","SX","TR","UA","UM","US","VA","VC","XK","YK"],description:"Europe zone"},{id:"DR4",name:"Russia",countriesOrAreas:["RU"],description:"Russia zone"},{id:"DR5",name:"A2",countriesOrAreas:["IR"],description:"A2 zone"}]}},iO="RTCReport";const nO=new class{constructor(){this.logger=iE.getLogger(),this.regularReport(hA),Qk.push(["setOnReportUrl","".concat(rO.grs_sdk_global_route_config_rtcha.services[0].servings[0].addresses.ROOT,"/webv4")]),Qk.push(["setIdsite","com.huawei.rtcsdk"]),Qk.setBatchSend({timeout:13e3,interval:!0,maxLength:30}),this.records=[],Cw.isFirefox()||(window.onbeforeunload=()=>{this.logger.info("stat","window is closing, emergency report"),this.records.length>0&&this.reportRecordsBeacon(this.records),this.clearData()})}setReportServer(e){this.opsServer=null;const t=eO.getProxyServer();if(t){const r=e.replace(/http(s)?:\/\//,"");this.opsServer="".concat(t,"/").concat(r,"/webv4")}else this.opsServer="".concat(e,"/webv4");Qk.push(["setOnReportUrl",this.opsServer])}regularReport(e){this.reportInterval&&clearInterval(this.reportInterval),this.reportInterval=setInterval((()=>{if(this.opsServer&&0!=this.records.length)try{Qk.setRequestMode("ajax"),this.records.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};Qk.push(["sendData",t,t,r,null,null])})),this.clearData()}catch(jN){this.logger.error(iO,"regularReport failed")}}),e)}async addRecords(e){this.records=this.records.concat(e||[]),this.adjustRecordsLength(this.records)}async addRecord(e){this.records.push(e),this.adjustRecordsLength(this.records)}adjustRecordsLength(e){e.length>1e4&&e.splice(0,e.length-1e4)}clearData(){this.records.length=0}immediateReportRecords(){this.opsServer&&(this.reportRecords(this.records),this.clearData())}reportRecords(e){if(this.opsServer)try{Qk.setRequestMode("ajax"),e.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};Qk.push(["sendData",t,t,r,null,t=>{4===t.readyState&&200===t.status||this.addRecord(e)},!0])}))}catch(jN){throw this.logger.error(iO,"fetch request failed"),jN}}async reportRecordsBeacon(e){if(this.opsServer)try{Qk.setRequestMode("beacon"),e.forEach((e=>{const t=e.event.toString(),r={rtc_sdk:e};Qk.push(["sendData",t,t,r,null,null,!0])}))}catch(jN){throw this.logger.error(iO,"beacon request failed"),jN}}},oO="STATISTIC_ENABLE",sO="ACCESS_RESOURCE_TYPE",aO="RESOURCE_TAGS",cO="FRAME_ENCRYPTION_MODE",uO="PORT_TYPE",dO="ENVIRONMENT_SUFFIX",lO="GRS_LOCAL_EXT_INFO",hO={ACCESS_RESOURCE_TYPE:e=>Zk.checkSFUResourceType(e),RESOURCE_TAGS:e=>Zk.checkResourceTags(e)},fO="ParametersUtil";const pO=new class{constructor(){this.logger=iE.getLogger(),this.parameters=new Map}setParameter(e,t){if(!e)return this.logger.error(fO,"setParameter, parameterKey is null"),!1;try{return this.logger.debug(fO,"setParameter, parameterKey: ".concat(e,", parameterValue: ").concat(t)),hO[e]&&hO[e](t),this.parameters.set(e.toLowerCase(),t),!0}catch(jN){return this.logger.error(fO,"setParameter occur error: ".concat(jN)),!1}}getParameter(e){try{return e&&this.parameters.has(e.toLowerCase())?this.parameters.get(e.toLowerCase()):null}catch(jN){return this.logger.error(fO,"getParameter occur error: ".concat(jN)),null}}};let mO=function(e){return e.TRACK_TYPE_AUDIO="audio",e.TRACK_TYPE_VIDEO="video",e.TYPE_APPLICATION="application",e}({}),gO=function(e){return e.STREAM_TYPE_MAIN="main",e.STREAM_TYPE_AUX="aux",e}({}),_O=function(e){return e[e.USER_SUBSCRIBE_AUDIOPOLICY=0]="USER_SUBSCRIBE_AUDIOPOLICY",e[e.TOPN_AUDIOPOLICY=1]="TOPN_AUDIOPOLICY",e}({}),SO=function(e){return e[e.USER_SUBSCRIBE_AUDIOPOLICY=2]="USER_SUBSCRIBE_AUDIOPOLICY",e[e.TOPN_AUDIOPOLICY=3]="TOPN_AUDIOPOLICY",e}({}),vO=function(e){return e[e.COMMON_SFU_RESOURCE=0]="COMMON_SFU_RESOURCE",e[e.COMPANY_SFU_RESOURCE=1]="COMPANY_SFU_RESOURCE",e[e.MPC_SFU_RESOURCE=2]="MPC_SFU_RESOURCE",e[e.LLL_SFU_RESOURCE=3]="LLL_SFU_RESOURCE",e}({});let yO=function(e){return e[e.NETWORK_QUALITY_UNKNOW=0]="NETWORK_QUALITY_UNKNOW",e[e.NETWORK_QUALITY_GREAT=1]="NETWORK_QUALITY_GREAT",e[e.NETWORK_QUALITY_GOOD=2]="NETWORK_QUALITY_GOOD",e[e.NETWORK_QUALITY_DEFECTS=3]="NETWORK_QUALITY_DEFECTS",e[e.NETWORK_QUALITY_WEAK=4]="NETWORK_QUALITY_WEAK",e[e.NETWORK_QUALITY_BAD=5]="NETWORK_QUALITY_BAD",e[e.NETWORK_QUALITY_DISCONNECT=6]="NETWORK_QUALITY_DISCONNECT",e}({}),IO=function(e){return e[e.NotJoin=0]="NotJoin",e[e.Joined=1]="Joined",e[e.Rejoining=2]="Rejoining",e}({}),TO=function(e){return e[e.normal=0]="normal",e[e.resolutionChange=1]="resolutionChange",e[e.remoteRejoinCache=2]="remoteRejoinCache",e[e.localRejoin=3]="localRejoin",e}({});const RO={"90p-":{width:120,height:90},"90p":{width:160,height:90},"120p":{width:160,height:120},"180p-":{width:240,height:180},"180p":{width:320,height:180},"240p":{width:320,height:240},"270p":{width:480,height:270},"300p":{width:400,height:300},"360p-":{width:480,height:360},"360p":{width:640,height:360},"450p":{width:800,height:450},"480p":{width:640,height:480},"540p":{width:960,height:540},"630p":{width:1120,height:630},"720p-":{width:960,height:720},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}};class EO{static getResolution(e,t){const r=Math.min(e,t);return r<180?"LD":r<360?"SD":r<720?"HD":"FHD"}static getResolutionType(e,t){return Object.keys(RO).find((r=>RO[r].width===e&&RO[r].height===t))}}class bO{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;this.elements=new Array(e+1),this.front=0,this.tail=0,this._size=0}getCapacity(){return this.elements.length-1}isEmpty(){return this.front===this.tail}size(){return this._size}push(e){this._size===this.getCapacity()&&this.dequeue(),this.elements[this.tail]=e,this.tail=(this.tail+1)%this.elements.length,this._size++}dequeue(){if(this.isEmpty())throw new Error("Cannot dequeue from an empty queue.");const e=this.elements[this.front];return this.elements[this.front]=null,this.front=(this.front+1)%this.elements.length,this._size--,e}getFront(){return this.isEmpty()?null:this.elements[this.front]}getTail(){if(this.isEmpty())return null;const e=0===this.tail?this.elements.length-1:this.tail-1;return this.elements[e]}getElement(e){return e<0||e>=this.size()?null:this.elements[(this.front+e)%this.elements.length]}}const CO=new class{constructor(){i(this,"isFireFox",Cw.isFirefox()),this.reportSymbol=Symbol("RTCInterval_".concat(XR.getCurrentTimestamp())),this.mapInterval=new bO}getSymbol(){return this.reportSymbol}reset(){delete this.mapInterval,this.mapInterval=new bO,clearTimeout(this.gatherTimer),this.gatherTimer=null}addConnection(e,t){this.connectionsManagers||(this.connectionsManagers=new Map),this.connectionsManagers.set(e,t),this.execMyInterval((async()=>{await this.execInterval()}),100)}checkIsMediaStatsType(e){return["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp"].includes(e.type)}checkCandidatePair(e){return"candidate-pair"===e.type.toString()&&(!0===e.selected||!0===e["nominated "]||"succeeded"===e.state)}async getStatsData(e,t){const r=await(null==t?void 0:t.getStats());r&&r.forEach(((t,r)=>{this.checkIsMediaStatsType(t)?e.set(t.type+"-"+t.kind+"_"+t.ssrc,t):this.checkCandidatePair(t)?(t.currentRoundTripTime=t.currentRoundTripTime||Math.abs(t.lastPacketReceivedTimestamp-t.lastPacketSentTimestamp),e.set(t.type,t)):"track"===t.type.toString()&&e.set(r,t)}))}async getData(e,t,r){const i=e.getConnection(r);await this.getStatsData(t,i)}async execInterval(){const e=new Map;for(const t of this.connectionsManagers.keys()){const r=new Map,i=new Map,n=new Map,o=[];o.push(this.getData(this.connectionsManagers.get(t),i,gO.STREAM_TYPE_MAIN)),o.push(this.getData(this.connectionsManagers.get(t),n,gO.STREAM_TYPE_AUX)),await Promise.all(o),r.set(gO.STREAM_TYPE_MAIN,i),r.set(gO.STREAM_TYPE_AUX,n),e.set(t,r)}this.mapInterval.push(e)}getLatestRemoteInboundStats(e,t,r){var i,n;const o=null===(i=this.mapInterval.getTail())||void 0===i||null===(n=i.get(e))||void 0===n?void 0:n.get(t);if(this.isFireFox){const t=r.split("_"),i=parseInt(t[1]),n=this.connectionsManagers.get(e).getMappingSsrcs(i),s=t[0].concat("_").concat(n).toString();return o&&o.get(s)}return o&&o.get(r)?o.get(r):null}getLatestStatsByTrackId(e,t,r){var i,n;const o=null===(i=this.mapInterval.getTail())||void 0===i||null===(n=i.get(e))||void 0===n?void 0:n.get(t);return o&&o.get(r)?o.get(r):null}getLatestReport(e,t){var r,i;return null===(r=this.mapInterval.getTail())||void 0===r||null===(i=r.get(e))||void 0===i?void 0:i.get(t)}getLatestStats(e,t,r){const i=this.getLatestReport(e,t);return this.getStatsBySsrcLabel(i,r,e)}getElementStats(e,t,r,i){var n,o;const s=null===(n=this.mapInterval.getElement(i))||void 0===n||null===(o=n.get(e))||void 0===o?void 0:o.get(t);return this.getStatsBySsrcLabel(s,r,e)}getStatsBySsrcLabel(e,t,r){if(!e)return null;if(this.isFireFox){const i=t.split("_"),n=parseInt(i[1]),o=this.connectionsManagers.get(r).getMappingSsrcs(n),s=i[0].concat("_").concat(o).toString();return e.get(s)}return e.get(t)}getLatestValue(e,t,r,i){const n=this.getLatestStats(e,t,r);return n?n[i]:null}getAllNumber(e,t,r,i){const n=this.mapInterval.size(),o=new Array(n);for(let s=0;sn&&(c+=a),a=0);return a>n&&(c+=a),c}execMyInterval(e,t){const r=()=>{this.gatherTimer=setTimeout((()=>{e(),r()}),t)};e(),r()}};class AO{constructor(e){i(this,"videoFreezeKey",Cw.isFirefox()?"packetsReceived":"framesReceived"),i(this,"mediaStatInfo",[]),i(this,"mediaStatDebugInfo",[]),i(this,"mediaStatSumInfo",[]),i(this,"mediaStatSumDebugInfo",[]),i(this,"ACSAddr",""),i(this,"SFUAddr",""),i(this,"lastSenderInfo",new Map),i(this,"lastSenderDebugInfo",new Map),i(this,"encryUserId",new Map),i(this,"remoteStreamInfo",[]),i(this,"audioPolicy",_O.USER_SUBSCRIBE_AUDIOPOLICY),i(this,"LocalStreamInfo",new Map),i(this,"auxsStreamInfo",new Map),i(this,"audioReceiveInfo",{audioReceivePackets:new Map,audioReceivePacketsLost:new Map,audioReceiveBytes:new Map}),i(this,"videoReceiveInfo",{videoReceivePackets:new Map,videoReceivePacketsLost:new Map,videoReceiveBytes:new Map,videoReceiveFrame:new Map}),i(this,"audioReceiveDebugInfo",{audioReceivePackets:new Map,audioReceivePacketsLost:new Map,audioReceiveBytes:new Map}),i(this,"videoReceiveDebugInfo",{videoReceivePackets:new Map,videoReceivePacketsLost:new Map,videoReceiveBytes:new Map,videoReceiveFrame:new Map}),i(this,"inBoundAudioSsrcInfos",[]),i(this,"audioPolicyLastCycle",_O.USER_SUBSCRIBE_AUDIOPOLICY),i(this,"audioStreamReceiverMap",new Map),i(this,"ssrcChangeCount",0),i(this,"audioStreamInfos",[]),i(this,"audioCount",0),i(this,"audioStreamAllInfos",[]),i(this,"audioAllCount",0),i(this,"audioStreamTop3Count",0),i(this,"module_","MediaStats"),i(this,"tempStat",{bytesSent:0,bytesReceived:0,sendBitrate:0,recvBitrate:0,rtt:0,upPktsLostRate:0,downPktsLostRate:0}),i(this,"stat",{bytesSent:0,bytesReceived:0,sendBitrate:0,recvBitrate:0,rtt:0,upPktsLostRate:0,downPktsLostRate:0}),i(this,"audioLevelInfo",{localAudio:new Map,remoteAudio:new Map,top3Audio:new Map}),i(this,"remoteUserMuteStatus",new Map),this.logger=e}setEncryInfo(e,t){this.encryUserId.set(e,t)}getEncryInfo(e){return this.encryUserId.get(e)}clearEncryUserId(){this.encryUserId.clear()}setRemoteUserManager(e){this.remoteUserManager=e}setStartSsrc(e){this.startSsrc=e}updateAudioLevel(e){if("local"===e.type){if(!this.audioLevelInfo.localAudio.get("local")){const e=[];this.audioLevelInfo.localAudio.set("local",e)}this.audioLevelInfo.localAudio.get("local").push(e.level)}else if("remoteTop3"===e.type){if(!this.audioLevelInfo.top3Audio.get("".concat(null==e?void 0:e.ssrc))){const t=[];this.audioLevelInfo.top3Audio.set("".concat(null==e?void 0:e.ssrc),t)}this.audioLevelInfo.top3Audio.get("".concat(null==e?void 0:e.ssrc)).push(e.level)}else{if(!this.audioLevelInfo.remoteAudio.get("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId))){const t=[];this.audioLevelInfo.remoteAudio.set("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId),t)}this.audioLevelInfo.remoteAudio.get("".concat(null==e?void 0:e.ssrc,"_").concat(null==e?void 0:e.userId)).push(e.level)}}getAudioLevel(e,t,r){let i=0,n=0;return"local"===e&&this.audioLevelInfo.localAudio.get("local")?(this.audioLevelInfo.localAudio.get("local").forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.localAudio.clear()):"remoteTop3"===e&&this.audioLevelInfo.top3Audio.get("".concat(t))?(this.audioLevelInfo.top3Audio.get("".concat(t)).forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.top3Audio.clear()):"remote"===e&&this.audioLevelInfo.remoteAudio.get("".concat(t,"_").concat(r))&&(this.audioLevelInfo.remoteAudio.get("".concat(t,"_").concat(r)).forEach((e=>{i+=e||0,n++})),this.audioLevelInfo.remoteAudio.clear()),0===n?0:Math.ceil(i/n)}setConnectionsManager(e){this.logger.info(this.module_,"setConnectionsManager"),this.connectionsManager=e}setSubscribeInfo(e){var t,r,i,n;if(!e)return;const o=this.remoteStreamInfo.find((t=>t.userId===e.userId));if(!o)return this.clearRemoteStreamInfoCache(e),void this.remoteStreamInfo.push(e);(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0&&e.mainStream.tracks.forEach((t=>{o.mainStream.tracks.find((e=>e.trackId===t.trackId))||(this.doClearRemoteStreamInfoCache(e,e.userId,t.cssrc),o.mainStream.tracks.push(t))})),(null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n?void 0:n.length)>0&&e.auxStream.tracks.forEach((t=>{o.auxStream.tracks.find((e=>e.trackId===t.trackId))||(this.doClearRemoteStreamInfoCache(e,e.userId,t.cssrc),o.auxStream.tracks.push(t))}))}doClearRemoteStreamInfoCache(e,t,r){let i=null;if(e.mainStream.tracks.forEach((e=>{e.cssrc===r&&(i=e.type)})),e.auxStream.tracks.forEach((e=>{e.cssrc===r&&(i=e.type)})),i===mO.TRACK_TYPE_AUDIO){const e="".concat(r,"-").concat(t);this.audioReceiveInfo.audioReceivePackets.delete(e),this.audioReceiveInfo.audioReceivePacketsLost.delete(e),this.audioReceiveInfo.audioReceiveBytes.delete(e)}else if(i===mO.TRACK_TYPE_VIDEO){const e="".concat(r,"-").concat(t);this.videoReceiveInfo.videoReceivePackets.delete(e),this.videoReceiveInfo.videoReceivePacketsLost.delete(e),this.videoReceiveInfo.videoReceiveBytes.delete(e),this.videoReceiveInfo.videoReceiveFrame.delete(e)}}clearRemoteStreamInfoCache(e){this.remoteStreamInfo.filter((t=>t.userId===e.userId)).forEach((t=>{this.clearRemoteStreamInfoCache4Stream(e,t.mainStream),this.clearRemoteStreamInfoCache4Stream(e,t.auxStream)}))}clearRemoteStreamInfoCache4Stream(e,t){t.tracks.forEach((t=>{const r=t.trackId,i=t.cssrc,n=e.userId;e.mainStream.tracks.forEach((t=>{t.cssrc===i&&t.trackId!==r&&this.doClearRemoteStreamInfoCache(e,n,i)}))}))}clearLocalStreamInfoCache(e){e&&this.LocalStreamInfo.forEach((t=>{e.ssrc===t.ssrc&&e.uid===t.uid&&e.streamId!==t.streamId&&this.lastSenderInfo.delete("".concat(e.ssrc,"-").concat(e.uid))}))}clearAuxsStreamInfoCache(e){e&&this.auxsStreamInfo.forEach((t=>{e.ssrc===t.ssrc&&e.uid===t.uid&&e.streamId!==t.streamId&&this.lastSenderInfo.delete("".concat(e.ssrc,"-").concat(e.uid))}))}setLocalMainStreamInfo(e,t){return!(!t||0===t.length)&&(this.LocalStreamInfo.clear(),t.forEach((t=>{const r={uid:e,streamId:"",ssrc:t.ssrc,type:t.type};t.type===mO.TRACK_TYPE_AUDIO?r.streamId=t.upstream.streamUid.toString():(r.streamId=t.upstream.streamUid.toString(),r.width=t.upstream.width,r.height=t.upstream.height,r.frame=t.upstream.fps),this.clearLocalStreamInfoCache(r),this.LocalStreamInfo.set(t.resolutionId,r)})),!0)}setLocalAuxsStreamInfo(e,t){if(!t)return!1;const r=Array.from(t.localTrackPublishInfos.values());return!!r&&(this.auxsStreamInfo.clear(),r.forEach((r=>{const i={uid:e,streamId:r.upstream.streamUid.toString(),ssrc:r.ssrc,type:r.type};r.type===mO.TRACK_TYPE_VIDEO&&(i.publishInfo={stream:t.localStream}),this.clearAuxsStreamInfoCache(i),this.auxsStreamInfo.set(r.resolutionId,i)})),!0)}deleteSubscribeInfo(e,t,r){if(r||t){if(t){const i=this.remoteStreamInfo.find((t=>t.userId===e));if(!i)return;const n=t===gO.STREAM_TYPE_MAIN?i.mainStream:i.auxStream;n.tracks=r?n.tracks.filter((e=>e.trackId!==r)):null}}else this.remoteStreamInfo=this.remoteStreamInfo.filter((t=>t.userId!==e))}setAudioPolicy(e){this.audioPolicyLastCycle=this.audioPolicy,this.audioPolicy=e,this.setAudioStreamInfo()}setSFUAddr(e){this.SFUAddr=e}setACSAddr(e){this.ACSAddr=e}leaveRoom(){this.mediaStatInfo=[]}getAudioPolicy(){return this.audioPolicy}getTransportMediaStats(){return this.stat}getMediaStatInfo(){const e=this.mediaStatInfo;return this.mediaStatInfo=[],e}getMediaStatSum(){const e=this.mediaStatSumInfo;return this.mediaStatSumInfo=[],e}getInBoundAudioSsrc(){const e=this.inBoundAudioSsrcInfos;return this.inBoundAudioSsrcInfos=[],e}async dealStats(){this.connectionsManager.isConnectionsExist()?(this.getAudioStreamInfo(),await this.getSenderInfo(!1),await this.getReceiverInfo(!1),this.stat.bytesSent+=this.tempStat.bytesSent,this.stat.bytesReceived+=this.tempStat.bytesReceived,this.stat.sendBitrate=this.tempStat.sendBitrate,this.stat.recvBitrate=this.tempStat.recvBitrate,this.clearTempStats()):this.logger.debug(this.module_,"peerConnection is undefined")}clearTempStats(){this.tempStat.bytesSent=0,this.tempStat.bytesReceived=0,this.tempStat.sendBitrate=0,this.tempStat.recvBitrate=0}clearMediaStatBytes(){this.stat.bytesSent=0,this.stat.bytesReceived=0}cleanAudioStreamInfos(){this.audioCount=this.audioStreamInfos.length,this.audioAllCount=this.audioStreamAllInfos.length,this.audioStreamInfos=[],this.audioStreamAllInfos=[]}updateAudioStreamInfos(e,t){if("add"===t){let t=0;this.remoteStreamInfo.forEach((r=>{if(e===r.userId){const e=r.mainStream.tracks.filter((e=>e.streamType===gO.STREAM_TYPE_MAIN&&e.type===mO.TRACK_TYPE_AUDIO));t=e.length>0?e[0].cssrc:0}}));const r={userid:e,audioSsrc:t};this.audioStreamInfos=this.audioStreamInfos.filter((r=>r.userid!=e||r.audioSsrc!=t)),this.audioStreamAllInfos=this.audioStreamAllInfos.filter((r=>r.userid!=e||r.audioSsrc!=t)),this.audioStreamInfos.push(r),this.audioStreamAllInfos.push(r)}"delete"!==t&&"removed"!==t||(this.audioStreamInfos=this.audioStreamInfos.filter((t=>t.userid!==e)),this.audioStreamAllInfos=this.audioStreamAllInfos.filter((t=>t.userid!==e))),this.audioPolicy!==_O.USER_SUBSCRIBE_AUDIOPOLICY&&this.audioCount===this.audioStreamInfos.length||this.ssrcChangeCount++,this.audioPolicy!==_O.TOPN_AUDIOPOLICY&&this.audioAllCount===this.audioStreamAllInfos.length||this.ssrcChangeCount++}updateAudioStreamTop3(e){this.audioStreamTop3CountTimer&&clearTimeout(this.audioStreamTop3CountTimer),this.audioStreamTop3CountTimer=setTimeout((()=>{this.audioStreamTop3Count=0}),4e3),this.audioStreamTop3Count=e}checkAudioStreamInfosIsExist(e,t){return 0!==this.audioStreamInfos.filter((r=>r.userid===e&&r.audioSsrc===t)).length}setAudioStreamInfo(){this.audioPolicy!==this.audioPolicyLastCycle&&(this.ssrcChangeCount=1,this.audioStreamReceiverMap.clear(),this.audioStreamTop3Count=0,this.audioReceiveInfo.audioReceiveBytes.clear(),this.audioReceiveInfo.audioReceivePackets.clear(),this.audioReceiveInfo.audioReceivePacketsLost.clear())}async getAudioStreamInfo(){this.audioPolicy===_O.TOPN_AUDIOPOLICY?await this.buildAudioStreamInfo3():this.audioPolicy===_O.USER_SUBSCRIBE_AUDIOPOLICY?await this.buildAudioStreamInfo2():this.logger.debug(this.module_,"mode 1 not uesed")}async buildAudioStreamInfo3(){const e=[],t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_STAT,access_addr:this.ACSAddr,sfu_addr:this.SFUAddr,audio_policy:this.audioPolicy,topn:3,audios_change_cnt:0,audios:e,no_stream_cnt:0};for(let n=0;n<3;n++){var r;const i=this.startSsrc+n,o="".concat(hC,"_").concat(i),s=CO.getLatestStats(null===(r=this.connectionsManager)||void 0===r?void 0:r.getConnectionId(),gO.STREAM_TYPE_MAIN,o);if(s){const r=this.connectionsManager.calcChangedStatistic(s.id,s.packetsReceived||0,["packetsReceived"])||s.packetsReceived,n=this.audioStreamReceiverMap.get(i)||0;let o=!0;0===r?o=!1:void 0===n?o=!0:r===n&&(o=!1),e.push({ssrc:i,userid:"",packet_cnt:r-n}),this.audioStreamReceiverMap.set(i,r),o||t.no_stream_cnt++}}const i=this.audioAllCount<3?this.audioAllCount:3;if(i<3){const e=t.no_stream_cnt-(3-i);t.no_stream_cnt=e<0?0:e}t.audios_change_cnt=this.ssrcChangeCount,this.inBoundAudioSsrcInfos.push(t)}async buildAudioStreamInfo2(){const e=[],t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_STAT,access_addr:this.ACSAddr,sfu_addr:this.SFUAddr,audio_policy:this.audioPolicy,topn:17,audios_change_cnt:0,audios:e,no_stream_cnt:0};this.remoteStreamInfo.every((r=>{var i;if(-1===this.audioStreamInfos.findIndex((e=>e.userid===r.userId)))return!0;const n=Array.from(r.mainStream.tracks.values()).find((e=>e.type===mO.TRACK_TYPE_AUDIO)),o="".concat(hC,"_").concat(null==n?void 0:n.cssrc),s=CO.getLatestStats(null===(i=this.connectionsManager)||void 0===i?void 0:i.getConnectionId(),gO.STREAM_TYPE_MAIN,o);if(r&&n&&s){const i=r.userId,o=this.connectionsManager.calcChangedStatistic(s.id,s.packetsReceived||0,["packetsReceived"])||s.packetsReceived,a=this.audioStreamReceiverMap.get(n.cssrc)||0;let c=!0;0===o?c=!1:void 0===a?c=!0:o===a&&(c=!1);const u=this.getEncryInfo(r.userId)||XR.secretString(r.userId)||"";e.push({ssrc:n.cssrc,userid:u,packet_cnt:o-a}),this.audioStreamReceiverMap.set(n.cssrc,o),!c&&this.checkAudioStreamInfosIsExist(i,n.cssrc)&&t.no_stream_cnt++}return!0})),t.audios_change_cnt=this.ssrcChangeCount,e.length>0&&this.inBoundAudioSsrcInfos.push(t)}async getVideoReceiverFrameDecodedMap(){const e=new Map;return await this.buildFrameDecodedMap(gO.STREAM_TYPE_MAIN,e),await this.buildFrameDecodedMap(gO.STREAM_TYPE_AUX,e),e}async buildFrameDecodedMap(e,t){const r=e===gO.STREAM_TYPE_AUX,i=this.connectionsManager.getReceivers(r?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN);for(let n=0;n{const n={};(r?i.auxStream.tracks:i.mainStream.tracks).forEach((o=>{var s;const a=CO.getLatestStats(null===(s=this.connectionsManager)||void 0===s?void 0:s.getConnectionId(),e,"".concat(fC,"_").concat(o.cssrc));if(a){n.userId=i.userId,n.isAux=r,n.decodedFrame=this.connectionsManager.calcChangedStatistic(a.id,a.framesDecoded||0,["framesDecoded"]);const e="".concat(i.userId,",").concat(r?"1":"0");t.get(e)||t.set(e,n)}}))}))}}async getReceiverInfo(e){const t={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO_SUM,real_band_width:0,bytes:0,pkt_loss:0},r={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_VIDEO_SUM,real_band_width:0,tmmbr:0,video_tmmbr:0,req_band_width:0,pkt_loss:0,jitter:0,frame_rate:0,first_frame_count:0,bytes:0},i={isAudio:!1,isVideo:!1};await this.buildReceiverInfo(gO.STREAM_TYPE_MAIN,t,r,i,e),await this.buildReceiverInfo(gO.STREAM_TYPE_AUX,t,r,i,e),i.isAudio&&(e?this.mediaStatSumDebugInfo.push(t):this.mediaStatSumInfo.push(t)),i.isVideo&&(e?this.mediaStatSumDebugInfo.push(r):this.mediaStatSumInfo.push(r))}async buildReceiverInfo(e,t,r,i,n){const o=e===gO.STREAM_TYPE_AUX,s={timestamp:XR.getCurrentTimestamp(),event:ZC.QoS_DOWN_STREAM_AUDIO,streams:[]},a={timestamp:XR.getCurrentTimestamp(),event:o?ZC.QoS_AUX_DOWN_STREAM_VIDEO:ZC.QoS_DOWN_STREAM_VIDEO,qos_estimate:3,streams:[]};o||this.buildAudioReceiverInfo(s,t,n),this.buildVideoReceiverInfo(e,a,r,n),0!==a.streams.length&&(n?this.mediaStatDebugInfo.push(a):this.mediaStatInfo.push(a),i.isVideo=!0),0!==s.streams.length&&(n?this.mediaStatDebugInfo.push(s):this.mediaStatInfo.push(s),i.isAudio=!0)}checkMuteStatusIsChange(e){const t=this.remoteUserManager.checkSsrcIsMute(e),r=this.remoteUserMuteStatus.get(e),i=!t&&t===r;return this.remoteUserMuteStatus.set(e,t),i}buildAudioReceiverInfo(e,t,r){let i=null,n=null,o=null,s=0;if(r?(i=this.audioReceiveDebugInfo.audioReceivePackets,n=this.audioReceiveDebugInfo.audioReceivePacketsLost,o=this.audioReceiveDebugInfo.audioReceiveBytes,s=this.rtcStatsInteval):(i=this.audioReceiveInfo.audioReceivePackets,n=this.audioReceiveInfo.audioReceivePacketsLost,o=this.audioReceiveInfo.audioReceiveBytes,s=5),this.audioPolicy===_O.TOPN_AUDIOPOLICY){for(let u=0;u<3;u++){var a;const d={ssrc_uid:"",stream_uid:"",sfu_addr:"",dst_rcv_vel:0,dst_rcv_nel:0,bit_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,lost_pkt_cnt:0,srtp_decode_err:0,max_cont_lost_pkts:0,mos:0,jb_depth:0,play_err:0,play_total_time:5e3,freeze_loss_time:0,freeze_time:0,jitter90:0,jitter95:0,jitter100:0,tsm_count:0,ts_exp_cnt:0,ssrc_change_cnt:0,audio_pkt_error:0,audio_decode_error:0,dst_burst_pkt_lost_cnt:0,dst_burst_cnt:0,dst_burst_pkt_lost_rate:0,dst_audio_jb_discard_lost_rate:0,net_loss:0,rtp_loss:0,dst_mean_lost_rate:0,buffer_max_length:0,buffer_mean_length:0,net_ate_max_delay:0,net_ate_cur_delay:0,jb_max_num_delay:0,jb_cur_num_delay:0,pkt_recv_max_interval:0,pkt_recv_mean_interval:0,ui_sample_rate:0,ui_channels:0,en_codec_type:0,ui_total_pkt_loss:0,ui_buffer_total_length:0,ui_buffer_cal_cnt:0,ui_rec_pkt_cnt:0,i_channel_id:0,ui_dst_inc_bytes:0,ui_recv_redn_rate:0,ui_plc_count:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},l=this.startSsrc+u,h="".concat(hC,"_").concat(l),f=CO.getLatestStats(null===(a=this.connectionsManager)||void 0===a?void 0:a.getConnectionId(),gO.STREAM_TYPE_MAIN,h);if(f){d.ssrc_uid="".concat(l,"-").concat(l),d.stream_uid="STREAMUUID-".concat(l),d.sfu_addr=this.SFUAddr,this.connectionsManager.calcChangedStatistic(f.id,f,["bytesReceived","packetsReceived","packetsLost"]);const e=f.bytesReceived||0;o.get(l)||o.set(l,0),d.bytes=en.get(l)?a-n.get(l):0;d.lost_pkt_cnt=u;const p=t{var o;const s={ssrc_uid:"",stream_uid:"",sfu_addr:"",dst_rcv_vel:0,dst_rcv_nel:0,bit_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,lost_pkt_cnt:0,srtp_decode_err:0,max_cont_lost_pkts:0,mos:0,jb_depth:0,play_err:0,play_total_time:5e3,freeze_loss_time:0,freeze_time:0,jitter90:0,jitter95:0,jitter100:0,tsm_count:0,ts_exp_cnt:0,ssrc_change_cnt:0,audio_pkt_error:0,audio_decode_error:0,dst_burst_pkt_lost_cnt:0,dst_burst_cnt:0,dst_burst_pkt_lost_rate:0,dst_audio_jb_discard_lost_rate:0,net_loss:0,rtp_loss:0,dst_mean_lost_rate:0,buffer_max_length:0,buffer_mean_length:0,net_ate_max_delay:0,net_ate_cur_delay:0,jb_max_num_delay:0,jb_cur_num_delay:0,pkt_recv_max_interval:0,pkt_recv_mean_interval:0,ui_sample_rate:0,ui_channels:0,en_codec_type:0,ui_total_pkt_loss:0,ui_buffer_total_length:0,ui_buffer_cal_cnt:0,ui_rec_pkt_cnt:0,i_channel_id:0,ui_dst_inc_bytes:0,ui_recv_redn_rate:0,ui_plc_count:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},a=Array.from(n.mainStream.tracks.values()).find((e=>e.type===mO.TRACK_TYPE_AUDIO&&e.state===TO.normal)),c="".concat(hC,"_").concat(null==a?void 0:a.cssrc),u=CO.getLatestStats(null===(o=this.connectionsManager)||void 0===o?void 0:o.getConnectionId(),gO.STREAM_TYPE_MAIN,c);if(n&&a&&u){const t=this.getEncryInfo(n.userId)||XR.secretString(n.userId),r="".concat(a.cssrc,"-").concat(t);s.ssrc_uid=r,s.stream_uid="".concat(a.trackId)||"STREAMUUID-".concat(a.cssrc),s.sfu_addr=this.SFUAddr,this.connectionsManager.calcChangedStatistic(u.id,u,["bytesReceived","packetsReceived","packetsLost"]);const o=u.bytesReceived||0;e.audioReceiveBytes.get(r)||e.audioReceiveBytes.set(r,0),s.bytes=oe.audioReceivePacketsLost.get(r)?h-e.audioReceivePacketsLost.get(r):0;s.lost_pkt_cnt=f;const p=l{(e===gO.STREAM_TYPE_MAIN?d.mainStream.tracks.filter((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.state===TO.normal)):d.auxStream.tracks.filter((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.state===TO.normal))).forEach((l=>{var h,f;const p={ssrc_uid:"",stream_uid:"",sfu_addr:"",expect_pic_w:0,expect_pic_h:0,image_width:0,image_height:0,roc:0,buffered:0,bit_rate:0,frame_rate:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,jb_depth:0,fir_req_cnt:0,parse_srtp_fail:0,fir_frame_cnt:0,freeze_200ms_cnt:0,freeze_600ms_cnt:0,freeze_1000ms_cnt:0,freeze_200ms_time:0,freeze_600ms_time:0,freeze_1000ms_time:0,dec_key_frame_cnt:0,dec_key_frame_size:0,max_cont_lost_pkts:0,freeze_cnt:0,act_dec_runtime:5e3,ui_first_rcv_seq:0,ui_max_decode_delay:0,ui_min_decode_delay:0,ui_mean_decode_delay:0,ui_current_decode_delay:0,ui_max_channel_decode_delay:0,ui_min_channel_decode_delay:0,ui_mean_channel_decode_delay:0,ui_current_channel_decode_delay:0,ui_abnormal_pkt_count:0,ui_codec_pt_error:0,ui_no_dec_data_cnt:0,jb_discard_bytes:0,net_lost_pkt_counts:0,rcv_frame_counts:0,dec_bytes_out:0,rcv_red_bytes:0,dec_delay_over_time_cnt:0,channel_decode_over_time_cnt:0,dec_non_key_frame_size:0,dec_non_key_frame_cnt:0,us_loss_frame_rate:0,ui_pkt_rate:0,us_residual_pkt_loss:0,ul_decoder_start_time:0,us_mean_pkt_loss:0,ui_mean_rtt:0,e_dec_protocol:0,ui_distribute_tmmbr:0,frame_fail_cnt:0,advanced_frame_count:0,base_frame_count:0,before_postprocess_frames_rate:0,after_postprocess_frames_rate:0,red_rate:0,recover_rate:0,jb_listpacket_num:0,not_recv_pkt_cnt:0,not_recv_pkt_total_time:0,nack_request_cnt:0,send_key_request_cnt:0,jb_jitter:0,recv_frame_rate:0,recv_base_layer_frame_cnt:0,recv_mid_layer_frame_cnt:0,recv_out_layer_frame_cnt:0,jb_total_frame_cnt:0,jb_listframe_num:0,output_total_freezetime:0,output_freeze_cnt:0,ref_frame_error_cnt:0,force_out4_key_cnt:0,force_out4_struct_cnt:0,current_output_diftime:0,current_complete_type:0,jb_base_layer_frame_num:0,jb_mid_layer_frame_num:0,jb_out_layer_frame_num:0,freeze_400ms_cnt:0,freeze_400ms_time:0,freeze_200ms_rate:0,freeze_400ms_rate:0,freeze_600ms_rate:0,freeze_1000ms_rate:0,freeze_loss_time:0,first_frame_cnt:0,p_frame_cnt:0,lost_pkt_cnt:0,play_err:0,bad_pkt_cnt:0,empty_pkt_cnt:0,buf_drop_pkt_cnt:0},m="".concat(fC,"_").concat(l.cssrc),g=CO.getLatestStats(null===(h=this.connectionsManager)||void 0===h?void 0:h.getConnectionId(),e,m);if(g){const t=this.getEncryInfo(d.userId)||XR.secretString(d.userId),r="".concat(l.cssrc,"-").concat(t);p.ssrc_uid=r,this.connectionsManager.calcChangedStatistic(g.id,g,["keyFramesDecoded","packetsReceived","packetsLost","bytesReceived","framesDecoded","freezeCount"]),this.buildCommonVideoRecvInfo(p,g,l),this.buildBitRateVideoRecvInfo(g,r,o,s,p);const h=XR.getValue(g.bytesReceived,0),f=a.get(r)||0;p.bytes=hc?s-c:0;n.real_lost_pkt_cnt=u;const d=oe.type!==mO.TRACK_TYPE_AUDIO)):Array.from(this.LocalStreamInfo.values());if(0===c.length)return;const u=c.find((e=>e.type===mO.TRACK_TYPE_AUDIO)),d=c.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)),l=n?this.rtcStatsInteval:5;this.buildAudioSenderInfo(u,a,n),a.ssrc_uid&&(t.real_band_width+=Math.round(a.bytes/(1024*l)*8),i.isAudio=!0,s.push(a)),null==d||d.forEach((t=>{const s={ssrc_uid:"",stream_uid:"",sfu_addr:"",expect_pic_w:0,expect_pic_h:0,expect_frame_rate:0,image_width:0,image_height:0,frame_rate:0,bit_rate:0,max_cont_loss:0,pkt_loss:0,rtt:0,jitter:0,bytes:0,pkts:0,roc:0,first_req_count:0,first_frame_count:0,frame_count:0,redn_rate:0,ui_first_send_seq:0,ui_no_ref_redundance_rate:0,ui_enc_max_bit_rate_set:0,ui_enc_min_bit_rate_set:0,ui_enc_current_bit_rate_set:0,ui_max_encode_delay:0,ui_min_encode_delay:0,ui_mean_encode_delay:0,ui_current_encode_delay:0,ui_buffer_data:0,ui_snd_fir_frame_key_count:0,ui_snd_fir_frame_arq_count:0,ui_snd_fir_frame_period_count:0,ui_max_channel_encode_delay:0,ui_min_channel_encode_delay:0,ui_mean_channel_encode_delay:0,ui_current_channel_encode_delay:0,ui_enc_frame_counts:0,ui_enc_bytes_out:0,ui_estimate_bitrate:0,ui_red_bytes_out:0,ui_nack_bytes_out:0,ui_enc_over_time_cnt:0,ui_enc_delay_over_time_cnt:0,ui_channel_encode_over_time_cnt:0,ui_before_pre_process_frm_cnt:0,ui_after_pre_process_frm_cnt:0,repeat_red_pkt_count:0,usable_bitrate:0,available_enc_bitrate:0,send_pkt_hungry_cnt:0,send_buffer_frm_cnt:0,advanced_frame_cnt:0,base_frame_cnt:0,avg_pre_process_time_in_period:0,max_pre_process_time:0,before_encode_lost_frm_cnt:0,us_sent_mean_lost_rate:0,ui_mean_r_t_t:0,ui_cumulative_lost:0,ui_extended_max_seq_num:0,ui_pkt_rate:0,ui_send_bit_rate:0,f_key_redundance_rate:0,f_ref_redundance_rate:0,f_no_ref_redundance_rate:0,e_enc_protocol:0,before_encode_frames_rate:0,before_send_frames_rate:0,after_send_frames_rate:0,data_cache_bytes:0,input_frame_cnt:0,input_pacing_pkt_cnt:0,input_pacing_fec_pkt_cnt:0,input_pacing_arq_pkt_cnt:0,send_fec_pkt_cnt:0,send_arq_pkt_cnt:0,nack_not_rsp_for_not_find_cnt:0,nack_not_rsp_for_key_cnt:0,nack_not_rsp_for_rtt_cnt:0,nack_not_rsp_for_time_cnt:0,nack_not_rsp_for_bw_cnt:0,deliver_red_rate:0,output_frame_cnt:0,estimate_bit_rate:0,tmmbr:0,p_frame_count:0,key_frame_count:0,bad_pkt_cnt:0,qos_estimate:3};this.buildVideoSenderInfo(t,s,e,n),s.ssrc_uid&&(r.real_band_width+=Math.round(s.bytes/(1024*l)*8),i.isVideo=!0,o.push(s))}));const h=this.getConnectionRemb(e);if(r.video_tmmbr=h>0?Math.round(h/1024):0,r.tmmbr+=r.video_tmmbr,s.length>0){const e={timestamp:XR.getCurrentTimestamp()};e.event=ZC.QoS_UP_STREAM_AUDIO,e.streams=s,n?this.mediaStatDebugInfo.push(e):this.mediaStatInfo.push(e)}if(o.length>0){const t={timestamp:XR.getCurrentTimestamp()};t.event=e?ZC.QoS_AUX_UP_STREAM_VIDEO:ZC.QoS_UP_STREAM_VIDEO,t.streams=o,n?this.mediaStatDebugInfo.push(t):this.mediaStatInfo.push(t)}}buildAudioSenderInfo(e,t,r){var i,n;if(!e)return;const o=r?this.lastSenderDebugInfo:this.lastSenderInfo,s=r?this.rtcStatsInteval:5,a=o.get("".concat(e.ssrc,"-").concat(e.uid))||{audioSendPackets:0,audioSendPacketsLost:0,audioSendBytes:0,videoSendPackets:0,videoSendPacketsLost:0,videoSendBytes:0};let c="".concat(pC,"_").concat(e.ssrc),u=CO.getLatestStats(null===(i=this.connectionsManager)||void 0===i?void 0:i.getConnectionId(),gO.STREAM_TYPE_MAIN,c);if(u){const i=this.getEncryInfo(e.uid)||XR.secretString(e.uid);t.ssrc_uid="".concat(e.ssrc,"-").concat(i),t.stream_uid=e.streamId,t.sfu_addr=this.SFUAddr;const n=u.bytesSent||0;t.bytes=na.audioSendPacketsLost?e-a.audioSendPacketsLost:0,i=t.pkts;t.pkt_loss=i>0?Math.round(r/(i+r)*100):0,a.audioSendPacketsLost=e}o.set("".concat(e.ssrc,"-").concat(e.uid),a)}addExpectInfo(e,t){t.expect_pic_w=(null==e?void 0:e.width)||0,t.expect_pic_h=(null==e?void 0:e.height)||0,t.expect_frame_rate=(null==e?void 0:e.frame)||0}addRembInfo(e,t){const r=this.getConnectionRemb(e);t.usable_bitrate=r>0?Math.round(r/1024):0}getConnectionRemb(e){let t=0;return this.connectionsManager.isConnectionsExist()?(t+=e?this.getRemb(gO.STREAM_TYPE_AUX):this.getRemb(gO.STREAM_TYPE_MAIN),t):t}getRemb(e){let t=0;try{const r=CO.getLatestReport(this.connectionsManager.getConnectionId(),e);if(r){const e=r.get("candidate-pair");e&&Object.prototype.hasOwnProperty.call(e,"availableOutgoingBitrate")&&(t=e.availableOutgoingBitrate||0)}}catch(jN){this.logger.error(this.module_,"getRemb failed",jN)}return t}buildVideoSenderInfo(e,t,r,i){var n,o;if(!e)return;const s=i?this.lastSenderDebugInfo:this.lastSenderInfo,a=i?this.rtcStatsInteval:5,c=s.get("".concat(e.ssrc,"-").concat(e.uid))||{audioSendPackets:0,audioSendPacketsLost:0,audioSendBytes:0,videoSendPackets:0,videoSendPacketsLost:0,videoSendBytes:0};this.addExpectInfo(e,t),this.addRembInfo(r,t);const u="".concat(mC,"_").concat(e.ssrc),d=CO.getLatestStats(null===(n=this.connectionsManager)||void 0===n?void 0:n.getConnectionId(),r?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,u);if(d){const n=this.getEncryInfo(e.uid)||XR.secretString(e.uid);t.ssrc_uid="".concat(e.ssrc,"-").concat(n),t.stream_uid=e.streamId,t.sfu_addr=this.SFUAddr,AO.buildCommonVideoSendInfo(t,d,e,r);const o=XR.getValue(d.bytesSent,0);t.bytes=oc.videoSendPacketsLost?e-c.videoSendPacketsLost:0,i=t.pkts;t.pkt_loss=Math.round(r/(i+r)*100)}else t.pkt_loss=0;c.videoSendPacketsLost=e,t.rtt=Math.round(1e3*(h.roundTripTime||0))}s.set("".concat(e.ssrc,"-").concat(e.uid),c)}static buildCommonVideoSendInfo(e,t,r,i){if(i){var n;const t=null===(n=r.publishInfo)||void 0===n?void 0:n.stream;e.image_width=(null==t?void 0:t.getScreenWidth())||0,e.image_height=(null==t?void 0:t.getScreenHeight())||0,e.frame_rate=(null==t?void 0:t.getScreenFrameRate())||0}else e.image_width=(null==r?void 0:r.width)||0,e.image_height=(null==r?void 0:r.height)||0,e.frame_rate=(null==r?void 0:r.frame)||0;e.image_width=t.frameWidth||0,e.image_height=t.frameHeight||0,e.frame_rate=Math.round(t.framesPerSecond||0),e.first_frame_count=t.firCount||0,e.frame_count=t.framesSent||0}async buildRtcStatsDebugInfo(e){this.rtcStatsInteval=e;const t={mediaStatsDebugInfo:null,mediaStatsSumDebugInfo:null};return this.connectionsManager.isConnectionsExist()?(await this.getSenderInfo(!0),await this.getReceiverInfo(!0),t.mediaStatsDebugInfo=this.mediaStatDebugInfo,t.mediaStatsSumDebugInfo=this.mediaStatSumDebugInfo,this.mediaStatDebugInfo=[],this.mediaStatSumDebugInfo=[],t):(this.logger.debug(this.module_,"peerConnection is undefined"),t)}}class wO{constructor(e,t){i(this,"eventInfoMap",new Map),i(this,"reqInfoMap",new Map),i(this,"sfuInfo",{ipAddress:"",videoPort:0,audioPort:0,auxPort:0}),i(this,"deviceInfo",{audioOutputId:void 0,audioInputId:void 0,videoInputId:void 0}),i(this,"mediaOpsData",[]),i(this,"signalSendMsgs",[]),i(this,"signalReceiveMsgs",[]),i(this,"parentSpanIdMap",new Map),i(this,"spanIdMap",new Map),this.logger=e,this.mediaStats=new AO(e),this.module_="RTCStat",this.commInfo={},this.commInfo.instance_id=XR.getDeviceID(),t&&(this.commInfo.appid=t.appId,this.commInfo.domain=t.domain),this.commInfo.sdk_name="hwwebrtc",this.commInfo.corp="",this.commInfo.service_name="rtc",this.commInfo.operator="",this.commInfo.sdk_version="web-".concat(uA,"-").concat(dA),this.signalSendMsgs.push("BYE"),this.signalSendMsgs.push("PUSH_STREAM_RES_ALL"),this.signalSendMsgs.push("APPLY_PUSH_STREAM"),this.signalSendMsgs.push("AUDIO_POLICY"),this.signalSendMsgs.push("SWITCH_ROLE"),this.signalSendMsgs.push("CHANGE_STREAM_STATUS"),this.signalSendMsgs.push("APP_DATA"),this.signalSendMsgs.push("ENABLE_AUDIO"),this.signalSendMsgs.push("DISABLE_AUDIO"),this.signalSendMsgs.push("ENABLE_VIDEO"),this.signalSendMsgs.push("DISABLE_VIDEO"),this.signalSendMsgs.push("JOIN_ROOM"),this.signalSendMsgs.push("EXIT_ROOM"),this.signalSendMsgs.push("PING"),this.signalSendMsgs.push("PUSH_STREAM_RESULT"),this.signalSendMsgs.push("GET_ROOM_USERINFO"),this.signalSendMsgs.push("QUERY_PUBLISH"),this.signalSendMsgs.push("START_PUBLISH"),this.signalSendMsgs.push("STOP_PUSH_STREAM"),this.signalSendMsgs.push("STOP_PUBLISH"),this.signalSendMsgs.push("CANCEL_SUBS_STREAM"),this.signalSendMsgs.push("SUBS_STREAM"),this.signalSendMsgs.push("UPDATE_PUBLISH"),this.signalReceiveMsgs.push("WATCH_STREAM_NOTIFY")}static isStatiscEnable(){return"off"!==pO.getParameter(oO)}addCommInfo(e){return e.timestamp=XR.getCurrentTimestamp(),e.trace_id=this.commInfo.trace_id||"",e.instance_id=this.commInfo.instance_id,e.room_uid=this.commInfo.room_uid||"",e.domain=this.commInfo.domain||"",e.event_name=(null==e?void 0:e.event_name)||"",e.appid=this.commInfo.appid||"",e.corp=this.commInfo.corp||"",e.room_id=this.commInfo.room_id||"",e.user_id=this.getMediaStat().getEncryInfo(this.commInfo.user_id)||XR.secretString(this.commInfo.user_id)||"",e.sdk_version=this.commInfo.sdk_version||"",e.sdk_name=this.commInfo.sdk_name||"",e.service_name=this.commInfo.service_name||"",e.operator=this.commInfo.operator||"",e.net_type=XR.getNetworkType()||"",e.country="",e.province="",e.city="",e}setRemoteUserManager(e){this.remoteUserManager=e,this.mediaStats.setRemoteUserManager(e)}clearMediaStatBytes(){this.mediaStats.clearMediaStatBytes()}async collectReceiverDecodedFrameMap(){return this.mediaStats.getVideoReceiverFrameDecodedMap()}setLocalUserInfo(e){this.commInfo.room_id=e.roomId,this.commInfo.user_id=e.userId,this.user=e}setTraceInfo(e){this.commInfo.trace_id=e}setRoomUid(e){this.commInfo.room_uid=e}setSFUAddress(e){this.sfuInfo=e,e.ipAddress&&this.mediaStats.setSFUAddr(e.ipAddress)}getMediaStat(){return this.mediaStats}leaveRoom(){this.mediaCollectionTimer&&clearTimeout(this.mediaCollectionTimer),this.mediaStats.leaveRoom()}startMediaCollector(){clearTimeout(this.mediaCollectionTimer),this.mediaCollectionTimer=setTimeout((async()=>{try{await this.mediaStats.dealStats(),this.setMediaStatInfo(),this.setMediaStatSumInfo(),this.setInBoundAudioSsrcInfos(),nO.addRecords(this.mediaOpsData),this.mediaOpsData.length=0}catch(jN){this.logger.error(this.module_,"startMediaCollector failed ".concat(jN))}finally{this.startMediaCollector()}}),5e3)}reportAudioMuteInfo(e,t){const r=t?1:3;let i;i=1===e?zC.INPUT_AUDIO:zC.OUTPUT_AUDIO,this.reportSwitchDevicesInfo(i,this.deviceInfo.audioInputId,0,r)}reportVideoMuteInfo(e,t){const r=t?4:5;this.reportSwitchDevicesInfo(zC.INPUT_VIDEO,this.deviceInfo.videoInputId,0,r)}async setDeviceStatusInfo(){(async function(){return new Promise(((e,t)=>{navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices||t(new qc(Gc.RTC_ERR_CODE_NOT_SUPPORT_MEDIA_DEVICES)),navigator.mediaDevices.enumerateDevices().then((r=>{if(r&&0!==r.length){const t={};r.forEach((e=>{"default"!==e.deviceId&&"communications"!==e.deviceId&&(t[e.kind]=[...t[e.kind]||[],e])})),e(t)}else t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_DEVICES))})).catch((e=>{t(e)}))}))})().then((e=>{this.setSpeakerDeviceInfo(e.audiooutput||[]),this.setCameraDeviceInfo(e.videoinput||[]),this.setMicrophoneDeviceInfo(e.audioinput||[])})).catch((e=>{this.logger.error(this.module_,"getRTCDeviceGroups failed ".concat(e))}))}recordUploadRequsetInfo(e){if(null!=e&&e.type&&"PING"!==e.type)switch(this.reqInfoMap.set(e.requestId,e),e.type){case"JOIN_ROOM":e.eventId=$C.EVENT_JOIN_ROOM,this.eventInfoMap.set(e.eventId,e);break;case"EXIT_ROOM":e.eventId=$C.EVENT_LEAVE_ROOM,this.eventInfoMap.set(e.eventId,e);break;case"SWITCH_ROLE":e.eventId=$C.EVENT_SWITCH_ROLE,this.eventInfoMap.set(e.eventId,e);break;case"PUSH_STREAM_RES_ALL":if(e.videoStreams&&e.videoStreams.length>0){e.videoStreams.find((e=>(null==e?void 0:e.content)===CC.desktop))&&(e.eventId=$C.EVENT_SEND_AUX_STREAM,this.eventInfoMap.set(e.eventId,e))}}}getDownloadRequestInfo(e){if(null==e||!e.requestId)return"";if("PONG"===e.resultMessage)return"PONG";const t=this.reqInfoMap.get(e.requestId);return t&&(null==t?void 0:t.type)||""}recordDownloadRequestInfo(e){if(null==e||!e.requestId)return;if("PONG"===e.resultMessage)return;const t=this.reqInfoMap.get(e.requestId);if(t){switch(this.reportSignalRepForServer2Web(t,e),t.type){case"SUBS_STREAM":t.videoUpstreams&&this.reportVideoSub(t.videoSubType,t.requestId,t.videoUpstreams,e.resultCode,e.resultMessage),t.audioUpstreams&&this.reportAudioSub(t.audioSubType,t.requestId,t.audioUpstreams,e.resultCode);break;case"PUSH_STREAM_RES_ALL":t.videoStreams&&t.videoStreams.length>0&&this.reportUpStreamVideoInfo(t.videoStreams,t.requestId,e.resultCode);break;case"AUDIO_POLICY":this.reportAudioPolicyInfo(t.audioPolicy,t.requestId,e.resultCode)}this.reqInfoMap.delete(e.requestId)}}setMediaStatInfo(){const e=this.mediaStats.getMediaStatInfo()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setMediaStatSumInfo(){const e=this.mediaStats.getMediaStatSum()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setInBoundAudioSsrcInfos(){const e=this.mediaStats.getInBoundAudioSsrc()||[];e.forEach((e=>{this.addCommInfo(e)})),this.mediaOpsData=this.mediaOpsData.concat(e)}setRequestId(e){const t=this.eventInfoMap.get(e.event);return t&&(e.request_id=t.requestId),this}transformJoinInfoResult(e){if(!e&&0!==e)return cA.INTERNAL_ERROR;let t=cA.INTERNAL_ERROR;switch(e){case Gc.RTC_ERR_CODE_SUCCESS:t=cA.SUCCESS;break;case Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED:case Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED:case Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT:case Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT:case Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR:case Gc.RTC_ERR_CODE_STATUS_ERROR:t=cA.NETWORK_CONNECT_ERROR;break;case Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL:case Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN:t=cA.SERVER_ERROR;break;case Gc.RTC_ERR_CODE_INVALID_PARAMETER:t=cA.INTERNAL_ERROR}return t}reportJoinInfo(e,t,r,i,n){var o,s;this.getMediaStat().setACSAddr(t);const a={};a.event=$C.EVENT_JOIN_ROOM,a.access_addr=t,a.sfu_addr=this.sfuInfo.ipAddress,a.aport=this.sfuInfo.audioPort,a.vport=this.sfuInfo.videoPort,this.setRequestId(a),a.result=this.transformJoinInfoResult(e),a.platform="web-"+XR.getPlatform(),a.user_agent="web-"+XR.getUserAgent(),a.role=null===(o=this.user)||void 0===o?void 0:o.role,a.join_qos=JSON.stringify(i||{}),a.is_rejoin=r?1:0,a.nick_name=XR.shieldNickname((null===(s=this.user)||void 0===s?void 0:s.userName)||""),a.time_diff_server=0,a.failMessage="".concat(e||" ").concat(n||" "),this.addCommInfo(a),this.joinTime=a.timestamp,this.eventInfoMap.delete($C.EVENT_JOIN_ROOM),nO.reportRecords([a])}reportRelayJoinInfo(e){var t;const r={};r.event=$C.EVENT_JOIN_ROOM,r.access_addr=e.acsAddr,r.sfu_addr=this.sfuInfo.ipAddress,r.aport=this.sfuInfo.audioPort,r.vport=this.sfuInfo.videoPort,r.request_id=e.requestId,r.result=this.transformJoinInfoResult(e.code),r.platform="web-"+XR.getPlatform(),r.user_agent="web-"+XR.getUserAgent(),r.role=e.role,r.join_qos=JSON.stringify({}),r.is_rejoin=0,r.nick_name=XR.shieldNickname((null===(t=this.user)||void 0===t?void 0:t.userName)||""),r.time_diff_server=0,r.failMessage="".concat(e.code||" ").concat(e.failMessage||" "),this.addCommInfo(r),r.trace_id=e.traceId,r.room_id=e.roomId,r.room_uid=String(e.roomUid),nO.reportRecords([r])}reportRelayLeavInfo(e){const t={};t.event=$C.EVENT_LEAVE_ROOM,t.reason=0,t.result=e.code,t.a_snd_lost_mean=0,t.v_snd_lost_mean=0,t.a_snd_band_width_mean=0,t.v_snd_band_width_mean=0,t.a_snd_rtt_mean=0,t.a_recv_rtt_mean=0,t.v_snd_rtt_mean=0,t.v_recv_rtt_mean=0,t.a_recv_lost_mean=0,t.v_recv_lost_mean=0,t.a_recv_band_width_mean=0,t.v_recv_band_width_mean=0,t.freeze_200ms_cnt=0,t.freeze_600ms_cnt=0,t.freeze_1000ms_cnt=0,t.stut_time_mean=0,t.freeze_400ms_cnt=0,t.freeze_200ms_rate=0,t.freeze_400ms_rate=0,t.freeze_600ms_rate=0,t.freeze_1000ms_rate=0,t.v_snd_frame_rate=0,t.v_snd_pkt_rate=0,t.a_snd_pkt_rate=0,t.v_recv_frame_rate=0,t.v_recv_pkt_rate=0,t.a_recv_pkt_rate=0,t.v_snd_jitter=0,t.v_recv_jitter=0,this.addCommInfo(t),t.trace_id=e.traceId,t.room_id=e.roomId,t.room_uid=String(e.roomUid),t.request_id=e.requestId,t.elapsed=0,nO.reportRecords([t])}reportLeavInfo(e){const t={};t.event=$C.EVENT_LEAVE_ROOM,t.reason=0,t.result=e,t.a_snd_lost_mean=0,t.v_snd_lost_mean=0,t.a_snd_band_width_mean=0,t.v_snd_band_width_mean=0,t.a_snd_rtt_mean=0,t.a_recv_rtt_mean=0,t.v_snd_rtt_mean=0,t.v_recv_rtt_mean=0,t.a_recv_lost_mean=0,t.v_recv_lost_mean=0,t.a_recv_band_width_mean=0,t.v_recv_band_width_mean=0,t.freeze_200ms_cnt=0,t.freeze_600ms_cnt=0,t.freeze_1000ms_cnt=0,t.stut_time_mean=0,t.freeze_400ms_cnt=0,t.freeze_200ms_rate=0,t.freeze_400ms_rate=0,t.freeze_600ms_rate=0,t.freeze_1000ms_rate=0,t.v_snd_frame_rate=0,t.v_snd_pkt_rate=0,t.a_snd_pkt_rate=0,t.v_recv_frame_rate=0,t.v_recv_pkt_rate=0,t.a_recv_pkt_rate=0,t.v_snd_jitter=0,t.v_recv_jitter=0,t.elapsed=(XR.getCurrentTimestamp()-this.joinTime)/1e3,this.addCommInfo(t),this.setRequestId(t),this.eventInfoMap.delete($C.EVENT_LEAVE_ROOM),nO.reportRecords([t])}reportVideoSub(e,t,r,i,n){const o=[],s=[],a=[],c=[],u=[];null==r||r.forEach((e=>{const t=this.getMediaStat().getEncryInfo(e.pUserId)||XR.secretString(e.pUserId)||"";s.push(t),o.push(e.pSsrcId),u.push((null==e?void 0:e.code)||0);const r=this.remoteUserManager.getStreamInfoByPStreamUid(e.pStreamUid);if(r){const e=EO.getResolutionType(r.width,r.height);a.push(e&&e.toUpperCase().replace("-",""))}else this.logger.warn(this.module_,"Can not getStreamInfoByPStreamUid for reportVideoSub");c.push(String(e.pStreamUid))}));const d={event:$C.EVENT_WATCH,action:aA[e],request_id:t,ssrc_list:o.join(","),stream_uid_list:c.join(","),uid_list:s.join(","),img_list:a.join(","),reasonList:u.join(","),result:i,failMessage:0===i?"":n};this.addCommInfo(d),nO.reportRecords([d])}reportSwitchDevicesInfo(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:6;e===zC.OUTPUT_AUDIO?this.deviceInfo.audioOutputId=t:e==zC.INPUT_AUDIO?this.deviceInfo.audioInputId=t:e===zC.INPUT_VIDEO&&(this.deviceInfo.videoInputId=t);const n={event:$C.EVENT_SWITCH_DEVICE,type:e,name:t,result:r,opt:i};this.addCommInfo(n),nO.addRecord(n)}reportSwitchRoleInfo(e,t){const r={event:$C.EVENT_SWITCH_ROLE,role:e,result:t};this.setRequestId(r),this.addCommInfo(r),nO.addRecord(r)}reportStartSendMediaStream(e,t){const r={event:$C.EVENT_SEND_MEDIA,type:e,opt:t};this.addCommInfo(r),nO.reportRecords([r])}setMediaCaptureSucc(e,t){const r={event:$C.EVENT_START_MEDIA,type:e,dev_name:t};this.addCommInfo(r),nO.addRecord(r)}reportAuxiliaryStreamShareInfo(e,t){const r={event:$C.EVENT_SEND_AUX_STREAM,action:e,result:t};this.setRequestId(r),this.addCommInfo(r),nO.reportRecords([r])}setAudioSubscribeInfo(e,t,r){const i=[];let n;null==e||e.forEach((e=>{const t={uid:this.getMediaStat().getEncryInfo(null==e?void 0:e.userid)||XR.secretString(null==e?void 0:e.userid)||"",ssrc:(null==e?void 0:e.ssrc)||0};i.push(t),n=e.action-1}));const o={event:$C.EVENT_SUBSCIBE,request_id:t,policy:this.getMediaStat().getAudioPolicy(),streams:i,action:n,result:r};this.addCommInfo(o),nO.reportRecords([o])}reportAudioSub(e,t,r,i){const n=[];null==r||r.forEach((e=>{const t={uid:this.getMediaStat().getEncryInfo(null==e?void 0:e.pUserId)||XR.secretString(null==e?void 0:e.pUserId)||"",ssrc:(null==e?void 0:e.pSsrcId)||0,reason:(null==e?void 0:e.code)||0};n.push(t)}));const o={event:$C.EVENT_SUBSCIBE,request_id:t,policy:this.getMediaStat().getAudioPolicy(),streams:n,action:e,result:i};this.addCommInfo(o),nO.reportRecords([o])}setConnectionStatusInfo(e,t){const r={timestamp:0,event:$C.EVENT_CONNECTION_CHANNEL_STATUS,type:t,on:e};this.addCommInfo(r),nO.reportRecords([r])}reportUpStreamVideoInfo(e,t,r){const i=[],n=[];e.forEach((e=>{n.push(EO.getResolution(e.width,e.height)),i.push("".concat(e.width,"*").concat(e.height))}));const o={event:$C.EVENT_SET_UP_STREAM,request_id:t,resolution_name_list:n.join(","),width_height_list:i.join(","),result:0===r?GC.SUCCESS:GC.FAIL};this.addCommInfo(o),nO.addRecord(o)}reportAudioPolicyInfo(e,t,r){const i={event:$C.EVENT_SET_AUDIO_POLICY,request_id:t,policy:e,result:r,topn:e===_O.TOPN_AUDIOPOLICY?3:17};this.addCommInfo(i),nO.addRecord(i)}setSysBasicInfo(){const e={event:eA.DEVICE_RT_SYSTEM,device_cpu:0,app_cpu:0,mem_ratio:0};this.addCommInfo(e),nO.addRecord(e)}setCameraInfo(e,t){const r={event:eA.DEVICE_RT_CAMERA,cap_format:0,cap_width:(null==e?void 0:e.width)||0,cap_height:(null==e?void 0:e.height)||0,cap_frame_rate:(null==e?void 0:e.frameRate)||0,out_width:(null==t?void 0:t.width)||0,out_height:(null==t?void 0:t.height)||0,out_cap_frames:(null==t?void 0:t.frameRate)||0,cap_overtime_cnt:0,frame_capture_time:0,render_frame_rate:0,frame_render_time:0};this.addCommInfo(r),nO.addRecord(r)}setSpeakerInputInfo(){const e={event:eA.DEVICE_RT_SPEAKER,dst_down_vel:0,dst_down_nel:0,speaker_vol:0,speaker_play_err_num:0};this.addCommInfo(e),nO.addRecord(e)}setMicrophoneInfo(){const e={event:eA.DEVICE_RT_MICROPHONE,src_cap_vel:0,src_cap_nel:0,src_mic_vol_scale:0,capture_abnormal:0,mic_vol:0,mic_recoder_err_num:0};this.addCommInfo(e),nO.addRecord(e)}async setSpeakerDeviceInfo(e){const t=[];for(let i=0;i5?s-5:0),c=5;ct!==e)):this.clientEventEmitter=null}registerDeviceChangedNotify(){let e=!1;AC().then((e=>{(!e||e.length<=0)&&this.logger.info(MO,"no device available now"),e=e||[],this.preDevices=new Map;for(const t of e)iE.addPrivacyString(t.deviceId),t.deviceId&&"default"!==t.deviceId&&"communications"!==t.deviceId&&this.preDevices.set(t.deviceId,t.kind)})).finally((()=>{navigator.mediaDevices.ondevicechange=async t=>{if(t.isTrusted){if(this.deviceChangeCallBack.push(this.handleDeviceChangeEvent.bind(this)),!e)for(;this.deviceChangeCallBack.length>0;)e=!0,await this.deviceChangeCallBack.shift()(),this.deviceChangeCallBack.length<1&&(e=!1)}else this.logger.error(MO,"device change event trigger by script")}}))}async handleDeviceChangeEvent(){let e=await AC();e=e||[];const t=new Map;for(const i of e)i.deviceId&&"default"!==i.deviceId&&"communications"!==i.deviceId&&t.set(i.deviceId,i.kind);let r=this.internalEventEmitters;this.clientEventEmitter&&(r=[...this.internalEventEmitters,this.clientEventEmitter]),this.preDevices.forEach(((e,i)=>{t.has(i)||(this.logger.info(MO,"deviceType: ".concat(e," deviceId: ").concat(i," remove")),r.forEach((t=>{t.emit(UC[kO[e]],{deviceId:i,state:PO})})),this.stat.setDeviceChangedInfo(e,i,1))})),t.forEach(((e,t)=>{this.preDevices.has(t)||(this.logger.info(MO,"deviceType: ".concat(e," deviceId: ").concat(t," add")),r.forEach((r=>{r.emit(UC[kO[e]],{deviceId:t,state:OO})})),this.stat.setDeviceChangedInfo(e,t,0))})),this.preDevices=t}};function NO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function UO(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2e4,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,a=0;for(;a1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;const s=new Promise(((e,r)=>{t=setTimeout((()=>{clearTimeout(t),r(new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT))}),n)})),a=new Promise(((n,s)=>{fetch(this.getFetchUrl(e),UO(UO(UO({},this.defaultRequestOption),r),{headers:i})).then((t=>{if(XR.syncLocalTime(t.headers.get("Date")),!t.ok)return 504===t.status?this.logger.error(xO,"[HTTP_ID:".concat(o,"] doFetch failed: 504")):0===t.status?this.logger.error(xO,"[HTTP_ID:".concat(o,"] doFetch failed: 0")):this.logger.error(xO,"[HTTP_ID:".concat(o,"] doFetch failed: ").concat(t.status)),void s(new qc(t.status,"network error"));let r;const a=t.headers.get("Content-Type")||i["Content-Type"];r=/.*application\/json.*/.test(a)?t.json():/^text.*/.test(a)?t.text():t.arrayBuffer(),r.then((e=>{n({httpCode:t.status,data:e})})).catch((t=>{this.logger.error(xO,"[HTTP_ID:".concat(o,"], requestUrl: ").concat(XR.shieldUrlParameters(e),", doFetch get response failed: ").concat(t)),s(new qc(null==t?void 0:t.name,null==t?void 0:t.message))}))})).catch((t=>{this.logger.error(xO,"[HTTP_ID:".concat(o,"], requestUrl: ").concat(XR.shieldUrlParameters(e),", doFetch failed for exception: ").concat(t)),s(new qc(null==t?void 0:t.name,null==t?void 0:t.message))})).finally((()=>{clearTimeout(t)}))}));return Promise.race([s,a])}extendInfosHandle(e,t,r,i,n){i&&("start"===t?Object.assign(r,{id:i.length+1,domain:e,start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"dispatch",rspCode:"",errMsg:""}):"end"===t?((/v1\/dns/.test(e)||/global\.talk-cloud\.net/.test(e))&&(r.start_ms=XR.adjustTimeByOffset(r.start_ms)),n instanceof qc?(r.delay_ms=XR.getCurrentTimestamp()-r.start_ms,r.rspCode="".concat(n.getCode()),r.errMsg=n.getMsg()):(r.delay_ms=XR.getCurrentTimestamp()-r.start_ms,r.rspCode=n.httpCode||"200"),i.push(r)):this.logger.info(xO,"cannot handle"))}};function BO(){}function VO(){VO.init.call(this)}function YO(e){return void 0===e._maxListeners?VO.defaultMaxListeners:e._maxListeners}function jO(e,t,r,i){var n,o,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]):(o=e._events=new BO,e._eventsCount=0),s){if("function"==typeof s?s=o[t]=i?[r,s]:[s,r]:i?s.unshift(r):s.push(r),!s.warned&&(n=YO(e))&&n>0&&s.length>n){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=s.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(a)}}else s=o[t]=r,++e._eventsCount;return e}function FO(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function HO(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function KO(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}BO.prototype=Object.create(null),VO.EventEmitter=VO,VO.usingDomains=!1,VO.prototype.domain=void 0,VO.prototype._events=void 0,VO.prototype._maxListeners=void 0,VO.defaultMaxListeners=10,VO.init=function(){this.domain=null,VO.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new BO,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},VO.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},VO.prototype.getMaxListeners=function(){return YO(this)},VO.prototype.emit=function(e){var t,r,i,n,o,s,a,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=s[e]))return!1;var d="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=KO(e,i),o=0;o0;)if(r[o]===t||r[o].listener&&r[o].listener===t){s=r[o].listener,n=o;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new BO,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i0?Reflect.ownKeys(this._events):[]};const zO=new class{constructor(){i(this,"eventHandlers",{visibilitychange:()=>{let e="FOREGROUND";document.hidden&&(e="BACKGROUND");for(const t of this.eventBus.values())t.emit(e)}}),i(this,"eventListeners",{visibilitychange:e=>{"ADD"===e?document.addEventListener("visibilitychange",this.eventHandlers.visibilitychange):document.removeEventListener("visibilitychange",this.eventHandlers.visibilitychange)}}),this.eventBus=new Map,this.addListener("visibilitychange",XR.isMobileDevice.bind(XR))}register(e){const t=XR.generateRandomId(32);return this.eventBus.set(t,e),t}unregister(e){e&&this.eventBus.delete(e)}addListener(e,t){t&&!t()||this.eventListeners[e]&&this.eventListeners[e]("ADD")}removeListener(e){this.eventListeners[e]&&this.eventListeners[e]("REMOVE")}};class WO{constructor(){this.context_=new AudioContext,this.script_=this.context_.createScriptProcessor(2048,1,1),this.script_.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);let r=0,i=0;for(let n=0;n.99&&(i+=1);this.instant_=Math.sqrt(r/t.length),this.slow_=.95*this.slow_+.05*this.instant_,this.clip_=i/t.length},this.instant_=0,this.slow_=0,this.clip_=0}connectToSource(e){return new Promise(((t,r)=>{try{const r=new MediaStream;r.addTrack(e),this.mic_=this.context_.createMediaStreamSource(r),this.mic_.connect(this.script_),this.script_.connect(this.context_.destination),t()}catch(Aw){r(Aw)}}))}stop(){this.mic_.disconnect(),this.script_.disconnect(),this.context_.close()}getVolume(){return parseFloat(this.instant_.toFixed(2))}}class GO{constructor(e){this.module_="RTCPlayer",this.mediaStream_=new MediaStream,this.log_=e.logger,this.track_=e.track,this.playerDiv_=e.playerDiv,this.playerId_=e.playerId,this.playerElement_=null,this.state_="NONE",this.event_=new VO,this.pauseCount=0,this.listenHandlers={canPlayHandler:this.canPlayHandler.bind(this),playingHandler:this.playingHandler.bind(this),playerEndedHandler:this.playerEndedHandler.bind(this),playerPausedHandler:this.playerPausedHandler.bind(this),trackEndedHandler:this.trackEndedHandler.bind(this),trackMutedHandler:this.trackMutedHandler.bind(this),trackUnmutedHandler:this.trackUnmutedHandler.bind(this),playHandler:null,backgroundHandler:this.backgroundHandler.bind(this),foregroundHandler:this.foregroundHandler.bind(this)}}on(e,t){this.event_.on(e,t)}off(e,t){this.event_.removeListener(e,t)}foregroundHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, application is foreground"),this.module_.indexOf("Audio")>0&&this.track_&&this.trackEnable!==this.track_.enabled&&(this.track_.enabled=this.trackEnable),"PAUSED"===this.state_&&(this.module_.indexOf("Video")>0?this.event_.emit("videoCanPlay"):this.event_.emit("audioCanPlay"))}backgroundHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, application is background"),this.module_.indexOf("Audio")>0&&this.track_&&(this.trackEnable=this.track_.enabled,this.trackEnable&&(this.track_.enabled=!1))}canPlayHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is canplay status"),this.event_.emit(this.module_.indexOf("Video")>0?"videoCanPlay":"audioCanPlay"),this.event_.emit(iC,{event:"playerCanplay",type:"".concat(this.module_),streamId:this.playerId_})}playingHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is starting playing"),this.event_.emit(iC,{event:"playerPlaying",type:"".concat(this.module_),streamId:this.playerId_}),this.state_="PLAYING",this.event_.emit(Zb,{state:this.state_,reason:"playing"})}playerEndedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is ended"),this.event_.emit(iC,{event:"playerEnded",type:"".concat(this.module_),streamId:this.playerId_}),"STOPPED"!==this.state_&&(this.state_="STOPPED",this.event_.emit(Zb,{state:this.state_,reason:"ended"}))}playerPausedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player is paused"),this.event_.emit(iC,{event:"playerPause",type:"".concat(this.module_),streamId:this.playerId_}),this.state_="PAUSED",this.event_.emit(Zb,{state:this.state_,reason:"pause"}),this.module_.indexOf("Video")>0?(this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"try to play again"),this.event_.emit("videoCanPlay")):(this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"try to play again"),this.event_.emit("audioCanPlay"))}trackEndedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, player track is ended"),this.event_.emit(iC,{event:"trackEnded",type:"".concat(this.module_),streamId:this.playerId_}),"STOPPED"!==this.state_&&(this.state_="STOPPED",this.event_.emit(Zb,{state:this.state_,reason:"ended",trackEnded:!0}))}trackMutedHandler(){this.log_.debug("".concat(this.module_,"#").concat(this.playerId_),"handleEvents, track is muted"),this.event_.emit(iC,{event:"trackMute",type:"".concat(this.module_),streamId:this.playerId_}),"PAUSED"!==this.state_&&(this.state_="PAUSED",this.event_.emit(Zb,{state:this.state_,reason:"mute"}))}trackUnmutedHandler(){this.log_.debug("".concat(this.module_,"#[").concat(this.playerId_,"]"),"handleEvents, track is unmuted"),this.event_.emit(iC,{event:"trackUnmute",type:"".concat(this.module_),streamId:this.playerId_}),"PAUSED"===this.state_&&(this.state_="PLAYING",this.event_.emit(Zb,{state:this.state_,reason:"unmute"}))}closeAllEvents(){var e,t,r,i,n,o,s,a,c;null===(e=this.playerElement_)||void 0===e||e.removeEventListener("canplay",this.listenHandlers.canPlayHandler),null===(t=this.playerElement_)||void 0===t||t.removeEventListener("playing",this.listenHandlers.playingHandler),null===(r=this.playerElement_)||void 0===r||r.removeEventListener("ended",this.listenHandlers.playerEndedHandler),null===(i=this.playerElement_)||void 0===i||i.removeEventListener("pause",this.listenHandlers.playerPausedHandler),null===(n=this.track_)||void 0===n||n.removeEventListener("ended",this.listenHandlers.trackEndedHandler),null===(o=this.track_)||void 0===o||o.removeEventListener("mute",this.listenHandlers.trackMutedHandler),null===(s=this.track_)||void 0===s||s.removeEventListener("unmute",this.listenHandlers.trackUnmutedHandler),null===(a=this.event_)||void 0===a||a.removeListener("videoCanPlay",this.listenHandlers.playHandler),null===(c=this.event_)||void 0===c||c.removeListener("audioCanPlay",this.listenHandlers.playHandler),this.event_.removeListener("FOREGROUND",this.listenHandlers.foregroundHandler),this.event_.removeListener("BACKGROUND",this.listenHandlers.backgroundHandler),zO.unregister(this.sysEventRegisterUid)}handleEvents(){this.playerElement_.addEventListener("canplay",this.listenHandlers.canPlayHandler),this.playerElement_.addEventListener("playing",this.listenHandlers.playingHandler),this.playerElement_.addEventListener("ended",this.listenHandlers.playerEndedHandler),this.playerElement_.addEventListener("pause",this.listenHandlers.playerPausedHandler),this.track_.addEventListener("ended",this.listenHandlers.trackEndedHandler),this.track_.addEventListener("mute",this.listenHandlers.trackMutedHandler),this.track_.addEventListener("unmute",this.listenHandlers.trackUnmutedHandler),this.event_.on("FOREGROUND",this.listenHandlers.foregroundHandler),this.event_.on("BACKGROUND",this.listenHandlers.backgroundHandler),this.sysEventRegisterUid=zO.register(this.event_)}stop(){this.closeAllEvents(),this.playerElement_&&(this.playerElement_.srcObject=null),this.playerElement_=null,this.mediaStream_=new MediaStream,this.log_.info(this.module_,"stop success")}replaceTrack(e){this.log_.info(this.module_,"replaceTrack start");const t=this.module_.indexOf("Audio")>0?this.mediaStream_.getAudioTracks():this.mediaStream_.getVideoTracks(),r=t.length?t[0]:null;r!==e&&(r&&this.mediaStream_.removeTrack(r),this.mediaStream_.addTrack(e),this.track_=e)}async resume(e){return new Promise(((t,r)=>{this.playerElement_?this.playerElement_.play().then((()=>{this.log_.info(this.module_,"audio player resume success, streamId:".concat(this.playerId_,", playParameters: ").concat(JSON.stringify(e))),t(null)})).catch((t=>{this.log_.error(this.module_,"player resume failed, errmsg=".concat(t," , playParameters: ").concat(JSON.stringify(e))),"NotAllowedError"===t.name?r(new qc(Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW)):r(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,t.message))})):r(new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"resume failed, element is null"))}))}async multiPlatformAdapter(){return new Promise((e=>{if(XR.isWKWebview()){const t=window.WeixinJSBridge;t?(this.log_.info(this.module_,"multiPlatformAdapter handle begin"),t.invoke("getNetworkType",{},(()=>{e()}),!1)):document.addEventListener("WeixinJSBridgeReady",(()=>{this.log_.info(this.module_,"multiPlatformAdapter WeixinJSBridgeReady, handle begin"),t.invoke("getNetworkType",{},(()=>{e()}),!1)}))}else e()}))}async doPlay(e,t,r){let i;return await this.multiPlatformAdapter(),i=this.module_.indexOf("Video")>0?", screenFit:".concat(r.objectFit,", mirror:").concat(r.mirror):", deviceId:".concat(r.outputDeviceId,", volume:").concat(r.volume,", muted:").concat(r.muted),this.playerElement_.play().then((()=>{var t,r;this.log_.info(this.module_,"play success, parentDiv id:".concat(null===(t=this.playerDiv_)||void 0===t?void 0:t.id,", resolutionId or streamId:").concat(this.playerId_,", physical track id:").concat(null===(r=this.track_)||void 0===r?void 0:r.id).concat(i)),this.afterPlayStrategy(),e(null)})).catch((e=>{var r,n;this.log_.error(this.module_,"play failed, errmsg=".concat(e,",parentDiv id:").concat(null===(r=this.playerDiv_)||void 0===r?void 0:r.id,", resolutionId or streamId:").concat(this.playerId_,", physical track id:").concat(null===(n=this.track_)||void 0===n?void 0:n.id).concat(i)),"NotAllowedError"===e.name?t(new qc(Gc.RTC_ERR_CODE_PLAY_NOT_ALLOW)):t(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,e.message))})).finally((()=>{clearTimeout(this.playTimeOutTimer)}))}afterPlayStrategy(){if(!this.pauseCount&&XR.getPlatform().indexOf("Ios15")>=0){this.log_.error(this.module_,XR.getPlatform());const e=setTimeout((()=>{clearTimeout(e),this.playerElement_.pause(),this.pauseCount++}),100)}}}class JO extends GO{constructor(e){super({logger:e.logger,track:e.track,playerDiv:e.playerDiv,playerId:e.playerId}),this.module_="RTCAudioPlayer",this.muted_=e.muted,this.outputDeviceId_="",this.volume_="number"==typeof(null==e?void 0:e.volume)?e.volume:.5,this.soundMeter_=null}async play(){return new Promise(((e,t)=>{let r,i=!0;var n;(r=this.playerDiv_?this.playerDiv_.querySelector("#audio_".concat(this.playerId_)):this.playerElement_,r)||(r=document.createElement("audio"),r.muted=this.muted_,r.setAttribute("id","audio_".concat(this.playerId_)),r.setAttribute("autoplay",""),r.setAttribute("playsinline",""),r.setAttribute("muted",""),null===(n=this.playerDiv_)||void 0===n||n.appendChild(r),i=!1);"sinkId"in HTMLMediaElement.prototype&&this.outputDeviceId_&&r.setSinkId(this.outputDeviceId_),0===this.mediaStream_.getAudioTracks().length&&this.mediaStream_.addTrack(this.track_),r.srcObject=this.mediaStream_,this.playerElement_=r,this.setVolume(this.volume_),this.handleEvents(),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"trigger audioCanPlay event by Timer"),this.event_.emit("audioCanPlay"),this.playTimeOutTimer&&(clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"audio playing timeout"),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=null,e(null)}),2e3))}),i?0:1e3),this.listenHandlers.playHandler&&this.event_.removeListener("audioCanPlay",this.listenHandlers.playHandler),this.listenHandlers.playHandler=this.doPlay.bind(this,e,t,{deviceId:this.outputDeviceId_,volume:this.volume_,muted:this.muted_}),this.event_.on("audioCanPlay",this.listenHandlers.playHandler)}))}async setSinkId(e){this.outputDeviceId_!==e&&(await this.playerElement_.setSinkId(e),this.outputDeviceId_=e)}setVolume(e){this.playerElement_.volume=e}getAudioLevel(){return this.soundMeter_||(this.soundMeter_=new WO,this.soundMeter_.connectToSource(this.track_)),this.soundMeter_.getVolume()}stop(){super.stop(),this.soundMeter_&&(this.soundMeter_.stop(),this.soundMeter_=null)}async resume(){return super.resume({streamId:this.playerId_,deviceId:this.outputDeviceId_,volume:this.volume_,muted:this.muted_})}replaceTrack(e){super.replaceTrack(e),this.soundMeter_&&(this.soundMeter_.stop(),this.soundMeter_=null)}}class qO extends GO{constructor(e){super({logger:e.logger,track:e.track,playerDiv:e.parentDiv,playerId:e.playerId}),this.module_="RTCVideoPlayer",this.objectFit_=e.objectFit,this.mirror_=e.mirror}async play(){return new Promise(((e,t)=>{let r=this.playerDiv_.querySelector("#video_".concat(this.playerId_)),i=!0;if(!r){r=document.createElement("video"),r.muted=!0;let e="0";this.mirror_&&(e="180deg"),r.setAttribute("id","video_".concat(this.playerId_)),r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.transform="rotateY(".concat(e,")"),r.style["object-fit"]=this.objectFit_,r.setAttribute("autoplay",""),r.setAttribute("playsinline",""),r.setAttribute("muted",""),this.playerDiv_.appendChild(r),i=!1}0===this.mediaStream_.getVideoTracks().length&&this.mediaStream_.addTrack(this.track_),r.srcObject=this.mediaStream_,this.playerElement_=r,this.handleEvents(),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"trigger videoCanPlay event by Timer"),this.event_.emit("videoCanPlay"),this.playTimeOutTimer&&(clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=setTimeout((()=>{this.log_.info(this.module_,"video playing timeout"),clearTimeout(this.playTimeOutTimer),this.playTimeOutTimer=null,e(null)}),2e3))}),i?0:1e3),this.listenHandlers.playHandler&&this.event_.removeListener("videoCanPlay",this.listenHandlers.playHandler),this.listenHandlers.playHandler=this.doPlay.bind(this,e,t,{objectFit:this.objectFit_,mirror:this.mirror_}),this.event_.on("videoCanPlay",this.listenHandlers.playHandler)}))}async resume(){return super.resume({streamId:this.playerId_,screentFit:this.objectFit_,mirror:this.mirror_})}getVideoFrame(){const e=document.createElement("canvas");return e.width=this.playerElement_.videoWidth,e.height=this.playerElement_.videoHeight,e.getContext("2d").drawImage(this.playerElement_,0,0),e.toDataURL("image/png")}}function XO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function QO(e){for(var t=1;tt.startsWith("".concat(e.height))&&cC[t].width===e.width||parseInt(t)>e.height));t&&(e.maxBitrate&&e.minBitrate||(e.maxBitrate=cC[t].maxBitrate,e.minBitrate=cC[t].minBitrate),e.frameRate||(e.frameRate=cC[t].frameRate))}class ZO{static getLocalProfileByTrack(e){const t={},r=e.getSettings();if(e.kind===mO.TRACK_TYPE_AUDIO)t.sampleRate=r.sampleRate,t.channelCount=1;else{var i,n,o,s;const a=e.getConstraints();t.width=("number"==typeof a.width?a.width:null===(i=a.width)||void 0===i?void 0:i.ideal)||r.width,t.height=("number"==typeof a.height?a.height:null===(n=a.height)||void 0===n?void 0:n.ideal)||r.height,t.frameRate=("number"==typeof a.frameRate?a.frameRate:null===(o=a.frameRate)||void 0===o?void 0:o.ideal)||parseInt(null===(s=r.frameRate)||void 0===s?void 0:s.toString()),t.minBitrate=null,t.maxBitrate=null,$O(t)}return t}static formatVideoProfile(e){let t={};if(!e){return t=QO({},cC["360p_2"]),t}if("string"==typeof e){if(uC.includes(e)){t=QO({},cC[e])}}else t.height=e.height,t.width=e.width,t.frameRate=e.frameRate,t.maxBitrate=e.maxBitrate,t.minBitrate=e.minBitrate,void 0!==t.width&&void 0!==t.height||(t.width=cC["360p_2"].width,t.height=cC["360p_2"].height),$O(t);return t}static formatAudioProfile(e){let t={};if(!e){return t=QO({},sC.standard),t}if("string"==typeof e){if(aC.includes(e)){t=QO({},sC[e])}}else t.bitrate=e.bitrate,t.channelCount=e.channelCount,t.sampleRate=e.sampleRate,t.sampleRate||(t.sampleRate=16e3),t.channelCount||(t.channelCount=1),t.bitrate||(t.bitrate=24e3);return t}static formatScreenProfile(e){let t={};if(!e){return t=QO({},dC["720p"]),t}if("string"==typeof e){if(lC.includes(e)){t=QO({},dC[e])}}else t.height=e.height,t.width=e.width,t.bitrate=e.bitrate,t.frameRate=e.frameRate,t.width&&t.height||(t.width=dC["720p"].width,t.height=dC["720p"].height),t.frameRate||(t.frameRate=15),t.bitrate||(t.bitrate=dC["720p"].bitrate);return t}}const eP=XR.isSafari(),tP=(e,t)=>{XR.isSupportConstraints("aspectRatio")&&!eP&&(e.aspectRatio={ideal:t.width/t.height}),e.width=eP?{min:cC["90p_2"].width}:{min:cC["90p_2"].width,ideal:t.width},e.height=eP?{min:cC["90p_2"].height}:{min:cC["90p_2"].height,ideal:t.height},e.frameRate=t.frameRate};class rP{static getOptimalVideoConstraint(e,t){const r={},i=[];["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e};const n=[{width:t.width,height:t.height},{aspectRatio:t.width/t.height}];i.push(...n),tP(r,t),r.advanced=i;const o={};return o.video=r,o}static getSuboptimalVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e},tP(r,t);const i={};return i.video=r,i}static getNextVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={exact:e}:r.deviceId={exact:e},tP(r,t);const i={};return i.video=r,i}static getWorstVideoConstraint(e,t){const r={};["user","environment","left","right"].includes(e)?r.facingMode={ideal:e}:r.deviceId={ideal:e},tP(r,t);const i={};return i.video=r,i}static getRecoveryVideoConstraint(){const e={video:!0};return e}static initScreenShareConstraint(e,t){const r={};if(eP?(r.video={frameRate:t.frameRate},t.width&&(r.video.width={max:t.width}),t.height&&(r.video.height={max:t.height})):r.video={width:t.width||void 0,height:t.height||void 0,frameRate:t.frameRate},e){const e={sampleRate:sC.high.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};Cw.isChrome()&&(e.googNoiseSuppression=!0,e.googAutoGainControl=!0,e.googAutoGainControl2=!0),r.audio=e}return r}static initAudioConstraint(e,t){const r={},i={sampleRate:t.sampleRate,channelCount:t.channelCount,deviceId:e,echoCancellation:!0};return Cw.isFirefox()&&e&&(i.deviceId={exact:e}),i.noiseSuppression=!0,i.autoGainControl=!0,Cw.isChrome()&&(i.googNoiseSuppression=!0,i.googAutoGainControl=!0,i.googAutoGainControl2=!0),r.audio=i,r}}var iP=function(e){return e[e.Stopped=0]="Stopped",e[e.Playing=1]="Playing",e[e.Closed=2]="Closed",e}(iP||{});const nP="HRTCTrack";class oP{constructor(e){this.log_=e.logger||iE.getLogger(),this.trackType_=e.trackType,this.streamType_=e.streamType,this.isRemote_=e.isRemote,this.resolutionId_=e.resolutionId,e.track?this.setLocalProfileByTrack(e.track):this.setTrackProfile(e.trackProfile),this.track_=e.track,this.playState_=iP.Closed,this.trackMuted_=!1,this.event_=e.event||new VO,this.trackType_===mO.TRACK_TYPE_AUDIO?this.statusChangeReporter_=e=>{this.event_.emit(Zb,{type:mO.TRACK_TYPE_AUDIO,id:this.getResolutionId(),state:e.state,reason:e.reason})}:this.statusChangeReporter_=e=>{this.event_.emit(Zb,{type:mO.TRACK_TYPE_VIDEO,id:this.getResolutionId(),state:e.state,reason:e.reason})},this.statusTraceReporter_=e=>{this.event_.emit(iC,e)}}async initScreenShare(e){const t=rP.initScreenShareConstraint(e,this.profile_);this.log_.info(nP,"initScreenShare, screen constraints: ".concat(JSON.stringify(t)));const r=[],i={type:mO.TRACK_TYPE_AUDIO},n={type:mO.TRACK_TYPE_VIDEO};return new Promise((o=>{navigator.mediaDevices.getDisplayMedia(t).then((t=>{const r=t.getVideoTracks()[0];this.track_&&(this.track_.stop(),this.player_&&this.player_.replaceTrack(r)),this.track_=r,n.track=r,this.content=CC.desktop,r.onended=()=>{this.event_.emit(eC,this.trackId_||this.resolutionId_)},e&&(0===(t.getAudioTracks()||[]).length?this.log_.info(nP,"initScreenShare, cannot capture system output audio, pls make sure checked the share Audio option in share page"):i.track=t.getAudioTracks()[0])})).catch((e=>{this.log_.error(nP,"initScreenShare, getDisplayMedia failed, errMsg= ".concat(e)),i.error=this.handleCaptureError(e),n.error=i.error})).finally((()=>{r.push(i),r.push(n),o(r)}))}))}async initAudioCapture(e){const t=rP.initAudioConstraint(e,this.profile_);return await this.getUserMedia(t,mO.TRACK_TYPE_AUDIO,CC.main)}async initVideoCapture(e,t){let r;return this.log_.info(nP,"initVideoCapture, try getOptimalVideoConstraint"),r=await this.getUserMedia(rP.getOptimalVideoConstraint(e,this.profile_),mO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getSuboptimalVideoConstraint"),r=await this.getUserMedia(rP.getSuboptimalVideoConstraint(e,this.profile_),mO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getNextVideoConstraint"),r=await this.getUserMedia(rP.getNextVideoConstraint(e,this.profile_),mO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getWorstVideoConstraint"),r=await this.getUserMedia(rP.getWorstVideoConstraint(e,this.profile_),mO.TRACK_TYPE_VIDEO,t),oP.isTrackAvailable(r.track)?r:(this.log_.info(nP,"initVideoCapture, try getRecoveryVideoConstraint"),await this.getUserMedia(rP.getRecoveryVideoConstraint(),mO.TRACK_TYPE_VIDEO,t)))))}async getUserMedia(e,t,r){const i={type:t};try{var n;null===(n=this.track_)||void 0===n||n.stop();const o=await navigator.mediaDevices.getUserMedia(e),s=t===mO.TRACK_TYPE_VIDEO?o.getVideoTracks()[0]:o.getAudioTracks()[0];return await this.replaceTrack(s),i.track=this.track_,this.content=r,i.type===mO.TRACK_TYPE_VIDEO&&this.setCameraCaptureReport(),i}catch(jN){return i.error=this.handleCaptureError(jN,t),i}}static isTrackAvailable(e){return!!e&&(e.enabled&&!e.muted&&"live"===e.readyState)}setCameraCaptureReport(){this.cameraCaptureHandleTimer&&clearInterval(this.cameraCaptureHandleTimer),this.cameraCaptureHandleTimer=setInterval((()=>{if(this.track_&&this.profile_){var e;const t=this.track_.getSettings(),r={width:this.profile_.width,height:this.profile_.height,frameRate:parseInt(null===(e=this.profile_.frameRate)||void 0===e?void 0:e.toString())||0};this.event_.emit(oC.CameraCapture,t,r)}}),2e3)}clearCameraCaptureReport(){this.cameraCaptureHandleTimer&&clearInterval(this.cameraCaptureHandleTimer)}handleCaptureError(e,t){if(/.*Malformed constraints.*/gi.test(e.message))return this.log_.warn(nP,"init ".concat(t||"screen","capture getUserMedia failed, handleCaptureError: ").concat(e)),null;const r=e.name||"";let i;return i=/.*NotAllowedError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_PERMISSION_DENIED):/.*OverConstrainedError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_OVER_CONSTRAINED):/.*NotReadableError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_READABLE):/.*NotFoundError.*/gi.test(r)?new qc(Gc.RTC_ERR_CODE_CAPTURE_DEVICE_NOT_FOUND):new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR,e.message),this.log_.error(nP,"init ".concat(t||"screen","capture getUserMedia failed, handleCaptureError: ").concat(i)),i}isClosed(){return this.playState_===iP.Closed}isPlaying(){return this.playState_===iP.Playing}getTrackType(){return this.trackType_}getResolutionId(){return this.resolutionId_}getTrackId(){return this.trackId_}getElementId(){return this.elementId_}getObjectFit(){return this.objectFit_}setTrackId(e){this.trackId_=e}getTrackProfile(){return this.profile_}setTrackContentType(e){this.content=e}getTrackContentType(){return this.content||CC.main}updateTrackProfile(e){this.trackType_===mO.TRACK_TYPE_VIDEO&&e&&(this.profile_.width=e.width,this.profile_.height=e.height)}setTrackProfile(e){this.log_.info(nP,"setTrackProfile begin,uniqueId_:".concat(this.resolutionId_,", ").concat(this.trackType_,",")+"".concat(this.streamType_,", profile:").concat(JSON.stringify(e))),this.trackType_!==mO.TRACK_TYPE_AUDIO?this.trackType_!==mO.TRACK_TYPE_VIDEO||this.streamType_!==gO.STREAM_TYPE_MAIN?this.trackType_===mO.TRACK_TYPE_VIDEO&&this.streamType_===gO.STREAM_TYPE_AUX&&(this.profile_=ZO.formatScreenProfile(e)):this.profile_=ZO.formatVideoProfile(e):this.profile_=ZO.formatAudioProfile(e)}getTrack(){return this.track_}async replaceTrack(e){var t;if(e){var r;if(null===(t=this.player_)||void 0===t||t.replaceTrack(e),!this.isRemote_)null===(r=this.track_)||void 0===r||r.stop();this.track_=e,this.track_.enabled=!this.trackMuted_,this.isRemote_||(this.setLocalProfileByTrack(e),this.playState_===iP.Playing&&await this.restart())}}setLocalProfileByTrack(e){this.profile_=ZO.getLocalProfileByTrack(e),this.log_.info(nP,"setLocalProfileByTrack, this.profile_:".concat(JSON.stringify(this.profile_)))}removeTrack(){var e;(this.player_&&this.player_.stop(),this.isRemote_)||(null===(e=this.track_)||void 0===e||e.stop());this.track_=null}async play(e,t,r){const i=this.getTrackType();if(this.log_.info(nP,"".concat(i," track begin play, elementId:").concat(t,", playerDiv.id:").concat(e.id,", options:").concat(JSON.stringify(r)," ")),this.playState_===iP.Playing)return this.log_.info(nP,"".concat(i," track is playing, return")),{trackType:i,error:null};if(!this.track_)return this.log_.error(nP,"".concat(i," track is empty")),{trackType:i,error:new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"".concat(i," track is empty"))};switch(this.elementId_=t,this.trackType_){case mO.TRACK_TYPE_AUDIO:this.player_||(this.log_.info(nP,"create AudioPlayer"),this.player_=new JO({logger:this.log_,playerDiv:e,playerId:this.getTrackId()||this.getResolutionId(),track:this.track_,muted:r.muted,volume:this.audioVolume_}));break;case mO.TRACK_TYPE_VIDEO:this.objectFit_=r.objectFit,this.player_||(this.log_.info(nP,"create VideoPlayer"),this.player_=new qO({logger:this.log_,parentDiv:e,playerId:this.getTrackId()||this.getResolutionId(),track:this.track_,objectFit:r.objectFit,mirror:r.mirror}))}this.player_.off(Zb,this.statusChangeReporter_),this.player_.on(Zb,this.statusChangeReporter_),this.player_.off(iC,this.statusTraceReporter_),this.player_.on(iC,this.statusTraceReporter_),this.log_.info(nP,"play ".concat(i," track start")),this.playState_=iP.Playing;try{return await this.player_.play(),{trackType:i,error:null}}catch(jN){const t=jN instanceof qc&&/.*timeout.*/i.test(jN.getMsg());return this.log_[t?"warn":"error"](nP,"play ".concat(i," failed: ").concat(jN)),this.playState_=iP.Stopped,{trackType:i,error:jN}}}async replay(){if(!this.player_)return this.log_.info(nP,"".concat(this.getTrackType()," player is null")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"".concat(this.getTrackType()," player is null"));this.player_.off(Zb,this.statusChangeReporter_),this.player_.on(Zb,this.statusChangeReporter_),this.player_.off(iC,this.statusTraceReporter_),this.player_.on(iC,this.statusTraceReporter_),this.log_.info(nP,"rePlay ".concat(this.getTrackType()," track start")),this.playState_=iP.Playing;try{return await this.player_.play(),null}catch(jN){return this.log_.error(nP,"replay".concat(this.getTrackType(),", replay failed: ").concat(jN)),this.playState_=iP.Stopped,jN}}stop(){this.player_?(this.player_.off(Zb,this.statusChangeReporter_),this.player_.stop(),this.player_=null,this.playState_=iP.Stopped,this.trackMuted_=!1,this.log_.info(nP,"".concat(this.getTrackType()," stop player success"))):this.log_.info(nP,"".concat(this.getTrackType()," player is null"))}close(){var e;(this.stop(),this.isRemote_)||(null===(e=this.track_)||void 0===e||e.stop());this.elementId_="",this.log_.info(nP,"".concat(this.getTrackType()," close success")),this.playState_=iP.Closed,this.clearCameraCaptureReport()}async resume(){if(!this.player_)return this.log_.info(nP,"".concat(this.getTrackType()," player is null")),null;try{return await this.player_.resume(),null}catch(jN){return this.log_.error(nP,"".concat(this.getTrackType()," resume failed: ").concat(jN)),jN}}async restart(){this.player_&&(this.player_.stop(),await this.player_.play(),this.log_.info(nP,"restart success"))}getTrackMuted(){return this.track_?!this.track_.enabled:this.trackMuted_}muteTrack(){this.track_&&(this.track_.enabled=!1),this.trackMuted_=!0}unmuteTrack(){this.track_&&(this.track_.enabled=!0),this.trackMuted_=!1}async setSinkId(e){this.trackType_===mO.TRACK_TYPE_AUDIO&&this.player_&&await this.player_.setSinkId(e)}setAudioVolume(e){this.trackType_===mO.TRACK_TYPE_AUDIO&&(this.audioVolume_=e/100,this.player_&&this.player_.setVolume(this.audioVolume_))}getAudioLevel(){return this.trackType_===mO.TRACK_TYPE_AUDIO&&this.player_?this.player_.getAudioLevel():0}getVideoFrame(){return this.trackType_===mO.TRACK_TYPE_VIDEO&&this.player_?this.player_.getVideoFrame():null}setAudioOutput(e){this.trackType_===mO.TRACK_TYPE_AUDIO&&this.player_&&this.player_.setSinkId(e)}}const sP="AsyncLock";class aP{constructor(){i(this,"callback_",[]),this.callback_=[],this.logger=iE.getLogger()}async lock(e){this.logger.info(sP,"".concat(e," try to get lock")),await new Promise((t=>{const r={callbackFunc:()=>t(),lockTrigger:"".concat(e)};this.callback_.push(r),1===this.callback_.length&&(this.callback_[0].callbackFunc(),this.logger.info(sP,"".concat(this.callback_[0].lockTrigger," got lock")))}))}unlock(e){if(this.logger.info(sP,"".concat(e," try to unlock")),this.callback_.length>0){const e=this.callback_.shift();this.logger.info(sP,"".concat(e.lockTrigger," unlocked")),this.callback_.length>0&&(this.callback_[0].callbackFunc(),this.logger.info(sP,"".concat(this.callback_[0].lockTrigger," got lock")))}else this.logger.error(sP,"unlock, but no lock exist")}clear(){for(;this.callback_.length>0;)this.unlock(this.callback_[0].lockTrigger)}}const cP=new aP;function uP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function dP(e){for(var t=1;t{const n=i.value;return dP(dP({},i),{},{async value(){const t=this.locker||cP;try{var i,o;null===(i=this.log)||void 0===i||i.info(e,"function ".concat(r," is wating for lock. ")),await t.lock(e),null===(o=this.log)||void 0===o||o.info(e,"function ".concat(r," get a lock. "));for(var s=arguments.length,a=new Array(s),c=0;c{const n=i.value,o=e.substr(0,e.indexOf("$"));return dP(dP({},i),{},{async value(){let t,r;const i=XR.getCurrentTimestamp();for(var s=arguments.length,a=new Array(s),c=0;c{const n=i.value,o=e.substr(0,e.indexOf("$"));return dP(dP({},i),{},{value(){let t,r;const i=XR.getCurrentTimestamp();for(var s=arguments.length,a=new Array(s),c=0;c["object","function"].includes(typeof e)?e.getStatInfo?e.getStatInfo():e.getInfo?e.getInfo():e:e))}catch(Aw){return e}}class mP{static async callAsyncApi(e,t,r,i){let n,o;const s=XR.getCurrentTimestamp(),a=r||[];try{return o=await t.call(e,...a),o}catch(jN){throw n=jN,jN}finally{const t=XR.getCurrentTimestamp(),r=mP.doFinalParam([o,...a,e]);e.stat.setApiCallInfo(i,s,t,n,...r)}}static doFinalParam(e){return e.map((e=>["object","function"].includes(typeof e)&&e.getStatInfo?e.getStatInfo():e))}static callApi(e,t,r,i){let n,o;const s=XR.getCurrentTimestamp(),a=r||[];try{return o=t.call(e,...a),o}catch(jN){throw n=jN,jN}finally{const t=XR.getCurrentTimestamp(),r=mP.doFinalParam([o,...a,e]);e.stat.setApiCallInfo(i,s,t,n,...r)}}static callWithTimeout(e,t){let r;const i=new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT),n=new Promise(((e,t)=>{r=t}));let o=null;return t&&(o=setTimeout((()=>{o&&clearTimeout(o),r(i)}),t)),Promise.race([e.finally((()=>{o&&clearTimeout(o)})),n])}static async callWithRetryTimes(e,t,r,i,n){let o=r>=0?r+1:-1,s=1,a=!1;for(;-1===o||o;){let c,u;try{u=await e(s)}catch(jN){c=jN,a=n&&n(c),console.warn("FunctionUtil","callWithRetryTimes, func:".concat(e.name,", isInterrupted:").concat(a,",")+"retryTimes:".concat(r,", left times:").concat(-1===o?-1:o-1,", tryNumber:").concat(s,", err: ").concat(c))}finally{if(!((c||!c&&t)&&!a&&(-1===o||--o>0))){if(!c)return u;throw c}{const e="number"==typeof i?i:i(c);await XR.sleep(e),s++}}}}}class gP{constructor(e){"boolean"!=typeof e?this.eventEmitter_=e:e&&(this.eventEmitter_=new VO)}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.removeListener(e,t):this.eventEmitter.removeAllListeners(e)}emit(e,t){this.eventEmitter.emit(e,t)}get eventEmitter(){return this.eventEmitter_}set eventEmitter(e){this.eventEmitter_=e}}class _P{constructor(e,t){"boolean"!=typeof e?this.logger_=e:e&&(this.logger_=iE.getLogger(t))}get logger(){return this.logger_}set logger(e){this.logger_=e}}class SP{constructor(e,t){"boolean"!=typeof e?this.stat_=e:e&&(this.stat_="boolean"!=typeof t?new wO(iE.getLogger(),t):new wO(iE.getLogger()))}set stat(e){this.stat_=e}get stat(){return this.stat_}}var vP,yP,IP,TP,RP,EP,bP,CP,AP,wP,kP,OP,PP,MP,DP,NP,UP,xP,LP,BP,VP,YP,jP,FP,HP,KP,zP,WP,GP,JP,qP,XP,QP=new class{constructor(){this.gen=(()=>{let e=0;return()=>e++})()}getSequence(){return this.gen()}};class $P{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{emitter:!1,logger:!1,stat:!1,config:!1},t=arguments.length>1?arguments[1]:void 0;i(this,"onCallbackMap_",new Map),this.identifiedID_=t||Symbol("identifiedID_".concat(QP.getSequence())),!1!==e.emitter&&(this.emitterAble_=new gP(e.emitter)),!1!==e.logger&&(this.loggerAble_=new _P(e.logger,this.identifiedID_)),!1!==e.stat&&(this.statisticAble_=new SP(e.stat,e.config))}on(e,t,r){var i;r?this.onWithTimeout(e,t):null===(i=this.emitterAble_)||void 0===i||i.on(e,t)}off(e,t,r){var i;r?this.offWithTimeout(e,t):null===(i=this.emitterAble_)||void 0===i||i.off(e,t)}emit(e,t){var r;null===(r=this.emitterAble_)||void 0===r||r.emit(e,t)}onWithTimeout(e,t){var r;const i=this.getOnCallback(e,t);null===(r=this.emitterAble_)||void 0===r||r.on(e,i)}offWithTimeout(e,t){var r;null===(r=this.emitterAble_)||void 0===r||r.off(e,this.getOffCallback(e,t)||t)}getOnCallback(e,t){const r=async r=>{const i=XR.getCurrentTimestamp();let n;try{await mP.callWithTimeout(Promise.resolve(await t&&t(r)),1e4),n=XR.getCurrentTimestamp()}catch(jN){n=i+5e3}finally{var o,s;null===(o=this.stat)||void 0===o||o.recordCallbackInfo(e.toString(),null===(s=this.getInfo())||void 0===s?void 0:s.moduleName,i,n,r,(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))}},i=this.onCallbackMap_.get(e)||[];return i.push({func:t,callbackFun:r}),this.onCallbackMap_.set(e,i),r}getOffCallback(e,t){const r=this.onCallbackMap_.get(e)||[],i=r.findIndex((e=>e.func===t));if(i>-1){var n;const e=null===(n=r[i])||void 0===n?void 0:n.callbackFun;return r.splice(i,1),e}return null}get stat(){var e;return null===(e=this.statisticAble_)||void 0===e?void 0:e.stat}get logger(){var e;return null===(e=this.loggerAble_)||void 0===e?void 0:e.logger}get eventEmitter(){if(!this.emitterAble_||!this.emitterAble_.eventEmitter)throw new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);return this.emitterAble_.eventEmitter}get identifiedID(){return this.identifiedID_}getStatInfo(){}}class ZP extends qc{constructor(e,t,r){super(e,t),this.captureResults=r}getMediaCaptureResult(){return this.captureResults}getMediaCaptureResultByType(e){var t;return null===(t=this.captureResults)||void 0===t?void 0:t.find((t=>t.type===e))}toString(){return'["code": '.concat(this.code,', "message": "').concat(this.message," : ").concat(JSON.stringify(this.captureResults),'"]')}}let eM=(vP=fP("Stream$getStreamInfo#StreamInfo"),yP=hP("Stream$play#Promise#string#{ objectFit?: string; muted: boolean; resolutionId?: string; playerElementHidden?: boolean }#string"),IP=fP("Stream$stop#void#StreamOption"),TP=hP("Stream$resume#Promise#StreamOption"),RP=fP("Stream$close#void#StreamOption"),EP=fP("Stream$muteAudio#boolean"),bP=fP("Stream$muteVideo#boolean"),CP=fP("Stream$unmuteAudio#boolean"),AP=fP("Stream$unmuteVideo#boolean"),wP=hP("Stream$setAudioOutput#Promise#string"),kP=fP("Stream$setAudioVolume#void#number"),OP=class extends $P{constructor(e){super({emitter:!0,logger:e.log||!0,stat:!0}),i(this,"module_","Stream"),this.isRemote_=e.isRemote,this.id_=XR.generateStreamId(),this.type_=e.type,this.isAuxiliary_="auxiliary"===e.type,this.tracks={video:new Map,audio:new Map},this.playDivContainers=new Map,this.traceHandler=this.playerStatusTrace.bind(this)}getStreamInfo(){return this.getStreamInfoImpl()}getStreamInfoImpl(){const e={videoProfiles:[]};for(const[r,i]of this.tracks[mO.TRACK_TYPE_VIDEO])if(i.getTrackType()===mO.TRACK_TYPE_VIDEO){const t={resolutionId:r,hasTrack:!!i.getTrack(),width:i.getTrackProfile().width,height:i.getTrackProfile().height,frameRate:i.getTrackProfile().frameRate,minBitrate:i.getTrackProfile().minBitrate,maxBitrate:i.getTrackProfile().maxBitrate};e.videoProfiles.push(t)}const t=this.getAnyAudioHRTCTrack();return t&&(e.audioProfile={sampleRate:t.getTrackProfile().sampleRate,channelCount:t.getTrackProfile().channelCount,bitrate:t.getTrackProfile().bitrate}),this.logger.info(this.module_,"getStreamInfoImpl success: ".concat(JSON.stringify(e))),e}getMaxResolutionHRTCTrack(e){let t;const r=Array.from(this.tracks[mO.TRACK_TYPE_VIDEO].values()),i=e?r:r.filter((e=>e.getTrack()));for(const n of i)t?t&&Math.max(n.getTrackProfile().width,n.getTrackProfile().height)-Math.max(t.getTrackProfile().width,t.getTrackProfile().height)>0&&(t=n):t=n;return t}getMaxResolutionProfile(e){if(0===e.size)return null;let t,r;for(const[i,n]of e)t?Math.max(n.width,n.height)-Math.max(t.width,t.height)>0&&(t=n,r=i):(t=n,r=i);return t?{resolutionId:r,width:t.width,height:t.height,frameRate:t.frameRate,minBitrate:t.minBitrate,maxBitrate:t.maxBitrate}:null}getHRTCTracks(e){const t=[],r=Array.from(this.tracks[mO.TRACK_TYPE_AUDIO].values()),i=Array.from(this.tracks[mO.TRACK_TYPE_VIDEO].values());if(!e)return[...r,...i];const n=void 0===e.hasTrack?r:r.filter((t=>!!t.getTrack()===e.hasTrack)),o=void 0===e.hasTrack?i:i.filter((t=>!!t.getTrack()===e.hasTrack));return e.mediaType?e.mediaType===mO.TRACK_TYPE_VIDEO?t.push(...o):t.push(...n):(t.push(...n),t.push(...o)),t}getHRTCTrackIds(e){const t=[];for(const r of this.getHRTCTracks(e))t.push(r.getTrackId());return t}getAnyVideoHRTCTrack(e){let t;return t=e?this.tracks[mO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(!0),t}getVideoHRTCTrack(e){var t;let r;return r=e?this.tracks[mO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(),null!==(t=r)&&void 0!==t&&t.getTrack()?r:null}getAnyAudioHRTCTrack(){return this.isAuxiliary_?this.tracks[mO.TRACK_TYPE_AUDIO].get("auxAudio"):this.tracks[mO.TRACK_TYPE_AUDIO].get("mainAudio")}getUninitializedAudioHRTCTrack(){const e=this.getAnyAudioHRTCTrack();return null!=e&&e.getTrack()?null:e}getUninitializedVideoHRTCTrack(e){var t;let r;return r=e?this.tracks[mO.TRACK_TYPE_VIDEO].get(e):this.getMaxResolutionHRTCTrack(!0),null!==(t=r)&&void 0!==t&&t.getTrack()?null:r}getAudioHRTCTrack(){const e=this.getAnyAudioHRTCTrack();return null!=e&&e.getTrack()?e:null}getUniqueId(){return this.id_}getInfo(){return{moduleName:"Stream",appId:"",roomId:"",userName:"",userId:"",domain:""}}startupPlay(e,t){this.client_.forEach((r=>{r.startupQoSReportPlay(e,t)}))}async play(e,t){const r=XR.getCurrentTimestamp();this.startupPlay(this.getUniqueId(),r),await this.playImpl(e,t)}async playImpl(e,t){let r;if(null!=t&&t.objectFit){if(!/^cover|contain|fill$/.test(t.objectFit))throw this.logger.error(this.module_,"invalid play options.objectFit: ".concat(t.objectFit)),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid play options.objectFit: ".concat(t.objectFit));r=t.objectFit}else r=this.isRemote_&&"auxiliary"===this.getType()?"contain":"cover";const i=!(null==t||!t.muted);if(this.logger.info(this.module_,"stream start to play with elementId: ".concat(e,", options.objectFit: ").concat(r,",options.muted: ").concat(i," resolutionId:").concat(null==t?void 0:t.resolutionId)),!e)throw this.logger.error(this.module_,"elementId:".concat(e," not a invalid HTMLElement Id")),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"elementId:".concat(e," not a invalid HTMLElement Id"));const n=document.getElementById(e);if(!n)throw this.logger.error(this.module_,"document.getElementById by elementId:".concat(e," failed")),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"document.getElementById by elementId:".concat(e," failed"));let o;const s=null!=t&&t.resolutionId?this.getVideoHRTCTrack(t.resolutionId):this.getMaxResolutionHRTCTrack(),a=s?s.getResolutionId():this.id_,c=this.playDivContainers.get(e);if(c){var u;o=c.HTMLElement,n.querySelector("#".concat(o.id))||n.appendChild(o),this.logger.info(this.module_,"get exist player div, key:".concat(e,", div: ").concat(null===(u=c.HTMLElement)||void 0===u?void 0:u.id))}else{o=document.createElement("div"),o.setAttribute("id","player_".concat(a)),o.style.width="100%",o.style.height="100%",o.style.position="relative",o.style.overflow="hidden",o.style["background-color"]="#000",n.appendChild(o);const t={HTMLElement:o,hasVideoTrack:!1,hasAudioTrack:!1};this.playDivContainers.set(e,t),this.logger.info(this.module_,"new player div, key:".concat(e,", div: ").concat(o.id))}o.style.display=null!=t&&t.playerElementHidden?"none":"block",await this.playTracks(e,o,r,i,null==t?void 0:t.resolutionId)}reportCanPlay(e){this.client_.forEach((t=>{t.startupQoSReportCanPlay(e)}))}playerStatusTrace(e){this.logger.debug(this.module_,"playerStatusTrace, ".concat(JSON.stringify(e))),null!=e&&e.event&&"playerCanplay"===e.event&&(e.id=this.getUniqueId(),this.reportCanPlay(e))}async playTracks(e,t,r,i,n){const o=[],s=this.isAuxiliary_?null:this.getAudioHRTCTrack(),a=n?this.getVideoHRTCTrack(n):this.getMaxResolutionHRTCTrack();null!=a&&a.getTrack()&&o.push(a.play(t,e,{objectFit:r,mirror:this.mirror_})),null!=s&&s.getTrack()&&o.push(s.play(t,e,{muted:i})),0!==o.length?(this.off(iC,this.traceHandler),this.on(iC,this.traceHandler),await Promise.all(o).then((r=>{const i=r.filter((e=>null!==e.error));i.length===o.length&&t&&t.remove();const n=r.filter((e=>null===e.error)),s=null==n?void 0:n.some((e=>e.trackType===mO.TRACK_TYPE_AUDIO)),a=null==n?void 0:n.some((e=>e.trackType===mO.TRACK_TYPE_VIDEO));if(this.playDivContainers.has(e)&&this.playDivContainers.set(e,{HTMLElement:t,hasAudioTrack:s,hasVideoTrack:a}),i.length>0)throw i[0].error}))):this.logger.warn(this.module_,"no available track for play")}stop(e){this.stopImpl(e)}stopImpl(e){var t;this.logger.info(this.module_,"stopImpl begin, option:".concat(JSON.stringify(e)));const r=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}),i=[];var n;(!e||e.video&&!e.resolutionIds?i.push(...r):e.video&&null!==(t=e.resolutionIds)&&void 0!==t&&t.length&&e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&i.push(t)})),i.forEach((e=>{e.stop()})),!e||e.audio)&&(null===(n=this.getAudioHRTCTrack())||void 0===n||n.stop())}async resume(e){await this.resumeImpl(e)}async resumeImpl(e){var t;this.logger.info(this.module_,"resumeImpl begin, option:".concat(JSON.stringify(e)));const r=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}),i=[];!e||e.video&&!e.resolutionIds?i.push(...r):e.video&&null!==(t=e.resolutionIds)&&void 0!==t&&t.length&&e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&i.push(t)}));const n=[];if(i.forEach((e=>{n.push(e.resume())})),!e||e.audio){const e=this.getAudioHRTCTrack();e&&n.push(e.resume())}await Promise.all(n)}close(e){this.closeImpl(e)}closeImpl(e){if(this.logger.info(this.module_,"closeImpl begin, options:".concat(JSON.stringify(e))),!e||e.video&&!e.resolutionIds&&e.audio){for(const e of this.getHRTCTracks({hasTrack:!0}))e.close();for(const e of this.playDivContainers.values())e.HTMLElement&&e.HTMLElement.remove();return this.playDivContainers.clear(),void DO.removeEventEmitter(this.eventEmitter)}if(e.video){var t;const r=[];if(null!==(t=e.resolutionIds)&&void 0!==t&&t.length)e.resolutionIds.forEach((e=>{const t=this.getVideoHRTCTrack(e);t&&r.push(t)}));else{const e=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO});r.push(...e)}r.forEach((e=>{const t=null==e?void 0:e.getElementId();if(e.close(),t){const e=this.playDivContainers.get(t);var r,i,n;if(e)if(e.hasVideoTrack=!1,this.logger.debug(this.module_,"closeImpl, elementId:".concat(t,", divInfo: ").concat(null===(r=e.HTMLElement)||void 0===r?void 0:r.id,", hasAudioTrack: ").concat(e.hasAudioTrack,", hasVideoTrack: ").concat(e.hasVideoTrack,"}")),!e.hasAudioTrack)null===(i=this.playDivContainers.get(t))||void 0===i||null===(n=i.HTMLElement)||void 0===n||n.remove(),this.playDivContainers.delete(t),this.logger.info(this.module_,"closeImpl, release elementId: ".concat(t))}}))}e.audio&&this.closeAudio();this.getHRTCTracks({hasTrack:!0}).every((e=>e.isClosed()))&&(DO.removeEventEmitter(this.eventEmitter),this.mediaStream=null)}closeAudio(){const e=this.getAudioHRTCTrack();if(e){const n=e.getElementId();if(e.close(),n){const e=this.playDivContainers.get(n);var t,r,i;if(e)if(e.hasAudioTrack=!1,this.logger.debug(this.module_,"closeAudio, elementId:".concat(n,", divInfo: ").concat(null===(t=e.HTMLElement)||void 0===t?void 0:t.id,", hasAudioTrack: ").concat(e.hasAudioTrack,", hasVideoTrack: ").concat(e.hasVideoTrack,"}")),!e.hasVideoTrack)null===(r=this.playDivContainers.get(n))||void 0===r||null===(i=r.HTMLElement)||void 0===i||i.remove(),this.playDivContainers.delete(n),this.logger.info(this.module_,"closeAudio, release elementId: ".concat(n))}}}muteAudio(){return this.muteAudioImpl()}muteAudioImpl(){try{const e=this.getAudioHRTCTrack();return!!e&&(e.muteTrack(),!0)}catch(jN){return this.logger.error(this.module_,"muteAudio failed: ".concat(jN)),!1}}muteVideo(){return this.muteVideoImpl()}muteVideoImpl(){try{if(!this.hasVideoTrack())return!1;for(const e of this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}))e.muteTrack();return!0}catch(jN){return this.logger.error(this.module_,"muteVideo failed: ".concat(jN)),!1}}unmuteAudio(){return this.unmuteAudioImpl()}unmuteAudioImpl(){try{const e=this.getAudioHRTCTrack();return!!e&&(e.unmuteTrack(),!0)}catch(jN){return this.logger.error(this.module_,"unmuteAudio failed: ".concat(jN)),!1}}unmuteVideo(){return this.unmuteVideoImpl()}unmuteVideoImpl(){try{if(!this.hasVideoTrack())return!1;for(const e of this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}))e.unmuteTrack();return!0}catch(jN){return this.logger.error(this.module_,"unmuteVideo failed: ".concat(jN)),!1}}getId(){var e;return null===(e=this.getMaxResolutionHRTCTrack(!0))||void 0===e?void 0:e.getTrackId()}getUserId(){return this.userId_}getType(){return this.type_}async setAudioOutput(e){return this.setAudioOutputImpl(e)}async setAudioOutputImpl(e){try{const t=this.getAudioHRTCTrack();t&&await t.setSinkId(e),this.stat.reportSwitchDevicesInfo(zC.OUTPUT_AUDIO,e,sA.SUCCESS)}catch(jN){throw this.stat.reportSwitchDevicesInfo(zC.OUTPUT_AUDIO,e,sA.FAIL),jN}}setAudioVolume(e){this.setAudioVolumeImpl(e)}setAudioVolumeImpl(e){const t=this.getAudioHRTCTrack();t&&t.setAudioVolume(e)}getAudioLevel(){const e=this.getAudioHRTCTrack();return e?e.getAudioLevel():0}hasAudioTrack(){return!!this.getAudioHRTCTrack()}hasVideoTrack(){return Array.from(this.tracks[mO.TRACK_TYPE_VIDEO].values()).filter((e=>e.getTrack())).length>0}isAuxiliary(){return this.isAuxiliary_}getAudioTrack(){const e=this.getAudioHRTCTrack();return e?e.getTrack():null}getVideoTrack(e){const t=this.getVideoHRTCTrack(e);return t?t.getTrack():null}getVideoFrame(e){const t=this.getVideoHRTCTrack(e);return t?t.getVideoFrame():null}on(e,t){super.on(e,t,-1===nC.indexOf(e.toString()))}off(e,t){super.off(e,t,-1===nC.indexOf(e.toString()))}async restart(e){var t;if(e)return void(await(null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.restart()));const r=[];for(const i of this.getHRTCTracks({hasTrack:!0}))r.push(i.restart());await Promise.all(r)}async rePlayAudio(){const e=this.getAudioHRTCTrack();e&&!e.isPlaying()&&await e.replay()}getStatInfo(){return{isRemote_:this.isRemote_,type_:this.type_,userId_:this.userId_,id_:this.id_,isAuxiliary_:this.isAuxiliary_}}getStatExtraInfo(){return{isRemote:this.isRemote_,id:this.id_,userId:this.userId_}}hasAudio(){var e;const t=!!(null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack());return this.logger.debug(this.module_,"hasAudio: ".concat(t)),t}hasVideo(){const e=this.hasVideoTrack();return this.logger.debug(this.module_,"hasVideo: ".concat(e)),e}},n(OP.prototype,"getStreamInfo",[vP],Object.getOwnPropertyDescriptor(OP.prototype,"getStreamInfo"),OP.prototype),n(OP.prototype,"play",[yP],Object.getOwnPropertyDescriptor(OP.prototype,"play"),OP.prototype),n(OP.prototype,"stop",[IP],Object.getOwnPropertyDescriptor(OP.prototype,"stop"),OP.prototype),n(OP.prototype,"resume",[TP],Object.getOwnPropertyDescriptor(OP.prototype,"resume"),OP.prototype),n(OP.prototype,"close",[RP],Object.getOwnPropertyDescriptor(OP.prototype,"close"),OP.prototype),n(OP.prototype,"muteAudio",[EP],Object.getOwnPropertyDescriptor(OP.prototype,"muteAudio"),OP.prototype),n(OP.prototype,"muteVideo",[bP],Object.getOwnPropertyDescriptor(OP.prototype,"muteVideo"),OP.prototype),n(OP.prototype,"unmuteAudio",[CP],Object.getOwnPropertyDescriptor(OP.prototype,"unmuteAudio"),OP.prototype),n(OP.prototype,"unmuteVideo",[AP],Object.getOwnPropertyDescriptor(OP.prototype,"unmuteVideo"),OP.prototype),n(OP.prototype,"setAudioOutput",[wP],Object.getOwnPropertyDescriptor(OP.prototype,"setAudioOutput"),OP.prototype),n(OP.prototype,"setAudioVolume",[kP],Object.getOwnPropertyDescriptor(OP.prototype,"setAudioVolume"),OP.prototype),OP),tM=(PP=hP("LocalStream$initialize#Promise"),MP=hP("LocalStream$addAudioTrackCapture#Promise#string"),DP=hP("LocalStream$addVideoTrackCapture#Promise#VideoCaptureOption"),NP=fP("LocalStream$setAudioProfile#void#string|RTCAudioProfile"),UP=hP("LocalStream$setVideoProfile#void#string|RTCVideoProfile"),xP=hP("LocalStream$addResolution#Promise#string|RTCVideoProfile#boolean"),LP=hP("LocalStream$removeResolution#Promise#string"),BP=fP("LocalStream$setScreenProfile#void#string|RTCScreenProfile"),VP=hP("LocalStream$switchDevice#Promise#string#string"),YP=hP("LocalStream$addTrack#Promise#MediaStreamTrack#string"),jP=hP("LocalStream$removeTrack#Promise#MediaStreamTrack#string"),FP=hP("LocalStream$replaceTrack#Promise#MediaStreamTrack#string#string"),HP=fP("LocalStream$bindScreenAudio2RelatedStream#void#LocalStream#boolean"),KP=hP("LocalStream$startAudioMixing#Promise#AudioMixOption"),zP=hP("LocalStream$stopAudioMixing#Promise"),WP=fP("LocalStream$pauseAudioMixing#void"),GP=fP("LocalStream$resumeAudioMixing#void"),JP=fP("LocalStream$setAudioMixingVolume#void#number"),qP=fP("LocalStream$setAudioMixingPosition#void#number"),XP=class extends eM{constructor(e){super({isRemote:!1,type:"local",log:null}),this.module_="LocalStream",this.userId_=e.userId,this.audio_=e.audio,this.microphoneId_=e.microphoneId,this.video_=e.video,this.cameraId_=e.cameraId,this.facingMode_=e.facingMode,this.screen_=e.screen,this.isAuxiliary_=!!this.screen_,this.screenAudio_=e.screenAudio,this.audioSource_=e.audioSource,this.videoSource_=e.videoSource,this.mirror_=e.mirror,this.client_=[],this.audioMixOption_={filePath:null,startTime:0,replace:!1,loop:!1,repeatCount:1},this.audioMixInfo_={audioMixState:SC.IDLE,audioCtx:null,mediaNode:null,sourceNode:null,buffer:null,destNode:null,gainNode:null,gainValue:.5,startAt:0,pauseAt:0,pauseDur:0,playAutoEnded:!1,totalDur:0},this.mutePackageData=new Uint8Array([255,241,80,128,3,223,252,222,2,0,76,97,118,99,53,56,46,55,53,46,49,48,48,0,66,32,8,193,24,56,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28,255,241,80,128,1,191,252,33,16,4,96,140,28]).buffer,this.muteSendInfo={audioMixState:SC.IDLE,audioCtx:null,mediaNode:null,sourceNode:null,destNode:null},this.screenShareMixInfo={bindStream:null,screenShareAudioNode:null,destNode:null,gainNode:null,gainValue:.5,status:SC.INIT,muteMainAudio:!1},this.videoProfiles_=new Map,this.videoContents=new Map,this.logger.info(this.module_,"new local stream, stream config: ".concat(JSON.stringify(e)))}setMediaStream(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaStream.addTrack(e)}getMediaStream(){return this.mediaStream}getLocalId(){return this.id_}async initialize(){return await this.initializeImpl()}setVideoContentHint(e){if("detail"!==e&&"motion"!==e&&"text"!==e){const e=new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"invalid input parameter type");throw this.logger.error(this.module_,"setVideoContentHint fail, errMsg: ".concat(e)),e}const t=this.getVideoTrack();t&&"contentHint"in t?(t.contentHint=e,this.logger.info(this.module_,"set video track contentHint to: ".concat(e))):this.logger.info(this.module_,"no video track or no video contentHint in track")}async reset(){this.closeImpl();for(const e of this.getHRTCTracks({hasTrack:!0})){const t=e.getTrack();t&&await this.removeTrack(t)}this.tracks[mO.TRACK_TYPE_VIDEO].clear(),this.tracks[mO.TRACK_TYPE_AUDIO].clear()}initAuxStreamWithTrack(e,t){const r=[];if(e){const t=new oP({streamType:gO.STREAM_TYPE_AUX,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:e,event:this.eventEmitter});this.tracks[mO.TRACK_TYPE_AUDIO].set("auxAudio",t),r.push({type:mO.TRACK_TYPE_AUDIO,track:e})}if(t){const e=new oP({streamType:gO.STREAM_TYPE_AUX,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});this.tracks[mO.TRACK_TYPE_VIDEO].set(e.getResolutionId(),e),r.push({type:mO.TRACK_TYPE_VIDEO,track:t})}return this.appendDefaultLocalTrack(this.getMaxResolutionProfile(this.videoProfiles_),this.audioProfile_),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",r)}async initAuxStream(){if(this.audioSource_||this.videoSource_)return this.initAuxStreamWithTrack(this.audioSource_,this.videoSource_);{var e,t,r,i;const n=new oP({streamType:gO.STREAM_TYPE_AUX,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:this.screenProfile_,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o=await n.initScreenShare(this.screenAudio_),s=null===(e=o.find((e=>e.error)))||void 0===e?void 0:e.error;if(s)throw this.logger.error(this.module_,"initAuxStream, fail, errMsg = ".concat(s)),s instanceof qc?new ZP(s.getCode(),s.getMsg(),o):s;this.stat.setMediaCaptureSucc(WC.AUX,null===(t=n.getTrack())||void 0===t?void 0:t.label),this.tracks[mO.TRACK_TYPE_VIDEO].set(n.getResolutionId(),n),this.setMediaStream(null===(r=o.find((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.track)))||void 0===r?void 0:r.track),this.setVideoContentHint("detail");const a=null===(i=o.find((e=>e.type===mO.TRACK_TYPE_AUDIO&&e.track)))||void 0===i?void 0:i.track;return a&&this.tracks[mO.TRACK_TYPE_AUDIO].set("auxAudio",new oP({streamType:gO.STREAM_TYPE_AUX,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:a,event:this.eventEmitter})),this.auxStreamStopByNativeHandler=()=>{this.close(),this.eventEmitter.removeListener(eC,this.auxStreamStopByNativeHandler)},this.eventEmitter.on(eC,this.auxStreamStopByNativeHandler),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",o)}}async initMainStreamWithCfg(){const e=this.getMaxResolutionProfile(this.videoProfiles_);return await this.addCaptureWithCfg(this.video_,this.audio_,e,this.audioProfile_,CC.main)}async initMainStream(){return DO.initDeviceChangedNotify(this.eventEmitter,!0),this.on(UC.CameraChanged,(e=>{"REMOVE"===e.state&&this.clearEffectiveDeviceId(e.deviceId,"videoInput")})),this.on(UC.RecordingDeviceChanged,(e=>{"REMOVE"===e.state&&this.client_.length>0&&this.client_[0].getPublishAudioSender()&&(this.startSendMutePackage(),this.clearEffectiveDeviceId(e.deviceId,"audioInput"))})),this.on(oC.CameraCapture,((e,t)=>{this.setCameraCaptureReport(e,t)})),this.audioSource_||this.videoSource_?this.initMainStreamWithTrack(this.audioSource_,this.videoSource_):await this.initMainStreamWithCfg()}async initializeImpl(){this.logger.info(this.module_,"initializeImpl begin");try{return await this.reset(),this.screen_?await this.initAuxStream():await this.initMainStream()}catch(jN){throw this.logger.error(this.module_,"initializeImpl fail, errMsg:".concat(jN)),"function"!=typeof jN.getMediaCaptureResult&&"function"==typeof jN.getCode?new ZP(jN.getCode(),jN.getMsg(),null):jN}}setCameraCaptureReport(e,t){this.client_.forEach((r=>{r.setCameraCaptureReport(e,t)}))}async addCaptureWithCfg(e,t,r,i,n){this.logger.info(this.module_,"addCaptureWithCfg begin, video:".concat(e,", audio:").concat(t,",")+"camera:".concat(this.getCurrentCameraId(),", microphone:").concat(this.getCurrentMicrophoneId(),",")+"videoProfileInfo:".concat(JSON.stringify(r),", audioProfile:").concat(JSON.stringify(i)));if((this.tracks&&this.tracks[mO.TRACK_TYPE_VIDEO].size)>=2){const e=new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"resolution count can not be greater than ".concat(2));throw this.logger.error(this.module_,"addCaptureWithCfg fail, errMsg is=".concat(e)),e}const o=[];let s,a;e&&(s=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:r,logger:this.logger,resolutionId:r?r.resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o.push(s.initVideoCapture(this.getCurrentCameraId()||this.facingMode_,n))),t&&(a=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:i,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o.push(a.initAudioCapture(this.getCurrentMicrophoneId())));const c=await Promise.all(o);let u=null;for(const l of c)if(l.error)u="".concat(u).concat(u?"":";").concat(l.error.getMsg());else{var d;if(l.type===mO.TRACK_TYPE_AUDIO)this.tracks[mO.TRACK_TYPE_AUDIO].set("mainAudio",a),this.stat.setMediaCaptureSucc(WC.AUDIO,a.getTrack().label);else Array.from(Array.from(this.tracks[mO.TRACK_TYPE_VIDEO].values()).values()).some((e=>e.getTrackMuted()))&&s.muteTrack(),this.tracks[mO.TRACK_TYPE_VIDEO].set(s.getResolutionId(),s),this.stat.setMediaCaptureSucc(WC.VIDEO,null===(d=s.getTrack())||void 0===d?void 0:d.label),r&&this.videoProfiles_.set(s.getResolutionId(),r),this.videoContents.set(s.getResolutionId(),n);this.setMediaStream(l.track),this.appendDefaultLocalTrack(r,i),this.updateEffectiveDeviceInfo(l)}if(u){const e=new ZP(Gc.RTC_ERR_CODE_INVALID_OPERATION,"browser initialize capture fail, ".concat(u),c);throw this.logger.error(this.module_,"addCaptureWithCfg fail, errMsg= ".concat(e)),e}return this.logger.info(this.module_,"addCaptureWithCfg success, camera:".concat(this.getCurrentCameraId(),", microphone:").concat(this.getCurrentMicrophoneId())),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",c)}appendDefaultLocalTrack(e,t){if(!this.getAnyAudioHRTCTrack()){const e=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:t,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter});e.setTrackContentType(CC.main),this.tracks[mO.TRACK_TYPE_AUDIO].set("mainAudio",e),this.logger.info(this.module_,"addDefaultEmptyTrack success, audioTrack:".concat(e.getResolutionId(),",")+"track profile:".concat(JSON.stringify(e.getTrackProfile())))}if(!this.getAnyVideoHRTCTrack(null==e?void 0:e.resolutionId)){const t=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:e,logger:this.logger,resolutionId:e?e.resolutionId:this.generateResolutionId(),event:this.eventEmitter});t.setTrackContentType(CC.main),this.tracks[mO.TRACK_TYPE_VIDEO].set(t.getResolutionId(),t),this.logger.info(this.module_,"addDefaultEmptyTrack success, videoTrack:".concat(t.getResolutionId(),",")+"track profile:".concat(JSON.stringify(t.getTrackProfile())))}}generateResolutionId(){return this.id_+"-"+XR.generateRandomId(8,16)}initMainStreamWithTrack(e,t){const r=[];if(e){const t=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:e,event:this.eventEmitter});this.tracks[mO.TRACK_TYPE_AUDIO].set("mainAudio",t),r.push({type:mO.TRACK_TYPE_AUDIO,track:e})}if(t){const e=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});this.tracks[mO.TRACK_TYPE_VIDEO].set(e.getResolutionId(),e),r.push({type:mO.TRACK_TYPE_VIDEO,track:t})}return this.appendDefaultLocalTrack(this.getMaxResolutionProfile(this.videoProfiles_),this.audioProfile_),new ZP(Gc.RTC_ERR_CODE_SUCCESS,"",r)}async addAudioTrackCapture(e){return await this.addAudioTrackCaptureImpl(e)}async addAudioTrackCaptureImpl(e){var t;this.logger.info(this.module_,"addAudioTrackCaptureImpl, microphoneId: ".concat(e));const r=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,trackProfile:this.audioProfile_,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),i=await r.initAudioCapture(e||this.microphoneId_);if(i.error)throw this.logger.error(this.module_,"addAudioTrackCaptureImpl fail, errMsg: ".concat(i.error)),i.error;return this.stat.setMediaCaptureSucc(WC.AUDIO,null===(t=i.track)||void 0===t?void 0:t.label),this.updateEffectiveDeviceInfo(i),await this.addTrackImpl(i.track),i.track}async addVideoTrackCapture(e){return await this.addVideoTrackCaptureImpl(e)}async addVideoTrackCaptureImpl(e){var t;this.logger.info(this.module_,"addVideoTrackCaptureImpl, option: ".concat(JSON.stringify(e)));const r=null==e?void 0:e.resolutionId,i=r?this.videoProfiles_.get(r):this.getMaxResolutionProfile(this.videoProfiles_),n=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!1,trackProfile:i,logger:this.logger,resolutionId:this.generateResolutionId(),event:this.eventEmitter}),o=(null==e?void 0:e.cameraId)||this.cameraId_||this.facingMode_,s=await n.initVideoCapture(o,r?this.videoContents.get(r):CC.main);if(s.error)throw this.logger.error(this.module_,"addVideoTrackCaptureImpl fail, errMsg: ".concat(s.error)),s.error;return this.updateEffectiveDeviceInfo(s),this.stat.setMediaCaptureSucc(WC.AUDIO,null===(t=s.track)||void 0===t?void 0:t.label),await this.addTrackImpl(s.track,r),s.track}updateEffectiveDeviceInfo(e){e.type===mO.TRACK_TYPE_VIDEO?(this.effectiveCameraId_=e.track.getSettings().deviceId,this.logger.info(this.module_,"updateEffectiveDeviceInfo, effectiveCameraId_: ".concat(this.effectiveCameraId_))):e.type===mO.TRACK_TYPE_AUDIO&&(this.effectiveMicrophoneId_=e.track.getSettings().deviceId,this.logger.info(this.module_,"updateEffectiveDeviceInfo, effectiveMicrophoneId_: ".concat(this.effectiveMicrophoneId_)))}getCurrentCameraId(){return this.cameraId_||this.effectiveCameraId_}getCurrentMicrophoneId(){return this.microphoneId_||this.effectiveMicrophoneId_}getAudioSendBitrate(){const e=this.getAudioHRTCTrack();return e?e.getTrackProfile().bitrate:0}isAudioMuted(){const e=this.getAudioHRTCTrack();return!e||e.getTrackMuted()}isVideoMuted(e){const t=this.getVideoHRTCTrack(e);return!t||t.getTrackMuted()}setAudioProfile(e){this.setAudioProfileImpl(e)}setAudioProfileImpl(e){const t=this.getAudioHRTCTrack();this.audioProfile_=e,null==t||t.setTrackProfile(e)}getVideoMaxBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.maxBitrate:0}getVideoMaxSendBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.maxBitrate<35e4?r.maxBitrate-2e4:r.maxBitrate:0}getVideoMiniBitrate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.minBitrate:0}getVideoWidth(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.width:0}getVideoHeight(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.height:0}getVideoFrameRate(e){var t;const r=null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile();return r?r.frameRate:0}getVideoProfile(e){var t;return null===(t=this.getVideoHRTCTrack(e))||void 0===t?void 0:t.getTrackProfile()}async setVideoProfile(e,t){await this.setVideoProfileImpl(e,t)}async addResolution(e,t){return await this.addResolutionImpl(e,t)}async addResolutionImpl(e,t){try{if(this.videoSource_||this.audioSource_)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"localStream created by videoSource or audioSource");const r=ZO.formatVideoProfile(e),i={resolutionId:this.generateResolutionId(),width:r.width,height:r.height,frameRate:r.frameRate,minBitrate:r.minBitrate,maxBitrate:r.maxBitrate};this.logger.info(this.module_,"addResolutionImpl begin, profile:".concat(JSON.stringify(i)," ")),await this.addCaptureWithCfg(!0,t,i,this.audioProfile_,CC.slides);for(const e of this.client_)await e.publish(this);return this.logger.info(this.module_,"addResolutionImpl success"),i}catch(jN){throw this.logger.error(this.module_,"addResolutionImpl fail, errMsg:".concat(jN)),"function"!=typeof jN.getMediaCaptureResult?new ZP(jN.getCode(),jN.getMsg(),null):jN}}async removeResolution(e){return this.removeResolutionImpl(e)}async removeResolutionImpl(e){this.logger.info(this.module_,"removeResolutionImpl begin, resolutionId:".concat(e));const t=this.getVideoHRTCTrack(e);if(!t)throw this.logger.error(this.module_,"removeResolutionImpl, resolutionId:".concat(e," not found ")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"resolutionId:".concat(e," not found"));this.tracks[mO.TRACK_TYPE_VIDEO].delete(e),t.removeTrack();const r=this.getHRTCTracks({mediaType:mO.TRACK_TYPE_VIDEO});r&&0!==r.length||this.tracks[mO.TRACK_TYPE_AUDIO].delete("mainAudio");for(const i of this.client_)await i.publish(this);this.logger.info(this.module_,"removeResolutionImpl success, resolutionId:".concat(e))}async setVideoProfileImpl(e,t){var r;this.logger.info(this.module_,"setVideoProfile begin, profile: ".concat(JSON.stringify(e)));const i=this.getVideoHRTCTrack(t),n=ZO.formatVideoProfile(e);if(!i){const e=this.generateResolutionId();return void this.videoProfiles_.set(e,n)}const o={};XR.isSupportConstraints("aspectRatio")&&(o.aspectRatio={ideal:n.width/n.height}),o.width={ideal:n.width},o.height={ideal:n.height},o.frameRate={ideal:n.frameRate},await(null===(r=i.getTrack())||void 0===r?void 0:r.applyConstraints(o).then((()=>{this.logger.info(this.module_,"setVideoProfile, constraint: ".concat(JSON.stringify(i.getTrack().getConstraints()))),i.setLocalProfileByTrack(i.getTrack()),this.videoProfiles_.set(i.getResolutionId(),n),this.client_.forEach((async e=>{if(e){const t=e.getMainStreamSenderByTrack(i.getTrackId());await e.setSendBitrate(t,this.getVideoMaxSendBitrate(i.getResolutionId()),this.isAuxiliary()?"auxVideo":"mainVideo"),await e.publish(this)}}))})))}getScreenSendBitrate(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().bitrate:0}getScreenWidth(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().width:0}getScreenHeight(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().height:0}getScreenFrameRate(){const e=this.getVideoHRTCTrack();return e?e.getTrackProfile().frameRate:0}setScreenProfile(e){this.setScreenProfileImpl(e)}setScreenProfileImpl(e){const t=this.getVideoHRTCTrack();this.screenProfile_=e,t&&t.setTrackProfile(e)}async switchVideoDevice(e){var t;this.logger.info(this.module_,"switchVideoDevice begin, cameraId is ".concat(e));const r=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO});if(0===r.length)return void this.logger.error(this.module_,"switchVideoDevice failed, no video tracks");const i=[];for(const d of r){var n;null===(n=this.mediaStream)||void 0===n||n.removeTrack(d.getTrack()),d.setTrackProfile(this.videoProfiles_.get(d.getResolutionId())),i.push(d.initVideoCapture(e,d.getTrackContentType()))}const o=await Promise.all(i),s=[];for(const d of o){var a,c,u;if(d.error)throw d.error;null===(a=this.mediaStream)||void 0===a||a.addTrack(d.track);const e=d.track.getConstraints(),t=d.track.getSettings(),i="number"==typeof e.width?e.width:(null===(c=e.width)||void 0===c?void 0:c.ideal)||t.width,n="number"==typeof e.height?e.height:(null===(u=e.height)||void 0===u?void 0:u.ideal)||t.height,o=r.find((e=>{const t=e.getTrackProfile();return t.width===i&&t.height===n}));for(const r of this.client_){const e=r.getMainStreamSenderByTrack(null==o?void 0:o.getTrackId());e&&s.push(e.replaceTrack(d.track))}}if(o.length&&(this.cameraId_=e,this.effectiveCameraId_=e),0!==s.length){this.stat.setMediaCaptureSucc(WC.VIDEO,null===(t=o[0].track)||void 0===t?void 0:t.label),await Promise.all(s);for(const e of this.client_)await e.publish(this);this.logger.info(this.module_,"switchVideoDevice success")}else this.logger.debug(this.module_,"switchVideoDevice, no need replace sender track")}async switchAudioDevice(e){var t,r,i;this.logger.info(this.module_,"switchAudioDevice begin, microphoneId is ".concat(e));const n=this.getAudioHRTCTrack();if(!n)return void this.logger.error(this.module_,"switchAudioDevice failed, no audio tracks");null===(t=this.mediaStream)||void 0===t||t.removeTrack(n.getTrack());const o=await n.initAudioCapture(e);if(o.error)throw o.error;this.stat.setMediaCaptureSucc(WC.AUDIO,null===(r=o.track)||void 0===r?void 0:r.label),this.replaceMixAudioTrack(o.track),null===(i=this.mediaStream)||void 0===i||i.addTrack(o.track);const s=[];this.client_.forEach((e=>{const t=e.getPublishAudioSender();t&&s.push(t.replaceTrack(this.getPublishAudioTrack()))})),0===s.length&&this.logger.info(this.module_,"switchAudioDevice, no need replace sender track"),this.microphoneId_=e,this.effectiveMicrophoneId_=e,await Promise.all(s)}async switchDevice(e,t){return await this.switchDeviceImpl(e,t)}async switchDeviceImpl(e,t){return new Promise(((r,i)=>{if(this.logger.info(this.module_,"switchDeviceImpl begin, type:".concat(e,", deviceId:").concat(t)),e===mO.TRACK_TYPE_AUDIO){if("default"!==t&&(this.effectiveMicrophoneId_===t||this.audioSource_))return void r();this.switchAudioDevice(t).then((()=>{this.stopSendMutePackage(),this.stat.reportSwitchDevicesInfo(zC.INPUT_AUDIO,t,sA.SUCCESS),r()})).catch((e=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_AUDIO,t,sA.FAIL),this.logger.error(this.module_,"switchDevice failed, errmsg= ".concat(e)),i(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR))}))}else if(e===mO.TRACK_TYPE_VIDEO){if(this.effectiveCameraId_===t||this.videoSource_)return void r();this.switchVideoDevice(t).then((()=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_VIDEO,t,sA.SUCCESS),r()})).catch((e=>{this.stat.reportSwitchDevicesInfo(zC.INPUT_VIDEO,t,sA.FAIL),this.logger.error(this.module_,"switchDevice failed, errmsg= ".concat(e)),i(new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR))}))}else i(new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"invalid media type:".concat(e)))}))}async addTrack(e,t){return await this.addTrackImpl(e,t)}async addTrackImpl(e,t){var r;if(!e)throw this.logger.error(this.module_,"addTrack, track is null"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"track is null");if(this.logger.info(this.module_,"addTrackImpl begin, resolutionId:".concat(t,", physical track id:").concat(e.id)),e.kind===mO.TRACK_TYPE_AUDIO){const r=this.getUninitializedAudioHRTCTrack();if(!r)throw this.logger.error(this.module_,"addTrackImpl failed, audio track already exist"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"audio track already exist");{await r.replaceTrack(e),this.replaceMixAudioTrack(e);const i=this.getAnyVideoHRTCTrack(t),n=null!=i&&i.isPlaying()?i:null;n&&await this.play(n.getElementId(),{objectFit:n.getObjectFit(),muted:n.getTrackMuted(),resolutionId:n.getResolutionId()}),this.logger.info(this.module_,"addTrackImpl success , track type is audio,"+"physical track id:".concat(e.id))}}else{const r=this.getUninitializedVideoHRTCTrack(t);if(!r)throw this.logger.error(this.module_,"addTrackImpl failed, video track already exist"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"video track already exist");{await r.replaceTrack(e);const t=this.getAnyAudioHRTCTrack(),i=null!=t&&t.isPlaying()?t:null;i&&await this.play(i.getElementId(),{objectFit:i.getObjectFit(),muted:i.getTrackMuted(),resolutionId:null}),this.logger.info(this.module_,"addTrackImpl success , track type is video,"+"physical track id:".concat(e.id))}}null===(r=this.mediaStream)||void 0===r||r.addTrack(e);for(const i of this.client_)i&&await i.publish(this)}async removeTrack(e){return await this.removeTrackImpl(e)}async removeTrackImpl(e){var t;if(!e)throw this.logger.error(this.module_,"removeTrack, track is null"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"track is null");if(e.kind===mO.TRACK_TYPE_AUDIO)for(const[n,o]of this.tracks[mO.TRACK_TYPE_AUDIO]){var r;e.id===(null==o||null===(r=o.getTrack())||void 0===r?void 0:r.id)&&(o.removeTrack(),this.tracks[mO.TRACK_TYPE_AUDIO].set(n,o),this.logger.info(this.module_,"removeTrackImpl success , track type is ".concat(o.getTrackType(),",")+"physical track id:".concat(e.id)))}else for(const[n,o]of this.tracks[mO.TRACK_TYPE_VIDEO]){var i;e.id===(null==o||null===(i=o.getTrack())||void 0===i?void 0:i.id)&&(o.removeTrack(),this.tracks[mO.TRACK_TYPE_VIDEO].set(n,o),this.logger.info(this.module_,"removeTrackImpl success , track type is ".concat(o.getTrackType(),",")+"physical track id:".concat(e.id)))}null===(t=this.mediaStream)||void 0===t||t.removeTrack(e);for(const n of this.client_)n&&await n.publish(this)}async replaceTrack(e,t,r){return await this.replaceTrackImpl(e,t,r)}async replaceTrackImpl(e,t,r){var i,n,o;if(!e)throw this.logger.error(this.module_,"replaceTrack, track is null"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);let s;t===mO.TRACK_TYPE_AUDIO?(s=this.getAudioHRTCTrack(),this.replaceMixAudioTrack(e)):t===mO.TRACK_TYPE_VIDEO&&(s=this.getVideoHRTCTrack(r)),null===(i=this.mediaStream)||void 0===i||i.removeTrack(s.getTrack()),null===(n=this.mediaStream)||void 0===n||n.addTrack(e),await(null===(o=s)||void 0===o?void 0:o.replaceTrack(e));for(const a of this.client_)a&&await a.publish(this)}addClient(e){this.client_=this.client_.filter((t=>t&&t.getSymbol()!==e.getSymbol())),e&&this.client_.push(e)}removeClient(e){e&&-1!==this.client_.indexOf(e)&&this.client_.splice(this.client_.indexOf(e),1)}muteAudio(){return!!super.muteAudio()&&(this.stat.reportAudioMuteInfo(1,!0),this.client_.forEach((e=>{e.changeStreamMuteStatusNotify(!0,mO.TRACK_TYPE_AUDIO),e.reportAudioMuteInfo(1,!0)})),!0)}muteVideo(){return!!super.muteVideo()&&(this.stat.reportVideoMuteInfo(this.userId_,!0),this.client_.forEach((e=>{var t;const r=(null===(t=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}))||void 0===t?void 0:t.length)>1;e.changeStreamMuteStatusNotify(!0,mO.TRACK_TYPE_VIDEO,this.isAuxiliary_?CC.desktop:CC.main,r),e.reportVideoMuteInfo(this.userId_,!0)})),!0)}unmuteAudio(){return!!super.unmuteAudio()&&(this.stat.reportAudioMuteInfo(1,!1),this.client_.forEach((e=>{e.changeStreamMuteStatusNotify(!1,mO.TRACK_TYPE_AUDIO),e.reportAudioMuteInfo(1,!1)})),!0)}unmuteVideo(){return!!super.unmuteVideo()&&(this.stat.reportVideoMuteInfo(this.userId_,!1),this.client_.forEach((e=>{var t;const r=(null===(t=this.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}))||void 0===t?void 0:t.length)>1;e.changeStreamMuteStatusNotify(!1,mO.TRACK_TYPE_VIDEO,this.isAuxiliary_?CC.desktop:CC.main,r),e.reportVideoMuteInfo(this.userId_,!1)})),!0)}closeImpl(e){!1!==(null==e?void 0:e.audio)&&(this.closeScreenShareAudio(),this.isAuxiliary()||this.audioMixInfo_.playAutoEnded||this.audioMixInfo_.audioMixState===SC.IDLE||this.audioMixInfo_.audioMixState===SC.INIT||this.stopAudioMixing()),super.closeImpl(e)}clearEffectiveDeviceId(e,t){this.logger.info(this.module_,"clearEffectiveDeviceId, Input:".concat(e,", type:").concat(t)),"audioInput"===t?this.effectiveMicrophoneId_===e&&(this.effectiveMicrophoneId_="",this.logger.info(this.module_,"clearEffectiveDeviceId, audioInput:".concat(e))):"videoInput"===t&&this.effectiveCameraId_===e&&(this.effectiveCameraId_="",this.logger.info(this.module_,"clearEffectiveDeviceId, videoInput:".concat(e)))}startSendMutePackage(){var e;this.logger.debug(this.module_,"start SendMutePackage");const t=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();if(!t||"ended"!==t.readyState)return void this.logger.info(this.module_,"removed device is not in use, startSendMutePackage end");if(this.muteSendInfo.audioMixState!=SC.IDLE||!this.client_[0].getPublishAudioSender())return void this.logger.info(this.module_,"the condition is not met, startSendMutePackage end");this.muteSendInfo.audioCtx||(this.muteSendInfo.audioCtx=new AudioContext);let r=this.mutePackageData.slice(0);this.muteSendInfo.audioCtx.decodeAudioData(r,(e=>{var t;this.muteSendInfo.destNode=this.muteSendInfo.audioCtx.createMediaStreamDestination(),this.muteSendInfo.sourceNode=this.muteSendInfo.audioCtx.createBufferSource(),this.muteSendInfo.sourceNode.buffer=e,this.muteSendInfo.sourceNode.connect(this.muteSendInfo.destNode),this.muteSendInfo.sourceNode.loop=!0,this.muteSendInfo.sourceNode.start(0,0),this.muteSendInfo.audioMixState=SC.PLAY,null===(t=this.client_[0].getPublishAudioSender())||void 0===t||t.replaceTrack(this.muteSendInfo.destNode.stream.getAudioTracks()[0]),this.logger.info(this.module_,"startSendMutePackage success"),r=null}),(()=>{this.muteSendInfo.audioMixState=SC.IDLE,this.logger.info(this.module_,"startSendMutePackage failed"),r=null}))}stopSendMutePackage(){var e,t,r;this.logger.info(this.module_,"stopSendMutePackage begin"),this.muteSendInfo.audioMixState===SC.PLAY?(null===(e=this.muteSendInfo.mediaNode)||void 0===e||e.connect(this.muteSendInfo.destNode),null===(t=this.muteSendInfo.sourceNode)||void 0===t||t.stop(),null===(r=this.muteSendInfo.sourceNode)||void 0===r||r.disconnect(),this.muteSendInfo.sourceNode=null,this.muteSendInfo.audioMixState=SC.IDLE):this.logger.info(this.module_,"stopSendMutePackage end")}bindScreenAudio2RelatedStream(e,t){this.bindScreenAudio2RelatedStreamImpl(e,t)}bindScreenAudio2RelatedStreamImpl(e,t){if(this.logger.info(this.module_,"bindScreenAudio2RelatedStreamImpl, streamId: ".concat(e.getId())),t&&!e.hasAudioTrack()){const t=this.getAudioTrack();if(t){const r=new oP({streamType:gO.STREAM_TYPE_MAIN,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!1,logger:this.logger,resolutionId:this.generateResolutionId(),track:t,event:this.eventEmitter});e.tracks[mO.TRACK_TYPE_AUDIO].set("mainAudio",r)}}this.screenShareMixInfo.bindStream=e,e.screenShareMixInfo.bindStream=this;this.mixScreenAudio(t)||(this.screenShareMixInfo.bindStream=null,e.screenShareMixInfo.bindStream=null)}mixScreenAudio(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const r=this.screenShareMixInfo.bindStream;if(!this.isAuxiliary()||null==r||!r.getAudioHRTCTrack()||!this.getAudioHRTCTrack())return this.logger.error(this.module_,"mixScreenAudio2MainStreamAudio failed, isAuxiliary: ".concat(this.isAuxiliary()," ,main stream or audio track is null")),!1;if(this.screenShareMixInfo.status=SC.PLAY,!r.audioMixInfo_.audioCtx){var i;r.audioMixInfo_.audioCtx=new AudioContext,r.audioMixInfo_.destNode=r.audioMixInfo_.audioCtx.createMediaStreamDestination();const e=null===(i=r.getAudioHRTCTrack())||void 0===i?void 0:i.getTrack();e&&(r.audioMixInfo_.mediaNode=r.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),r.audioMixInfo_.mediaNode.connect(r.audioMixInfo_.destNode))}t&&(r.audioMixInfo_.mediaNode.disconnect(r.screenShareMixInfo.destNode),this.logger.info(this.module_,"mixScreenAudio2MainStreamAudio, only play screen share audio stream"));const n=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();return this.screenShareMixInfo.screenShareAudioNode=r.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([n])),this.screenShareMixInfo.destNode=r.audioMixInfo_.destNode,this.screenShareMixInfo.gainNode=r.audioMixInfo_.audioCtx.createGain(),this.screenShareMixInfo.gainNode.gain.value=this.screenShareMixInfo.gainValue,this.screenShareMixInfo.screenShareAudioNode.connect(this.screenShareMixInfo.gainNode),this.screenShareMixInfo.gainNode.connect(this.screenShareMixInfo.destNode),this.screenShareMixInfo.muteMainAudio=t,!0}getPublishAudioTrack(){var e;if(this.isAuxiliary()){if(this.screenShareMixInfo.destNode&&this.screenShareMixInfo.destNode.stream){const e=this.screenShareMixInfo.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}else{const e=this.screenShareMixInfo.bindStream;if(e){const t=e.client_.length>0&&e.client_[0].getPublishVideoSender(gO.STREAM_TYPE_AUX).length,r=this.audioMixInfo_.audioMixState===SC.PAUSE||this.audioMixInfo_.audioMixState===SC.PLAY;if((t||r)&&this.audioMixInfo_.destNode&&this.audioMixInfo_.destNode.stream){const e=this.audioMixInfo_.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}else if(this.audioMixInfo_.destNode&&this.audioMixInfo_.destNode.stream){const e=this.audioMixInfo_.destNode.stream.getAudioTracks();if(e&&e.length>0)return e[0]}}return null===(e=super.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack()}async resumeMixScreenAudio(){const e=this.screenShareMixInfo.bindStream;if(!(this.isAuxiliary()&&e&&this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.destNode))return void this.logger.info(this.module_,"cannot resumeMixScreenAudio, isAuxiliary: ".concat(this.isAuxiliary()));this.screenShareMixInfo.gainNode.connect(this.screenShareMixInfo.destNode);const t=e.client_.length>0&&e.client_[0].getPublishAudioSender(),r=this.client_.length>0&&this.client_[0].getPublishVideoSender(gO.STREAM_TYPE_AUX).length;t&&r&&await e.client_[0].getPublishAudioSender().replaceTrack(this.getPublishAudioTrack())}async stopMixScreenAudio(){this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.destNode?this.screenShareMixInfo.gainNode.disconnect(this.screenShareMixInfo.destNode):this.logger.info(this.module_,"stopScreenAudio gainNode or destNode is null")}setAudioVolume(e){if(this.isAuxiliary()){if(!this.screenShareMixInfo.bindStream||this.screenShareMixInfo.status!==SC.PLAY)return void this.logger.error(this.module_,"setScreenAudioVolume failed for play status error");const t=e/100;this.logger.info(this.module_,"setScreenAudioVolume: "+t),this.screenShareMixInfo.gainNode.gain.value=t,this.screenShareMixInfo.gainValue=t}else super.setAudioVolume(e)}closeScreenShareAudio(){if(this.isAuxiliary())this.screenShareMixInfo.gainNode&&this.screenShareMixInfo.gainNode.disconnect(),this.screenShareMixInfo.screenShareAudioNode&&this.screenShareMixInfo.screenShareAudioNode.disconnect(),this.screenShareMixInfo.gainNode=null,this.screenShareMixInfo.gainValue=.5,this.screenShareMixInfo.screenShareAudioNode=null,this.screenShareMixInfo.bindStream=null,this.screenShareMixInfo.status=SC.INIT;else{const e=this.screenShareMixInfo.bindStream;if(!e)return void this.logger.debug(this.module_,"closeScreenShareAudio, no need closeScreenShareAudio, aux stream is null");e.closeScreenShareAudio(),this.screenShareMixInfo.bindStream=null}}async startAudioMixing(e){await this.startAudioMixingImpl(e),this.eventEmitter.emit(rC),this.logger.info(this.module_,"emit ".concat(rC," at startAudioMixing"))}async startAudioMixingImpl(e){var t,r;if(this.logger.info(this.module_,"startAudioMixing start at: "+e.startTime),this.checkAudioMixingParameter(),this.audioMixInfo_.audioMixState===SC.IDLE&&this.initIdleAudioMixInfo(),this.audioMixInfo_.audioMixState!==SC.INIT)throw this.logger.error(this.module_,"startAudioMixing status: ".concat(this.audioMixInfo_.audioMixState)),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"startAudioMixing status: ".concat(this.audioMixInfo_.audioMixState));(this.setAudioMixOption(e),this.audioMixOption_.replace)?this.logger.info(this.module_,"startAudioMixing: replace"):null===(r=this.audioMixInfo_.mediaNode)||void 0===r||r.connect(this.audioMixInfo_.destNode);await(null===(t=this.client_[0].getPublishAudioSender())||void 0===t?void 0:t.replaceTrack(this.audioMixInfo_.destNode.stream.getAudioTracks()[0]));try{const e=await LO.fetch(this.audioMixOption_.filePath);await this.audioMixInfo_.audioCtx.decodeAudioData(e.data,(e=>{this.audioMixInfo_.startAt=XR.getCurrentTimestamp(),this.audioMixInfo_.pauseAt=0,this.audioMixInfo_.pauseDur=0,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.totalDur=0,this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at startAudioMixingImpl")))},this.audioMixInfo_.sourceNode.buffer=e,this.audioMixInfo_.buffer=e,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode),this.audioMixInfo_.audioMixState=SC.PLAY,this.logger.info(this.module_,"startAudioMixing, duration: ".concat(this.getAudioMixingDuration())),this.doAudioMixing(),this.logger.info(this.module_,"startAudioMixing end")}),(e=>{throw this.logger.error(this.module_,"startAudioMixing, decode audio failed"),e}))}catch(jN){var i,n,o;if(this.logger.error(this.module_,"startAudioMixing failed: ".concat(jN)),this.audioMixInfo_.audioMixState=SC.INIT,!this.audioMixOption_.replace)null===(o=this.audioMixInfo_.mediaNode)||void 0===o||o.disconnect(this.audioMixInfo_.destNode);throw null===(i=this.client_[0].getPublishAudioSender())||void 0===i||i.replaceTrack(null===(n=this.getAudioHRTCTrack())||void 0===n?void 0:n.getTrack()),jN}}doAudioMixing(){if(this.audioMixOption_.repeatCount>1){if(this.audioMixOption_.startTime>=this.getAudioMixingDuration())throw this.logger.error(this.module_,"startAudioMixing: ".concat(this.audioMixInfo_.audioMixState)),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"startAudioMixing: not valid startTime");this.audioMixInfo_.sourceNode.loop=!0;const e=this.audioMixOption_.repeatCount*this.getAudioMixingDuration()-this.audioMixOption_.startTime;this.audioMixInfo_.totalDur=e,this.audioMixInfo_.sourceNode.start(0,this.audioMixOption_.startTime/1e3,e/1e3)}else this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixOption_.loop?this.audioMixInfo_.totalDur=1/0:(this.getAudioMixingDuration()<=this.audioMixOption_.startTime&&(this.logger.info(this.module_,"startAudioMixing, bookmark: ".concat(this.audioMixOption_.startTime," invalid and reset to begin.")),this.audioMixOption_.startTime=0),this.audioMixInfo_.totalDur=this.getAudioMixingDuration()-this.audioMixOption_.startTime),this.audioMixInfo_.sourceNode.start(0,this.audioMixOption_.startTime/1e3)}setAudioMixOption(e){e.replace||(e.replace=!1),e.startTime||(e.startTime=0),e.loop||(e.loop=!1),e.repeatCount&&!e.loop||(e.repeatCount=0),this.audioMixOption_=e}initIdleAudioMixInfo(){if(!this.audioMixInfo_.audioCtx){var e;this.audioMixInfo_.audioCtx=new AudioContext,this.audioMixInfo_.destNode=this.audioMixInfo_.audioCtx.createMediaStreamDestination();const t=null===(e=this.getAudioHRTCTrack())||void 0===e?void 0:e.getTrack();t&&(this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([t])))}this.audioMixInfo_.gainNode=this.audioMixInfo_.audioCtx.createGain(),this.audioMixInfo_.gainNode.gain.value=this.audioMixInfo_.gainValue,this.audioMixInfo_.audioMixState=SC.INIT}checkAudioMixingParameter(){if(!this.client_||this.client_.length<1||!this.client_[0].getPublishAudioSender())throw this.logger.error(this.module_,"startAudioMixing failed"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"no mediaStream or no client or no audio!")}replaceMixAudioTrack(e){if(this.audioMixInfo_.audioMixState!==SC.IDLE&&this.audioMixInfo_.audioMixState!==SC.INIT&&this.audioMixInfo_.mediaNode&&this.audioMixInfo_.destNode){if(this.audioMixOption_.replace)return;return this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode),this.audioMixInfo_.mediaNode=null,this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),void this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode)}if(!this.isAuxiliary_){var t;const r=null===(t=this.screenShareMixInfo.bindStream)||void 0===t?void 0:t.screenShareMixInfo;r&&!r.muteMainAudio&&this.audioMixInfo_.audioCtx&&this.audioMixInfo_.destNode&&(this.audioMixInfo_.mediaNode=this.audioMixInfo_.audioCtx.createMediaStreamSource(new MediaStream([e])),this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode))}}async stopAudioMixing(){await this.stopAudioMixingImpl()}async stopAudioMixingImpl(){if(!this.audioMixInfo_.playAutoEnded)if(this.audioMixInfo_.audioMixState!==SC.IDLE&&this.audioMixInfo_.audioMixState!==SC.INIT){try{var e,t;await(null===(e=this.client_[0].getPublishAudioSender())||void 0===e?void 0:e.replaceTrack(null===(t=this.getAudioHRTCTrack())||void 0===t?void 0:t.getTrack()))}catch(Aw){throw this.logger.error(this.module_,"stopAudioMixing: ".concat(this.audioMixInfo_.audioMixState,", errMsg = ").concat(Aw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}var r;if(this.logger.info(this.module_,"stopAudioMixing"),!this.audioMixOption_.replace&&this.audioMixInfo_.audioMixState!==SC.PAUSE)null===(r=this.audioMixInfo_.mediaNode)||void 0===r||r.disconnect(this.audioMixInfo_.destNode);this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.buffer=null,this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.gainValue=.5,this.audioMixInfo_.sourceNode=null,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.audioMixState=SC.INIT}else this.logger.info(this.module_,"stopAudioMixing: ".concat(this.audioMixInfo_.audioMixState))}pauseAudioMixing(){this.pauseAudioMixingImpl()}pauseAudioMixingImpl(){if(this.audioMixInfo_.audioMixState===SC.PLAY){this.logger.info(this.module_,"pauseAudioMixing"),this.audioMixOption_.replace||this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode);try{var e,t;null===(e=this.client_[0].getPublishAudioSender())||void 0===e||e.replaceTrack(null===(t=this.getAudioHRTCTrack())||void 0===t?void 0:t.getTrack())}catch(Aw){throw this.logger.error(this.module_,"pauseAudioMixing, errMsg = ".concat(Aw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.pauseAt=XR.getCurrentTimestamp(),this.audioMixInfo_.audioMixState=SC.PAUSE}else this.logger.error(this.module_,"pauseAudioMixing: ".concat(this.audioMixInfo_.audioMixState))}resumeAudioMixing(){this.resumeAudioMixingImpl(),this.eventEmitter.emit(rC),this.logger.info(this.module_,"emit ".concat(rC," at resumeAudioMixing"))}resumeAudioMixingImpl(){if(this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"resumeAudioMixing: ".concat(this.audioMixInfo_.audioMixState));this.logger.info(this.module_,"resumeAudioMixing"),this.audioMixOption_.replace||this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode);try{var e;null===(e=this.client_[0].getPublishAudioSender())||void 0===e||e.replaceTrack(this.audioMixInfo_.destNode.stream.getAudioTracks()[0])}catch(Aw){throw this.logger.error(this.module_,"pauseAudioMixing, errMsg = ".concat(Aw)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at resumeAudioMixingImpl")))},this.audioMixInfo_.sourceNode.buffer=this.audioMixInfo_.buffer,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode);const t=this.audioMixInfo_.pauseAt-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur,r=t+this.audioMixOption_.startTime;if(this.audioMixOption_.repeatCount>1){this.audioMixInfo_.sourceNode.loop=!0;const e=this.audioMixOption_.repeatCount*this.getAudioMixingDuration()-this.audioMixOption_.startTime-t;this.audioMixInfo_.sourceNode.start(0,r%this.getAudioMixingDuration()/1e3,e/1e3)}else this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixInfo_.sourceNode.start(0,r%this.getAudioMixingDuration()/1e3);this.audioMixInfo_.pauseDur=this.audioMixInfo_.pauseDur+XR.getCurrentTimestamp()-this.audioMixInfo_.pauseAt,this.audioMixInfo_.audioMixState=SC.PLAY}getAudioMixingCurrentPosition(){let e=0;if(this.audioMixInfo_.audioMixState===SC.PAUSE)e=this.audioMixInfo_.pauseAt;else{if(this.audioMixInfo_.audioMixState!==SC.PLAY)return 0;e=XR.getCurrentTimestamp()}const t=this.getAudioMixingDuration();let r=(e-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur+this.audioMixOption_.startTime)%t;return r=Math.min(Math.round(r),t),this.logger.debug(this.module_,"getAudioMixingDuration: ".concat(r)),r}getAudioMixingDuration(){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return this.logger.error(this.module_,"getAudioMixingDuration failed for play status error"),0;const e=1e3*this.audioMixInfo_.sourceNode.buffer.duration;return this.logger.debug(this.module_,"getAudioMixingDuration: ".concat(e)),e}setAudioMixingVolume(e){this.setAudioMixingVolumeImpl(e)}setAudioMixingVolumeImpl(e){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"setAudioMixingVolume failed for play status error");const t=e/100;this.logger.debug(this.module_,"setAudioMixingVolume: "+t),this.audioMixInfo_.gainValue=t,this.audioMixInfo_.gainNode.gain.value=t}setAudioMixingPosition(e){this.setAudioMixingPositionImpl(e)}setAudioMixingPositionImpl(e){if(this.audioMixInfo_.audioMixState!==SC.PLAY&&this.audioMixInfo_.audioMixState!==SC.PAUSE)return void this.logger.error(this.module_,"setAudioMixingPosition failed for play status error");const t=this.getAudioMixingDuration();if(e<0||e>t)return void this.logger.error(this.module_,"setAudioMixingPosition failed for params error");let r;this.logger.debug(this.module_,"setAudioMixingPosition: ".concat(e)),this.audioMixInfo_.mediaNode.connect(this.audioMixInfo_.destNode),this.audioMixInfo_.sourceNode.stop(),this.audioMixInfo_.sourceNode.disconnect(),this.audioMixInfo_.gainNode.disconnect(),this.audioMixInfo_.sourceNode=null,r=this.audioMixInfo_.audioMixState===SC.PAUSE?this.audioMixInfo_.pauseAt:XR.getCurrentTimestamp();const i=r-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur+this.audioMixOption_.startTime;if(this.audioMixOption_.replace&&(this.audioMixInfo_.mediaNode.disconnect(this.audioMixInfo_.destNode),this.logger.info(this.module_,"resumeAudioMixing: replace")),this.audioMixInfo_.startAt=XR.getCurrentTimestamp(),this.audioMixInfo_.pauseAt=0,this.audioMixInfo_.pauseDur=0,this.audioMixInfo_.playAutoEnded=!1,this.audioMixInfo_.sourceNode=this.audioMixInfo_.audioCtx.createBufferSource(),this.audioMixInfo_.sourceNode.onended=()=>{Math.abs(this.audioMixInfo_.totalDur-(XR.getCurrentTimestamp()-this.audioMixInfo_.startAt-this.audioMixInfo_.pauseDur))<200&&(this.stopAudioMixing(),this.audioMixInfo_.playAutoEnded=!0,this.eventEmitter.emit(tC),this.logger.info(this.module_,"emit ".concat(tC," at setAudioMixingPositionImpl")))},this.audioMixInfo_.sourceNode.buffer=this.audioMixInfo_.buffer,this.audioMixInfo_.sourceNode.connect(this.audioMixInfo_.gainNode),this.audioMixInfo_.gainNode.connect(this.audioMixInfo_.destNode),i>=t&&this.audioMixOption_.repeatCount>1&&(this.audioMixOption_.repeatCount=Math.max(0,this.audioMixOption_.repeatCount-Math.floor(i/t))),this.audioMixOption_.repeatCount>1){this.audioMixInfo_.sourceNode.loop=!0;const r=this.audioMixOption_.repeatCount*t-e;this.audioMixInfo_.totalDur=r,this.audioMixInfo_.sourceNode.start(0,e/1e3,r/1e3)}else this.audioMixOption_.loop?this.audioMixInfo_.totalDur=1/0:this.audioMixInfo_.totalDur=t-e,this.audioMixInfo_.sourceNode.loop=this.audioMixOption_.loop,this.audioMixInfo_.sourceNode.start(0,e/1e3);this.audioMixOption_.startTime=e,this.audioMixInfo_.audioMixState===SC.PAUSE&&this.pauseAudioMixing()}getStatInfo(){return{audioProfile_:this.audioProfile_,videoProfile_:this.videoProfiles_,screenProfile_:this.screenProfile_,audio_:this.audio_,video_:this.video_,cameraId_:this.getCurrentCameraId(),facingMode_:this.facingMode_,microphoneId_:this.getCurrentMicrophoneId(),screen_:this.screen_,screenAudio_:this.screenAudio_}}},n(XP.prototype,"initialize",[PP],Object.getOwnPropertyDescriptor(XP.prototype,"initialize"),XP.prototype),n(XP.prototype,"addAudioTrackCapture",[MP],Object.getOwnPropertyDescriptor(XP.prototype,"addAudioTrackCapture"),XP.prototype),n(XP.prototype,"addVideoTrackCapture",[DP],Object.getOwnPropertyDescriptor(XP.prototype,"addVideoTrackCapture"),XP.prototype),n(XP.prototype,"setAudioProfile",[NP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioProfile"),XP.prototype),n(XP.prototype,"setVideoProfile",[UP],Object.getOwnPropertyDescriptor(XP.prototype,"setVideoProfile"),XP.prototype),n(XP.prototype,"addResolution",[xP],Object.getOwnPropertyDescriptor(XP.prototype,"addResolution"),XP.prototype),n(XP.prototype,"removeResolution",[LP],Object.getOwnPropertyDescriptor(XP.prototype,"removeResolution"),XP.prototype),n(XP.prototype,"setScreenProfile",[BP],Object.getOwnPropertyDescriptor(XP.prototype,"setScreenProfile"),XP.prototype),n(XP.prototype,"switchDevice",[VP],Object.getOwnPropertyDescriptor(XP.prototype,"switchDevice"),XP.prototype),n(XP.prototype,"addTrack",[YP],Object.getOwnPropertyDescriptor(XP.prototype,"addTrack"),XP.prototype),n(XP.prototype,"removeTrack",[jP],Object.getOwnPropertyDescriptor(XP.prototype,"removeTrack"),XP.prototype),n(XP.prototype,"replaceTrack",[FP],Object.getOwnPropertyDescriptor(XP.prototype,"replaceTrack"),XP.prototype),n(XP.prototype,"bindScreenAudio2RelatedStream",[HP],Object.getOwnPropertyDescriptor(XP.prototype,"bindScreenAudio2RelatedStream"),XP.prototype),n(XP.prototype,"startAudioMixing",[KP],Object.getOwnPropertyDescriptor(XP.prototype,"startAudioMixing"),XP.prototype),n(XP.prototype,"stopAudioMixing",[zP],Object.getOwnPropertyDescriptor(XP.prototype,"stopAudioMixing"),XP.prototype),n(XP.prototype,"pauseAudioMixing",[WP],Object.getOwnPropertyDescriptor(XP.prototype,"pauseAudioMixing"),XP.prototype),n(XP.prototype,"resumeAudioMixing",[GP],Object.getOwnPropertyDescriptor(XP.prototype,"resumeAudioMixing"),XP.prototype),n(XP.prototype,"setAudioMixingVolume",[JP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioMixingVolume"),XP.prototype),n(XP.prototype,"setAudioMixingPosition",[qP],Object.getOwnPropertyDescriptor(XP.prototype,"setAudioMixingPosition"),XP.prototype),XP);class rM extends eM{constructor(e){super({isRemote:!0,type:e.type,log:e.log}),this.userId_=e.userId,this.client_=[],this.client_.push(e.client),this.module_="RemoteStream",this.roomId_=e.roomId}muteAudio(){return!!super.muteAudio()&&(this.stat.reportAudioMuteInfo(2,!0),!0)}unmuteAudio(){return!!super.unmuteAudio()&&(this.stat.reportAudioMuteInfo(2,!1),!0)}getVideoHRTCTrackByTrackId(e){let t;for(const r of this.tracks[mO.TRACK_TYPE_VIDEO].values())if(r.getTrackId()===e){t=r;break}return t}updateRemoteResolutions(e,t,r){if(!t)return;const i=this.getHRTCTrackIds({mediaType:mO.TRACK_TYPE_VIDEO}),n=t.map((e=>e.streamId));for(const a of i)if(null==n||!n.includes(a))for(const t of this.getHRTCTracks({mediaType:mO.TRACK_TYPE_VIDEO}))if((null==t?void 0:t.getTrackId())===a){this.logger.info(this.module_,"updateRemoteResolutions, streamType:".concat(e,",delete track:").concat(a)),this.stop({audio:!1,video:!0,resolutionIds:[a]}),this.removeRemoteVideoTrack(a),this.tracks[mO.TRACK_TYPE_VIDEO].delete(t.getResolutionId());break}for(const a of t){if(i.includes(a.streamId)){var o;null===(o=this.getVideoHRTCTrackByTrackId(a.streamId))||void 0===o||o.updateTrackProfile(a);continue}const t=new oP({streamType:e,trackType:mO.TRACK_TYPE_VIDEO,isRemote:!0,trackProfile:{width:a.width,height:a.height},logger:this.logger,resolutionId:a.streamId,event:this.eventEmitter});t.setTrackId(a.streamId||t.getResolutionId()),this.tracks[mO.TRACK_TYPE_VIDEO].set(a.streamId,t)}const s=this.getAnyAudioHRTCTrack();if(r){if(!s){const t=new oP({streamType:e,trackType:mO.TRACK_TYPE_AUDIO,isRemote:!0,logger:this.logger,resolutionId:this.id_,event:this.eventEmitter});this.tracks[mO.TRACK_TYPE_AUDIO].set("mainAudio",t)}}else s&&(this.logger.info(this.module_,"updateRemoteResolutions, streamType:".concat(e,",delete audio track")),this.stop({audio:!0,video:!1}),this.removeRemoteAudioTrack(),this.tracks[mO.TRACK_TYPE_AUDIO].delete("mainAudio"));this.logger.info(this.module_,"updateResolutions success,userId:".concat(this.getUserId(),", streamType:").concat(e,",")+"new resolution is ".concat(this.getHRTCTracksProfileString()," hasAudio: ").concat(this.hasAudioTrack()))}getHRTCTracksProfileString(){const e=this.getHRTCTracks();let t="";return e.forEach((e=>{t=t+e.getTrackId()+":"+JSON.stringify(e.getTrackProfile())+","})),t}addRemoteTrack(e,t){if(e.kind===mO.TRACK_TYPE_AUDIO){const t=this.getAnyAudioHRTCTrack();null==t||t.replaceTrack(e)}else{const r=Array.from(this.tracks[mO.TRACK_TYPE_VIDEO].values()).find((e=>e.getTrackId()===t));null==r||r.replaceTrack(e)}this.logger.info(this.module_,"addRemoteTrack MediaStreamTrack for trackId:".concat(t," success,userId:").concat(this.getUserId(),", type:").concat(this.getType(),",")+"new resolution is ".concat(this.getHRTCTracksProfileString(),", hasAudio: ").concat(this.hasAudioTrack()))}isTracksReady(e,t){if(this.isRemote_){let r=!0;if(null!=e&&e.length){const t=this.getHRTCTrackIds();for(const i of e)if(!t.includes(i)||!this.getVideoHRTCTrackByTrackId(i).getTrack()){r=!1;break}}const i=this.getAudioHRTCTrack(),n=i&&!!i.getTrack(),o=r&&(!t||n);return this.logger.debug(this.module_,"isTracksReady userId:".concat(this.getUserId(),", type:").concat(this.getType(),",")+"result: ".concat(o,",videoTrackIds: ").concat(e,", isVideoReady:").concat(r,", isAudioReady:").concat(n)),o}return!0}isTrackReady(e,t){if(this.isRemote_){var r;if(e===mO.TRACK_TYPE_VIDEO)return!(null===(r=this.getVideoHRTCTrackByTrackId(t))||void 0===r||!r.getTrack());return!!this.getAudioHRTCTrack()}return!1}removeRemoteAudioTrack(){const e=this.getAnyAudioHRTCTrack();e&&e.removeTrack()}removeRemoteVideoTrack(e){const t=this.tracks[mO.TRACK_TYPE_VIDEO].get(e);t&&t.removeTrack()}}const iM=0,nM=2;let oM=function(e){return e.JOINER="anchor",e.PLAYER="audience",e}({}),sM=function(e){return e[e.JOINER=0]="JOINER",e[e.PLAYER=2]="PLAYER",e}({});class aM{get identifiedID(){return this.identifiedID_}set identifiedID(e){this.identifiedID_=e}get roomId(){return this.roomId_}set roomId(e){this.roomId_=e}get signature(){return this.signature_}set signature(e){this.signature_=e}get ctime(){return this.ctime_}set ctime(e){this.ctime_=e}get userId(){return this.userId_}set userId(e){this.userId_=e}get encUserId(){return this.encUserId_}set encUserId(e){this.encUserId_=e}get userName(){return this.userName_}set userName(e){this.userName_=e}get role(){return this.role_}set role(e){this.role_=e}get roleSignalType(){return nM===this.role_?oM.PLAYER:oM.JOINER}get appData(){return this.appData_}set appData(e){this.appData_=e}removeRelayInfo(e){this.relayInfos_=this.relayInfos_.filter((t=>t.roomId!==e))}addRelayInfo(e,t){this.relayInfos_||(this.relayInfos_=[]),this.relayInfos_.push({roomId:e,role:t})}getRelayInfos(){return this.relayInfos_}}const cM=new Map;class uM{static get(e){return cM.get(e)}static delete(e){cM.delete(e)}static init(e,t,r){const i=new aM;return i.identifiedID=e,i.userId=r.userId,i.userName=r.userName,i.role=r.role,i.signature=r.signature,i.ctime=r.ctime,i.appData={},r.userName&&(i.appData.nickname=r.userName),r.optionInfo&&[!0,!1].includes(r.optionInfo.recordPlaceholder)&&(i.appData.show_window=r.optionInfo.recordPlaceholder),i.roomId=t,cM.set(e,i),i}static transLocalUserToJoinConfig(e){var t;return{userId:e.userId,userName:e.userName,signature:e.signature,ctime:e.ctime,role:e.role,optionInfo:{recordPlaceholder:null===(t=e.appData)||void 0===t?void 0:t.show_window}}}static renewSignature(e,t,r){if(cM.has(e)){const i=cM.get(e);return i.ctime=t,i.signature=r,i}return null}}let dM=function(e){return e.ReceiveData="ReceiveData",e.ConnectionQuality="ConnectionQuality",e.Reconnected="Reconnected",e.SessionUnavailable="SessionUnavailable",e.ConnectionUnavailable="ConnectionUnavailable",e.ConnectionStateChanged="ConnectionStateChanged",e.AuthenticateFail="AuthenticateFail",e.SignatureExpired="SignatureExpired",e.ClientBanned="ClientBanned",e}({});class lM{constructor(){i(this,"state_",[])}default(e){return this.defaultVal_=e,this}get(){return 0!=this.state_.length?this.state_[this.state_.length-1]:null}set(e){return 2==this.state_.length&&this.state_.unshift(),this.state_.push(e),this}pre(){return this.state_.length>=2?this.state_[this.state_.length-2]:null}reset(){return this.state_=[],this.state_[0]=this.defaultVal_,this}get state(){return this.state_}}class hM extends lM{isChanged(){return this.state.length>1&&this.get()!==this.pre()}getDiffInfo(){return this.isChanged()?{updated:this.state[1]}:{}}}let fM=function(e){return e[e.Health=1]="Health",e[e.SubHealth=4]="SubHealth",e[e.Unavailable=6]="Unavailable",e}({});const pM="HealthMonitor";class mM extends $P{constructor(e){super({emitter:!0,logger:e.logger}),this.client=e,this.reset()}reset(){this.streamDetectTimer&&(clearInterval(this.streamDetectTimer),this.streamDetectTimer=null),this.streamStats={mainStream:{bytesIn:(new hM).default(0).set(0).set(0),bytesOut:(new hM).default(0).set(0).set(0)},auxStream:{bytesIn:(new hM).default(0).set(0).set(0),bytesOut:(new hM).default(0).set(0).set(0)},upQuality:(new hM).default(yO.NETWORK_QUALITY_UNKNOW).set(yO.NETWORK_QUALITY_UNKNOW).set(yO.NETWORK_QUALITY_UNKNOW),downQuality:(new hM).default(yO.NETWORK_QUALITY_UNKNOW).set(yO.NETWORK_QUALITY_UNKNOW).set(yO.NETWORK_QUALITY_UNKNOW)}}isStreamAvailable(){if(!this.client)return!1;const e=this.isAvailableStreamIncoming(gO.STREAM_TYPE_MAIN),t=this.isAvailableStreamIncoming(gO.STREAM_TYPE_AUX),r=this.isAvailableStreamOutgoing(gO.STREAM_TYPE_MAIN),i=this.isAvailableStreamOutgoing(gO.STREAM_TYPE_AUX);return e||t||r||i}getWsConnectionHealthStatus(){return this.streamDetectTimer?this.isStreamAvailable()?fM.SubHealth:fM.Unavailable:fM.Health}startStreamStateDetection(){this.streamDetectTimer||(this.streamDetectTimer=setInterval((async()=>{if(this.client){const e=this.client.getICETransportStat(gO.STREAM_TYPE_MAIN);e&&this.updateStreamStat(e,gO.STREAM_TYPE_MAIN);const t=this.client.getICETransportStat(gO.STREAM_TYPE_AUX);t&&this.updateStreamStat(t,gO.STREAM_TYPE_AUX),this.updateConnectionQuality(this.getWsConnectionHealthStatus())}}),3e3))}stopStreamStateDetection(){this.streamDetectTimer&&(clearInterval(this.streamDetectTimer),this.streamDetectTimer=null,this.updateConnectionQuality(this.getWsConnectionHealthStatus()))}updateConnectionQuality(e){if(!this.client)return;const t=this.client.isSendingStream()?e:yO.NETWORK_QUALITY_UNKNOW,r=this.client.isReceivingStream()?e:yO.NETWORK_QUALITY_UNKNOW;this.updateSignalQuality(t,r)}isAvailableStreamIncoming(e){const t=e===gO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;return t.bytesIn.get()-t.bytesIn.pre()>mM.getMinAvailableBytes()}static getMinAvailableBytes(){return sC.low.bitrate/8*3}isAvailableStreamOutgoing(e){const t=e===gO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;return t.bytesOut.get()-t.bytesOut.pre()>mM.getMinAvailableBytes()}updateStreamStat(e,t){const r=t===gO.STREAM_TYPE_MAIN?this.streamStats.mainStream:this.streamStats.auxStream;this.logger.info(pM,"".concat(t," : bytesIn:").concat(e.bytesReceived," ,bytesOut:").concat(e.bytesSent)),r.bytesIn.set(e.bytesReceived),r.bytesOut.set(e.bytesSent)}updateSignalQuality(e,t){if(this.streamStats.upQuality.set(e),this.streamStats.downQuality.set(t),this.logger.info(pM,"upQuality:".concat(this.streamStats.upQuality.pre(),",").concat("".concat(e)," ,downQuality:").concat(this.streamStats.downQuality.pre(),",").concat("".concat(t))),this.streamStats.upQuality.isChanged()||this.streamStats.downQuality.isChanged()){const r={uplinkNetworkQuality:e,downlinkNetworkQuality:t};this.logger.info(pM,"emit network-quality:".concat(JSON.stringify(r))),this.eventEmitter.emit(dM.ConnectionQuality,r)}}getInfo(){return{moduleName:"HealthMonitor"}}}function gM(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const _M="Socket",SM="heartbeat",vM="reconnectingEnd";var yM=function(e){return e[e.normal=1e3]="normal",e[e.multiKickoff=4e3]="multiKickoff",e[e.authenticateFail=4001]="authenticateFail",e[e.kickoff=4002]="kickoff",e[e.releaseRoom=4003]="releaseRoom",e[e.heartbeatTimeout=4004]="heartbeatTimeout",e[e.serverReconnectReq=4005]="serverReconnectReq",e[e.serveReconnectReqWithoutSfu=4006]="serveReconnectReqWithoutSfu",e[e.signatureFail=4009]="signatureFail",e}(yM||{});let IM=0;class TM extends $P{constructor(e,t,r){super({emitter:!0,logger:r.logger,stat:r.stat}),i(this,"callbacks",new Map),this.taskId=1e3,this.appId=e,this.edgeNodeDomains=t,this.clientConfig=r.clientConfig;const n=new hM;n.default(yC.IDLE).reset().set(yC.IDLE),this.wsStatus={state:n,isHeartbeat:!1,isWsReconnecting:!1,hasEverConnected:!1},this.healthMonitor=new mM(r),this.healthMonitor.on(dM.ConnectionQuality,this.getConnectionQualityListener()),this.wsReset()}setKeepAliveParams(e){this.heartBeatConfig=e}setTraceId(e){this.traceId=e}wsReset(){var e;this.closeConnection(),this.traceId="",this.connectId="",this.wsUrl="",this.acsIP="",this.wsStatus.state.reset(),this.wsStatus.hasEverConnected=!1,this.userInfo=void 0,null===(e=this.healthMonitor)||void 0===e||e.reset()}wsDisconnect(){this.healthMonitor.off(dM.ConnectionQuality),this.wsReset(),this.healthMonitor=void 0}getConnectionQualityListener(){return e=>{this.emit(dM.ConnectionQuality,e)}}async wsConnect(e,t,r,i,n,o,s){this.logger.info(_M,"wsConnect, acsIP:".concat(t,", firstTimeout:").concat(n,", retryTimeout:").concat(o,", retryCount:").concat(i,",retryInterval:").concat(s)),this.wsStatus.isWsReconnecting&&(this.logger.info(_M,"wsConnect, waiting for reconnecting ending"),await this.stopReconnecting(),this.logger.info(_M,"wsConnect, reconnecting end")),this.acsIP=t,this.userInfo=e,this.wsStatus.state.set(yC.DISCONNECTED),await this.doConnect(t,r,i,n,o,s,!1)}refreshUserInfo(e){this.userInfo=e}async startHeartbeat(){try{if(this.wsStatus.isHeartbeat)return void this.logger.warn(_M,"startHeartbeat, isHeartbeat so return");this.wsStatus.isHeartbeat=!0;const e=async e=>await this.sendHeartbeat(e);return await mP.callWithRetryTimes(e,!0,-1,this.getAsyncInterval(1e3*this.heartBeatConfig.heartBeatPeriod),this.needInterrupted())}catch(jN){this.logger.warn(_M,"startHeartbeat, error:".concat(jN))}finally{this.wsStatus.isHeartbeat=!1}}async wsSendRequest(e,t,r,i,n){this.logger.debug(_M,"wsSendRequest: ".concat(e.type," - ").concat(e.requestId));return await mP.callWithRetryTimes((async i=>await this.wsSendReqOnce(e.requestId,e,t,r,i)),!1,i,this.getAsyncInterval(n),this.needInterrupted())}wsSendResponse(e){this.ws.send(e)}generateRequestId(){return this.traceId,this.traceId+"Web"+(this.taskId++).toString()}async doConnect(e,t,r,i,n,o,s){return await mP.callWithRetryTimes((async r=>await this.wsConnectOnce(e,t,i,n,r,s)),!1,r,this.getAsyncInterval(o),this.needInterrupted())}async wsConnectOnce(e,t,r,i,n,o){if([yC.IDLE,yC.CONNECTING].includes(this.wsStatus.state.get())||!this.userInfo)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(this.wsStatus.state.get()!==yC.DISCONNECTED)return this.logger.error(_M,"wsConnectOnce, cusState:".concat(this.wsStatus.state.get(),", not DISCONNECTED, return")),null;this.connectId=this.taskId.toString(),this.wsUrl=this.getWsUrl(e,o);const s=XR.getCurrentTimestamp();this.ws=new WebSocket(this.wsUrl),this.logger.info(_M,"wsConnectOnce, url:".concat(XR.shieldUrlParameters(this.wsUrl),", connectId:").concat(this.connectId,", begin create websocket connection with server ")),1!==n||o?this.triggerConnectStatesChangeEvent(yC.RECONNECTING):this.triggerConnectStatesChangeEvent(yC.CONNECTING),this.ws.onopen=this.onopen.bind(this),this.ws.onerror=this.onerror.bind(this),this.ws.onmessage=this.onmessage.bind(this),this.ws.onclose=this.onclose.bind(this);const a={id:((null==t?void 0:t.length)||0)+1,domain:this.edgeNodeDomains.get(e),start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"wsConnect",rspCode:"",errMsg:""};try{const e=1===n?r:i;await this.getConnectionResp(e),a.delay_ms=XR.getCurrentTimestamp()-a.start_ms,a.rspCode="101"}catch(jN){throw this.logger.error(_M,"wsConnectOnce, connect occur exception, connectId:".concat(this.connectId,", error: ").concat(jN)),a.delay_ms=XR.getCurrentTimestamp()-a.start_ms,"function"==typeof jN.getCode&&(a.rspCode="".concat(jN.getCode()),a.errMsg=jN.getMsg()),jN}finally{null==t||t.push(a);const e=XR.getCurrentTimestamp(),r={version:"v1",startTimestamp:s,traceId:this.xNuwaTraceId,spanId:this.xNuwaSpanId,parentSpanId:"0000000000000000",ip:"",source:"SDK",target:"WiseCloudRtcAccessService",spanName:"connect",status:"0",endTimestamp:e,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(r)}}async stopReconnecting(){let e=null;this.wsStatus.state.set(yC.IDLE);const t=[new Promise((t=>{this.callbacks.set(vM,(r=>{e&&clearTimeout(e),t(r)}))})),new Promise(((t,r)=>{e=setTimeout((()=>{r(new qc(Gc.RTC_ERR_CODE_WEBSOCKET_RECONNECT_TIMEOUT))}),3e4)}))];return await Promise.race(t).then((e=>e)).finally((()=>{this.callbacks.delete(vM)}))}async getConnectionResp(e){const t=this.connectId;await mP.callWithTimeout(new Promise(((e,r)=>{this.callbacks.set(t,(i=>{if(i.isSuccess)this.logger.info(_M,"getConnectionResp, connectId:".concat(t,", connect success")),this.triggerConnectStatesChangeEvent(yC.CONNECTED),e();else{const e=TM.newSocketException(i);this.logger.info(_M,"getConnectionResp, connectId:".concat(t,", connect fail, errMsg=").concat(e)),r(e)}}))})),e).catch((r=>{if(this.triggerConnectStatesChangeEvent(yC.DISCONNECTED),r.getCode()!==Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT)throw r;throw this.logger.error(_M,"getConnectionResp, connectId:".concat(t,", websocket connect timeout after ").concat(e," ms")),this.ws&&this.ws.readyState===this.ws.CONNECTING&&(this.logger.info(_M,"getConnectionResp, connectId:".concat(t,",websocket connect timeout, close webSocket manual")),this.ws.close()),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT)})).finally((()=>{this.callbacks.delete(t)}))}static newSocketException(e){if(e.isSuccess)return null;const t=Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR,r=e.code,i="".concat(r||""," websocket connect error");return new qc(t,i)}getWsUrl(e,t){let r,i;this.xNuwaTraceId=XR.generateRandomId(32,16),this.xNuwaSpanId=XR.generateRandomId(16,16);let n,o="443";const s=/ws(?:s)?:\/\/([^/]+)(.*)/.exec(this.edgeNodeDomains.get(e));if(s&&3===s.length){const e=s[1].split(":");i=e[0],o=e[1]||"443",n=s[2]}else i=this.edgeNodeDomains.get(e),n="/websocket";const a=eO.getProxyServer();return r=a?/^http.*/.test(a)?a.replace("http","ws"):a.replace("https","wss"):"".concat("wss","://").concat(i,":").concat(o),r="".concat(r).concat(n,"?appId=").concat(escape(this.appId),"&roomId=").concat(escape(this.userInfo.roomId))+"&userId=".concat(escape(this.userInfo.userId),"&role=").concat(this.userInfo.roleSignalType,"&Authorization=").concat(escape(this.userInfo.signature))+"&ctime=".concat(this.userInfo.ctime,"&clientVersion=").concat(uA,"&clientType=").concat(XR.getSystemType())+"&romVersion=".concat(XR.getRomVersion(),"&agentType=").concat(2,"&netType=").concat(XR.getNetworkType())+"&traceId=".concat(this.traceId,"&x-nuwa-trace-id=").concat(this.xNuwaTraceId,"&x-nuwa-span-id=").concat(this.xNuwaSpanId)+"&HoldTime=".concat(120).concat(t?"&reconnect=true":"")+"&instanceId=".concat(XR.getDeviceID().replace(/[-]/g,"")).concat(this.clientConfig.countryCode?"&clientCountryCode=".concat(this.clientConfig.countryCode):""),a&&(r="".concat(r,"&org_domain=").concat(i,"&org_port=").concat(o)),r}cancelWsCloseCallBack(){this.ws&&(this.ws.onclose=e=>{this.logger.info(_M,"cancelWsCloseCallBack, connect close,code:".concat(e.code,", reason:").concat(e.reason))})}closeConnection(){this.ws&&(this.logger.info(_M,"close ws when reset"),this.cancelWsCloseCallBack(),this.ws.close(),this.ws=null)}triggerConnectStatesChangeEvent(e,t){this.wsStatus.state.set(e);const r=function(e){for(var t=1;t"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}getAsyncInterval(e){return t=>"function"==typeof(null==t?void 0:t.getCode)&&t.getCode()===Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT?0:e}async wsSendReqOnce(e,t,r,i,n){const o=TM.removeWatchType(t),s=XR.getCurrentTimestamp();try{if(this.wsStatus.state.get()===yC.IDLE)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(!this.ws||this.ws.readyState!==this.ws.OPEN)throw new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_OPEN);n>1&&this.logger.debug(_M,"wsSendReq: ".concat(e,", retry send message"));const s=JSON.stringify(o);this.ws.send(s),this.stat&&(this.stat.reportSignalReqForWeb2Server(o),this.stat.recordUploadRequsetInfo(t));const a=1===n?r:i;return await this.getResponse(o,a)}catch(jN){throw this.logger.error(_M,"wsSendReq: ".concat(e,", type: ").concat(o.type,", tryNumber: ").concat(n,",error: ").concat(jN)),"PING"===t.type&&this.healthMonitor.startStreamStateDetection(),this.recordWsException(t,jN,s),jN}finally{const e=this.stat.checkSignalSendMsgs((null==o?void 0:o.type)||""),t=o["x-nuwa-span-id"],r=XR.getCurrentTimestamp(),i={version:"v1",startTimestamp:s,traceId:o["x-nuwa-trace-id"],spanId:t,parentSpanId:e?"0000000000000000":this.stat.getParentSpanId(o["x-nuwa-span-id"]),ip:"",source:"SDK",target:"WiseCloudRtcAccessService",spanName:(null==o?void 0:o.type)||"",status:"0",endTimestamp:r,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(i)}}recordWsException(e,t,r){if("PING"!==e.type)switch(e.type){case"SUBS_STREAM":{const r=t.getCode(),i=t.getMsg();e.videoUpstreams&&this.stat.reportVideoSub(e.videoSubType,e.requestId,e.videoUpstreams,r,i),e.audioUpstreams&&this.stat.reportAudioSub(e.audioSubType,e.requestId,e.audioUpstreams,r);break}}else this.stat.reportSignalReqForHeartBeatLost(e,r)}async getResponse(e,t){let r=null;const i=[new Promise((t=>{const i="PING"===e.type?SM:e.requestId;this.callbacks.set(i,(e=>{r&&clearTimeout(r),t(e)}))})),new Promise(((e,i)=>{r=setTimeout((()=>{i(new qc(Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT))}),t)}))];return await Promise.race(i).finally((()=>{const t="PING"===e.type?SM:e.requestId;this.callbacks.delete(t)}))}onopen(e){this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!0}),this.logger.info(_M,"onopen, wss[".concat(XR.shieldUrlParameters(this.wsUrl),"], connectId:").concat(this.connectId,", connect success, ").concat(JSON.stringify(e))),this.stat.setConnectionStatusInfo(QC.CONNECTED,XC.SIGNAL)}onerror(e){this.logger.error(_M,"onerror, connectId:".concat(this.connectId,", websocket occur error:").concat(JSON.stringify(e))),this.stat.setConnectionStatusInfo(QC.CLOSED,XC.SIGNAL),this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!1})}onmessage(e){if(null==e||!e.data)return;const t=JSON.parse(e.data);this.wsStatus.hasEverConnected=!0,IM=0;const r=this.callbacks.get(SM);if(r&&r(t),t.type)this.emit(dM.ReceiveData,t);else{const e=this.callbacks.get(t.requestId);e&&e(t)}this.stat.reportSignalReqForServer2Web(t);const i=this.stat.getDownloadRequestInfo(t);this.stat.recordDownloadRequestInfo(t);const n=this.stat.checkSignalReceiveMsgs((null==t?void 0:t.type)||""),o=XR.generateRandomId(16,16),s=t["x-nuwa-span-id"];n&&this.stat.setSpanId(s,o);const a=XR.getCurrentTimestamp(),c={version:"v1",startTimestamp:a,traceId:t["x-nuwa-trace-id"],spanId:o,parentSpanId:s,ip:"",source:"WiseCloudRtcAccessService",target:"SDK",spanName:(null==t?void 0:t.type)||i,status:"0",endTimestamp:a,url:"",httpMethod:"",requestSize:"",responseSize:"",statusCode:"",tag:"",Events:"",scope:"videortn"};this.stat.reportTraceInfo2Nuwa(c)}async onclose(e){const t=e.code,r=e.reason;if(this.logger.warn(_M,"onclose,connectId:".concat(this.connectId,", code:").concat(t,", reason:").concat(r)),this.stat.setConnectionStatusInfo(QC.CLOSED,XC.SIGNAL),this.callbacks.has(this.connectId)&&this.callbacks.get(this.connectId)({isSuccess:!1,code:t,reason:r}),this.triggerConnectStatesChangeEvent(yC.DISCONNECTED,{code:t,reason:r}),TM.isServerAuthFail(t))this.handleServerAuthFail();else{if(!TM.isSignatureFail(t))return TM.isKickedOff(t)?(this.logger.warn(_M,"handleKickedOff, emit:".concat(dM.ClientBanned)),void this.emit(dM.ClientBanned)):TM.isServerSessionValidateFail(t)?(this.logger.warn(_M,"onclose, emit:".concat(dM.SessionUnavailable)),void this.emit(dM.SessionUnavailable)):void(t===yM.heartbeatTimeout||t===yM.serveReconnectReqWithoutSfu||t>1e3&&t<4e3?await this.reconnect():this.logger.error(_M,"onclose, no handler"));this.handleSignatureFail()}}handleServerAuthFail(){this.logger.error(_M,"handleServerAuthFail, auth failed to leave room"),this.logger.warn(_M,"handleServerAuthFail, emit:".concat(dM.AuthenticateFail," ")),this.emit(dM.AuthenticateFail)}async handleSignatureFail(){this.logger.warn(_M,"handle signature fail, emit:".concat(dM.SignatureExpired)),this.wsStatus.hasEverConnected?(this.emit(dM.SignatureExpired,{type:"reconnect"}),IM<5?(this.logger.warn(_M,"signature expired, try reconnect: retry times: ".concat(IM+1)),await this.reconnect(),IM++):this.emit(dM.SessionUnavailable)):this.emit(dM.SignatureExpired,{type:"join"})}async reconnect(){if(this.logger.info(_M,"reconnect, not user call leave, network error, go ws reconnecting"),!this.wsStatus.hasEverConnected)return this.logger.info(_M,"reconnect, haven't connect yet, so return"),null;if(this.wsStatus.isWsReconnecting)return this.logger.info(_M,"reconnect, isWsReConnecting so return"),null;try{this.wsStatus.isWsReconnecting=!0;const e=12e3,t=1e3;await this.doConnect(this.acsIP,null,-1,e,e,t,!0),this.logger.info(_M,"wsReconnect, success");const r=this.callbacks.get(vM);r&&r("success"),this.logger.warn(_M,"emit:".concat(dM.Reconnected)),this.emit(dM.Reconnected)}catch(jN){this.logger.error(_M,"wsReconnect, errMsg:".concat(jN));const t=this.callbacks.get(vM);t&&t(jN)}finally{this.wsStatus.isWsReconnecting=!1}}static isServerAuthFail(e){return[yM.authenticateFail,yM.releaseRoom].includes(e)}static isSignatureFail(e){return[yM.signatureFail].includes(e)}static isKickedOff(e){return[yM.multiKickoff,yM.kickoff].includes(e)}static isServerSessionValidateFail(e){return[yM.serverReconnectReq].includes(e)}async sendHeartbeat(e){try{if([yC.IDLE,yC.CONNECTING].includes(this.wsStatus.state.get()))throw this.logger.info(_M,"sendHeartbeat, but wsStatus is IDLE or CONNECTING, interrupted"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);if(!this.traceId)throw this.logger.error(_M,"sendHeartbeat, traceId is null"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED);const e={type:"PING",traceId:this.traceId,requestId:this.generateRequestId(),version:lA,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};await this.wsSendRequest(e,1e3*this.heartBeatConfig.heartBeatPeriod,1e3*this.heartBeatConfig.heartBeatPeriod,this.heartBeatConfig.heartBeatRetryTimes,1e3*this.heartBeatConfig.heartBeatPeriod),this.healthMonitor.stopStreamStateDetection()}catch(jN){this.logger.info(_M,"sendHeartbeat,father tryNumber:".concat(e,",child heartbeat retry out of limit:").concat(this.heartBeatConfig.heartBeatRetryTimes," and fail, error:").concat(jN)),this.handleHeartbeatFail(jN)}}handleHeartbeatFail(e){if("function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED)throw this.logger.warn(_M,"handleHeartbeatFail, ErrorCode.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED"),e;const t=this.healthMonitor.getWsConnectionHealthStatus();this.logger.warn(_M,"handleHeartbeatFail, healthStatus:".concat(t)),t===fM.Unavailable&&(this.logger.info(_M,"handleHeartbeatFail, connection unavailable when error:".concat(e)),this.logger.warn(_M,"emit:".concat(dM.ConnectionUnavailable)),this.emit(dM.ConnectionUnavailable))}getInfo(){return{moduleName:"Socket"}}}let RM=function(e){return e[e.MAIN=0]="MAIN",e[e.DESKTOP=1]="DESKTOP",e}({}),EM=function(e){return e.SEND_RECV="sendrecv",e.SEND_ONLY="sendonly",e.RECV_ONLY="recvonly",e.INACTIVE="inactive",e}({}),bM=function(e){return e[e.cmdPayload=99]="cmdPayload",e}({}),CM=function(e){return e[e.opusPayload=112]="opusPayload",e}({}),AM=function(e){return e[e.rtxPayLoad=107]="rtxPayLoad",e[e.h264PayLoad=122]="h264PayLoad",e[e.redPayLoad=110]="redPayLoad",e[e.ulpfecPayLoad=127]="ulpfecPayLoad",e}({}),wM=function(e){return e.H264="H264",e.H265="H265",e.H264H265="H264H265",e.OPUS="opus",e}({});const kM="signal",OM=5e3;class PM extends $P{constructor(e,t,r){super({emitter:!0,logger:r.logger,stat:r.stat},r.getSymbol()),this.edgeNodeDomains=t,this.socket=new TM(e,t,r),this.onSocketEvent(),this.reset()}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}reset(){var e;this.traceId="",this.isConnecting=!1,null===(e=this.socket)||void 0===e||e.wsReset()}disconnect(){var e;this.offSocketEvent(),this.reset(),null===(e=this.socket)||void 0===e||e.wsDisconnect(),this.socket=void 0}getConnectionQualityListener(){return e=>{this.emit(UC.NetworkQuality,e)}}getConnectionStateChangedListener(){return e=>{this.emit(UC.ConnectionStateChanged,e)}}getSignatureExpiredListener(){return e=>{this.emit(dM.SignatureExpired,e)}}getReceiveDataListener(){return e=>{this.receiveMsg(e)}}getSessionUnavailableListener(){return e=>{this.emit(dM.SessionUnavailable,e)}}getConnectionUnavailableListener(){return e=>{this.emit(dM.ConnectionUnavailable,e)}}getReconnectedListener(){return e=>{this.emit(dM.Reconnected,e)}}getAuthenticateFailListener(){return e=>{this.emit(dM.AuthenticateFail,e)}}getKickedOffListener(){return e=>{this.emit(dM.ClientBanned,e)}}onSocketEvent(){this.socket&&(this.socket.on(dM.ConnectionQuality,this.getConnectionQualityListener()),this.socket.on(dM.ConnectionStateChanged,this.getConnectionStateChangedListener()),this.socket.on(dM.SignatureExpired,this.getSignatureExpiredListener()),this.socket.on(dM.ReceiveData,this.getReceiveDataListener()),this.socket.on(dM.SessionUnavailable,this.getSessionUnavailableListener()),this.socket.on(dM.ConnectionUnavailable,this.getConnectionUnavailableListener()),this.socket.on(dM.Reconnected,this.getReconnectedListener()),this.socket.on(dM.AuthenticateFail,this.getAuthenticateFailListener()),this.socket.on(dM.ClientBanned,this.getKickedOffListener()))}offSocketEvent(){this.socket&&(this.socket.off(dM.ConnectionQuality),this.socket.off(dM.ConnectionStateChanged),this.socket.off(dM.SignatureExpired),this.socket.off(dM.ReceiveData),this.socket.off(dM.SessionUnavailable),this.socket.off(dM.ConnectionUnavailable),this.socket.off(dM.Reconnected),this.socket.off(dM.AuthenticateFail),this.socket.off(dM.ClientBanned))}getRandomAcsIp(){let e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(1===this.edgeNodeDomains.size||t)return this.selectedAcsIp="default",this.selectedAcsIp;let r=0;return this.selectedAcsIp?(e=[...this.edgeNodeDomains.keys()].filter((e=>"default"!==e&&e!==this.selectedAcsIp)),e.length<1||(r=Math.round(XR.getRandom()*(e.length-1)),this.selectedAcsIp=e[r]),this.selectedAcsIp):(e=[...this.edgeNodeDomains.keys()].filter((e=>"default"!==e)),r=Math.round(XR.getRandom()*(e.length-1)),this.selectedAcsIp=e[r],this.selectedAcsIp)}async connect(e,t){if(this.isConnecting)return this.logger.info(kM,"connect, isConnecting so return"),null;this.traceId=XR.generateStandardUuid(),this.socket.setTraceId(this.traceId);try{this.isConnecting=!0;const r=async r=>await this.connectOnce(e,t,r);return await mP.callWithRetryTimes(r,!1,2,this.getAsyncInterval(),this.needInterrupted())}finally{this.isConnecting=!1}}refreshUserInfo(e){this.socket.refreshUserInfo(e)}needInterrupted(){return e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}getAsyncInterval(){return()=>Math.round(500*XR.getRandom()+500)}async connectOnce(e,t,r){const i=this.getRandomAcsIp(PM.isLastTry(2,r));if(!i)throw this.logger.error(kM,"selectedAcsIP is null"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED,"no available servers to connect");return await this.socket.wsConnect(e,i,t,0,1e4,0,0),"default"===i?this.edgeNodeDomains.get("default"):i}static isLastTry(e,t){return t===e+1}async join(e,t,r,i,n,o,s,a){return new Promise(((c,u)=>{const d=PM.setJoinRequest(e,t,r,i,n,o,s,a);this.sendRequest(d).then((e=>{var t;0!==e.resultCode?(this.logger.error(kM,"join code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),u(new qc(Number(e.resultCode),e.resultMessage))):(null===(t=e.userInfos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),c(e))})).catch((e=>{u(e)}))}))}async subscribe(e,t,r){const i={type:"SUBS_STREAM",videoUpstreams:e,audioUpstreams:t,videoSubType:1,audioSubType:1,watchType:r,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)},n=await this.sendRequest(i);if(0!==n.resultCode){const e=JSON.stringify(i);throw this.logger.error(kM,"subscribe fail,err_code:".concat(n.resultCode,",")+"error_msg:".concat(n.resultMessage,",request ").concat(e)),new qc(Number(n.resultCode),n.resultMessage)}return this.logger.info(kM,"subscribe send msg result:".concat(n.resultMessage)),n}async queryRoomUsers(e){var t;const r={type:"GET_ROOM_USERINFO","x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};null!=e&&e.length&&(r.userIds=e);const i=await this.sendRequest(r);if(0!==i.resultCode)throw this.logger.error(kM,"queryRoomUsers fail,err_code:".concat(i.resultCode,",error_msg:").concat(i.resultMessage)),new qc(Number(i.resultCode),i.resultMessage);return null===(t=i.userInfos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),this.logger.info(kM,"queryRoomUsers send msg result:".concat(i.resultMessage)),i}async leave(){try{const e=await this.sendRequest({type:"EXIT_ROOM"});if(0!==e.resultCode)throw this.logger.error(kM,"leave, exit room, err_code:".concat(e.resultCode,",error_msg:").concat(e.resultMessage)),new qc(Number(e.resultCode),e.resultMessage);const t=await this.sendRequest({type:"BYE"});if(0!==t.resultCode)throw this.logger.error(kM,"leave, exit room, err_code:".concat(t.resultCode,",error_msg:").concat(t.resultMessage)),new qc(Number(t.resultCode),t.resultMessage)}catch(jN){throw new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}}async changeStreamStatus(e){try{return e.type="CHANGE_STREAM_STATUS",await this.sendRequest(e)}catch(jN){throw this.logger.error(kM,"changeStreamStatus fail, error:".concat(jN)),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR)}}static setJoinRequest(e,t,r,i,n,o,s,a){const c={type:"JOIN_ROOM",sdp:{secCap:"sec3.0",sfuType:pO.getParameter(sO)||vO.COMMON_SFU_RESOURCE,crypto:{type:1},frameType:pO.getParameter(cO)||xC.NON_ENCRYPTION,audios:[{content:CC.main,codecs:[{codec:wM.OPUS,pt:CM.opusPayload,ability:2}],audioLevel:3}],videos:[{content:CC.main,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]},{content:CC.slides,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]}],desktopVideos:[{content:CC.desktop,codecs:[{codec:wM.H264,pt:AM.h264PayLoad,ability:2}]}],audioPolicy:i,bandwidths:n},negSdp:[{type:RM.MAIN,sdp:t},{type:RM.DESKTOP,sdp:r}],scenario:1,relayMode:0,agentType:2,appData:e.appData,mediaData:{portType:o},"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)},u=pO.getParameter(aO);return u&&(c.sdp.resourceTags=u),s&&(c.sdp.command={codecs:[{codec:wM.OPUS,pt:bM.cmdPayload}],content:"cmd=1"}),Object.assign(c.mediaData,a||{}),c}async switchRole(e,t){const r=PM.setSwitchRoleRequest(e,t),i=await this.sendRequest(r);if(0!==i.resultCode)throw this.logger.error(kM,"switch user role fail,err_code:".concat(i.resultCode,",error_msg:").concat(i.resultMessage)),new qc(Number(i.resultCode),i.resultMessage);return i}static setSwitchRoleRequest(e,t){return{type:"SWITCH_ROLE",role:e===iM?oM.JOINER:oM.PLAYER,authorization:t.signature,ctime:parseInt(t.ctime),"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)}}async pushStreamResponse(e){this.logger.info(kM,"pushStreamRep send msg start:");try{await this.socket.wsSendResponse(JSON.stringify(e)),this.logger.info(kM,"pushStreamRep send response")}catch(Aw){throw this.logger.error(kM,"pushStreamRep send response fail, errMsg = ".concat(Aw)),new qc(Gc.RTC_ERR_CODE_PUBLISH_RESPONSE_FAIL)}}keepAlive(){this.logger.info(kM,"keepAlive"),this.socket.startHeartbeat()}async sendRequest(e){return this.assignCommonMsgInfo(e),await this.socket.wsSendRequest(e,OM,OM,2,OM)}assignCommonMsgInfo(e){Object.assign(e,{traceId:this.traceId,requestId:this.socket.generateRequestId(),version:lA,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)})}async publish(e){return new Promise(((t,r)=>{const i=[],n=[];e.forEach((e=>{e.codec===wM.H264?i.push({content:e.content,mute:e.mute,width:e.width,height:e.height,fps:e.fps,maxFs:e.maxFs,maxMbps:e.maxMbps,codec:e.codec,pt:e.pt,streamData:e.streamData,streamUid:e.streamUid,ssrc:e.ssrc,createDate:e.createDate}):e.codec===wM.OPUS&&n.push({content:e.content,mute:e.mute,channels:e.channels,sampleRate:e.sampleRate,maxMbps:e.maxMbps,codec:e.codec,pt:e.pt,streamData:e.streamData,streamUid:e.streamUid,ssrc:e.ssrc,createDate:e.createDate})}));const o={type:"PUSH_STREAM_RES_ALL",pushStreamType:0,videoStreams:i,audioStreams:n,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(o).then((e=>{0!==e.resultCode?(this.logger.error(kM,"publish resp code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),r(new qc(Number(e.resultCode),e.resultMessage))):t(e)})).catch((e=>{r(e)}))}))}async appData(e,t,r){return new Promise(((i,n)=>{const o={};Object.assign(o,e),o[t]=r;const s={type:"APP_DATA",appData:o};this.sendRequest(s).then((e=>{0!==e.resultCode?(this.logger.error(kM,"appset code:".concat(e.resultCode,",msg:").concat(e.resultMessage)),n(new qc(Number(e.resultCode),e.resultMessage))):i(e)})).catch((e=>{n(e)}))}))}async changeAudioPolicy(e){return new Promise(((t,r)=>{const i={type:"AUDIO_POLICY",audioPolicy:e,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(i).then((n=>{if(0!==n.resultCode){const t=JSON.stringify(i);this.logger.error(kM,"change audioPolicy code:".concat(n.resultCode,",audioPolicy:").concat(e,",msg:").concat(n.resultMessage," request ").concat(t)),r(new qc(Number(n.resultCode),n.resultMessage))}else this.logger.info(kM,"change audioPolicy ".concat(e," success")),t(n)})).catch((t=>{this.logger.info(kM,"change audioPolicy ".concat(e," exception")),r(t)}))}))}async updateLiveStreaming(e,t,r){return new Promise(((i,n)=>{const o={type:"UPDATE_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,config:t,userInfos:r,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(o).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(o);this.logger.error(kM,"updateLiveStreaming code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),n(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"updateLiveStreaming success"),i(e)})).catch((e=>{this.logger.info(kM,"updateLiveStreaming failed: ".concat(e)),n(e)}))}))}async startLiveStreaming(e,t,r,i){return new Promise(((n,o)=>{const s={type:"START_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,config:r,userInfos:i,urls:t,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(s).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(s);this.logger.error(kM,"startLiveStreamRequest code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),o(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"startLiveStreamRequest success"),n(e)})).catch((e=>{this.logger.info(kM,"startLiveStreamRequest failed: ".concat(e)),o(e)}))}))}async stopLiveStreaming(e){return new Promise(((t,r)=>{const i={type:"STOP_PUBLISH",traceId:XR.generateStandardUuid(),taskId:e,"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16)};this.sendRequest(i).then((e=>{if(0!==e.resultCode){const t=JSON.stringify(i);this.logger.error(kM,"stopLiveStreaming code:".concat(e.resultCode,", msg:").concat(e.resultMessage,", request ").concat(t)),r(new qc(Number(e.resultCode),e.resultMessage))}else this.logger.info(kM,"stopLiveStreaming success"),t(e)})).catch((e=>{this.logger.info(kM,"stopLiveStreaming failed: ".concat(e)),r(e)}))}))}receiveMsg(e){if(e.type)switch(EC.has("".concat(e.type))||this.logger.info(kM,"message type: ".concat(e.type)),e.type){case bC.statusChangeNotify:var t;null===(t=e.infos)||void 0===t||t.forEach((e=>{iE.addPrivacyString(e.userId),iE.addPrivacyString(e.appData.nickname)})),this.emit(bC.statusChangeNotify,e);break;case bC.uploadLogNotify:this.emit(bC.uploadLogNotify,e);break;case bC.pushStreamNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.pushStreamNotify,e);break}case bC.stopPushStreamNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.stopPushStreamNotify,e);break}case bC.watchStreamNotify:this.emit(bC.watchStreamNotify,e);break;case bC.changeStreamStatusNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.changeStreamStatusNotify,e);break}case bC.disconnectNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.disconnectNotify,e);break}case bC.reconnectNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.reconnectNotify,e);break}case bC.configNotify:this.emit(bC.configNotify,e);break;case bC.appDataChangeNotify:{const t=e;iE.addPrivacyString(t.userId),this.emit(bC.appDataChangeNotify,e);break}case bC.top3AudioVolumeNotify:var r;null===(r=e.topUserAudios)||void 0===r||r.forEach((e=>{iE.addPrivacyString(e.userId)})),this.emit(bC.top3AudioVolumeNotify,e);break;case bC.publishStatusNotify:this.emit(bC.publishStatusNotify,e);break;case bC.roomStreamStatusNotify:this.emit(bC.roomStreamStatusNotify,e);break;default:this.logger.error(kM,"unknown message type ".concat(e.type))}else this.logger.error(kM,"unknown message:".concat(e))}setConfigParams(e){this.socket.setKeepAliveParams(e)}getInfo(){return{traceId:this.traceId}}mediaRelay(e,t,r){return new Promise(((i,n)=>{var o,s,a;const c={type:"ROOM_MEDIA_RELAY",srcRoomToken:{roomId:r.roomId,userId:(null===(o=e.srcRoomRelayInfo)||void 0===o?void 0:o.userId)||"0",role:0===r.role?oM.JOINER:oM.PLAYER,ctime:null===(s=e.srcRoomRelayInfo)||void 0===s?void 0:s.ctime,token:null===(a=e.srcRoomRelayInfo)||void 0===a?void 0:a.authorization}};c[t?"addDstRoomInfo":"removeDstRoomInfo"]=e.dstRoomRelayInfo.map((e=>({roomId:e.roomId,userId:r.userId,role:0===e.role?oM.JOINER:oM.PLAYER,ctime:e.ctime,token:e.authorization}))),this.sendRequest(c).then((e=>{0!==e.resultCode?n(new qc(Number(e.resultCode),e.resultMessage)):(this.logger.info(kM,"mediaRelay success"),i(e))})).catch((e=>{this.logger.info(kM,"mediaRelay failed: ".concat(e)),n(e)}))}))}}class MM{constructor(){this.audioStreams=new Map,this.logger=iE.getLogger()}getAudioStreams(){return[...this.audioStreams.values()]}getAudioStream(e){return this.audioStreams.get(e)}addAudioStream(e,t){const r={audioPlayer:null,audioMediaTrack:null,streamId:e,ssrc:t,playStatus:"init"};this.audioStreams.set(e,r)}updateAudioStream(e,t){const r=this.audioStreams.get(e);r.audioMediaTrack=t,r.audioPlayer=new JO({logger:this.logger,playerId:e,track:t})}getAudioLevel(){const e=[];for(const r of this.audioStreams.values()){var t;e.push({streamId:r.streamId,ssrc:r.ssrc,level:null===(t=r.audioPlayer)||void 0===t?void 0:t.getAudioLevel()})}return e}async setAudioOutput(e){if("sinkId"in HTMLMediaElement.prototype&&e)for(const t of this.audioStreams.values())await t.audioPlayer.setSinkId(e)}setAudioVolume(e){const t=e/100;for(const i of this.audioStreams.values()){var r;if("notAllow"===i.playStatus)this.resume(i.streamId).then((()=>{var e;null===(e=i.audioPlayer)||void 0===e||e.setVolume(t)}));else null===(r=i.audioPlayer)||void 0===r||r.setVolume(t)}}muteAudio(e){for(const t of this.audioStreams.values())e||"notAllow"!==t.playStatus?t.audioMediaTrack.enabled=!e:this.resume(t.streamId).then((()=>{t.audioMediaTrack.enabled=!e}))}isAudioMuted(){const e=Array.from(this.audioStreams.values());return!e.every((e=>"normal"===e.playStatus))||!e.every((e=>e.audioMediaTrack.enabled))}async play(e){for(const i of this.audioStreams.values())try{var t;if(e){if(i.streamId===e){var r;await(null===(r=i.audioPlayer)||void 0===r?void 0:r.play()),i.playStatus="normal";break}}else await(null===(t=i.audioPlayer)||void 0===t?void 0:t.play()),i.playStatus="normal"}catch(jN){this.logger.error("RemoteTopNAudioStreams","resume failed, error: ".concat(jN)),i.playStatus="notAllow"}}async resume(e){for(const i of this.audioStreams.values())try{var t;if(e){if(i.streamId===e){var r;await(null===(r=i.audioPlayer)||void 0===r?void 0:r.resume()),i.playStatus="normal";break}}else await(null===(t=i.audioPlayer)||void 0===t?void 0:t.resume()),i.playStatus="normal"}catch(jN){this.logger.error("RemoteTopNAudioStreams","resume failed, error: ".concat(jN)),i.playStatus="notAllow"}}setAudioVolume4Id(e,t){for(const r of this.audioStreams.values())if(r.streamId===e&&r.audioPlayer){"notAllow"===r.playStatus?this.resume(e).then((()=>{r.audioPlayer.setVolume(t/100)})):r.audioPlayer.setVolume(t/100);break}}close(e){if(e&&this.audioStreams.has(e)){const t=this.audioStreams.get(e);return t.audioPlayer.stop(),t.audioMediaTrack=null,t.audioPlayer=null,t.playStatus="init",void this.audioStreams.delete(e)}for(const t of this.audioStreams.values())t.audioPlayer.stop(),t.audioMediaTrack=null,t.audioPlayer=null,t.playStatus="init";this.audioStreams.clear()}}const DM="LocalStreamPublishManager";class NM{constructor(){this.logger=iE.getLogger(),this.localStreams=new Map,this.sdpRepInfo=null}reset(){Array.from(this.localStreams.values()).forEach((e=>{e.localTrackPublishInfos.clear()})),this.logger.info(DM,"reset successfully")}getStreamTrackInfo(e){const t=[];let r;return e.getHRTCTracks({hasTrack:!0}).forEach((i=>{const n=i.getTrackProfile();if(i.getTrackType()===mO.TRACK_TYPE_AUDIO)i.setTrackId(this.sdpRepInfo.audio.streamCodecs[0].streamUid.toString()),r={type:mO.TRACK_TYPE_AUDIO,resolutionId:i.getResolutionId(),upstream:{content:CC.main,mute:i.getTrackMuted(),maxMbps:Math.round((n.bitrate||0)/1e3),sampleRate:n.sampleRate,channels:n.channelCount,codec:wM.OPUS,pt:CM.opusPayload,streamUid:this.sdpRepInfo.audio.streamCodecs[0].streamUid,ssrc:this.sdpRepInfo.audio.sendSsrcBegin}};else{let t;if(e.isAuxiliary())i.setTrackId(this.sdpRepInfo.desktopVideo.streamCodecs[0].streamUid.toString()),t={content:CC.desktop,mute:i.getTrackMuted(),width:n.width,height:n.height,fps:n.frameRate,maxMbps:Math.round((n.maxBitrate||0)/1e3),maxFs:n.frameRate,codec:wM.H264,pt:AM.h264PayLoad,streamUid:this.sdpRepInfo.desktopVideo.streamCodecs[0].streamUid,ssrc:this.sdpRepInfo.desktopVideo.sendSsrcBegin};else{const e=i.getTrackContentType(),r=this.sdpRepInfo.video.streamCodecs.find((t=>t.content===e)).streamUid;i.setTrackId(r.toString()),t={content:e,mute:i.getTrackMuted(),width:n.width,height:n.height,fps:n.frameRate,maxMbps:Math.round((n.maxBitrate||0)/1e3),maxFs:n.frameRate,codec:wM.H264,pt:AM.h264PayLoad,streamUid:r,ssrc:e===CC.main?this.sdpRepInfo.video.sendSsrcBegin:this.sdpRepInfo.video.sendSsrcEnd}}r={type:mO.TRACK_TYPE_VIDEO,resolutionId:i.getResolutionId(),upstream:t}}t.push(r)})),this.logger.debug(DM,"getStreamTrackInfo, get trackInfos: ".concat(JSON.stringify(t))),t}getLocalStream(e){const t=this.localStreams.get(e);return t?t.localStream:null}generatePubInfoWhenPublish(e,t){const r={allTracks2Publish:[],tracks2NewPublish:[],tracks2KeepPublish:[],tracks2UnPublish:[]},i=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,n=this.localStreams.get(i);return n&&0!==n.localTrackPublishInfos.size?this.isSameStreamId(e)?this.updateStream(e,r):this.replaceStream(e,r):this.addStream(e,r,t),this.buildAll2PublishTrackInfo(r.allTracks2Publish,e.isAuxiliary(),!0),this.logger.info(DM,"generatePubInfoWhenPublish tracks2Update input: ".concat(JSON.stringify(r))),r}setSdpRepInfo(e){this.sdpRepInfo=e}buildAll2PublishTrackInfo(e,t,r){t?(this.buildMediaPubInfo(e,mO.TRACK_TYPE_VIDEO,gO.STREAM_TYPE_MAIN),this.buildMediaPubInfo(e,mO.TRACK_TYPE_AUDIO,gO.STREAM_TYPE_MAIN),r&&this.buildMediaPubInfo(e,mO.TRACK_TYPE_VIDEO,gO.STREAM_TYPE_AUX)):(this.buildMediaPubInfo(e,mO.TRACK_TYPE_VIDEO,gO.STREAM_TYPE_AUX),r&&(this.buildMediaPubInfo(e,mO.TRACK_TYPE_VIDEO,gO.STREAM_TYPE_MAIN),this.buildMediaPubInfo(e,mO.TRACK_TYPE_AUDIO,gO.STREAM_TYPE_MAIN)))}buildMediaPubInfo(e,t,r){var i;const n=null===(i=this.localStreams.get(r))||void 0===i?void 0:i.localTrackPublishInfos;n&&Array.from(n.values()).filter((e=>e.type===t)).forEach((t=>{t.sender&&(t.upstream.mute=!t.sender.track.enabled),e.push(t)}))}isSameStreamId(e){const t=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN;return this.localStreams.get(t).streamId===e.getLocalId()}static getString4TrackPublishInfos(e){let t;for(const r of e.entries())t="".concat(t||""," resolutionId: ").concat(r[0],", track type: ").concat(r[1].type,", watched: ").concat(r[1].watched,", published: ").concat(r[1].published);return t}updateStream(e,t){this.logger.info(DM,"updateStream, update stream begin");const r=[],i=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,n=this.getStreamTrackInfo(e),o=this.localStreams.get(i);n.forEach((e=>{const n=o.localTrackPublishInfos.get(e.resolutionId);r.push(e),n?(n.upstream.mute=e.upstream.mute,n.published&&t.tracks2KeepPublish.push(n),n.watched&&!n.published&&t.tracks2NewPublish.push(n)):this.addTrack(i,e,t,o)}));const s=[];Array.from(o.localTrackPublishInfos.values()).forEach((e=>{const i=r.find((t=>t.resolutionId===e.resolutionId));if(i){if(!NM.isSameResolution(i,e)){const t={type:i.type,resolutionId:i.resolutionId,upstream:i.upstream,published:e.published,watched:e.watched,ssrc:e.ssrc,sender:e.sender};o.localTrackPublishInfos.set(i.resolutionId,t)}}else e.published&&t.tracks2UnPublish.push(e),s.push(e.resolutionId)})),s.forEach((e=>{o.localTrackPublishInfos.delete(e)})),this.logger.info(DM,"updateStream, update stream ".concat(e.getLocalId()," successfully\n ").concat(NM.getString4TrackPublishInfos(o.localTrackPublishInfos)))}static isSameResolution(e,t){return e.upstream.height===t.upstream.height&&e.upstream.width===t.upstream.width}replaceStream(e,t){return this.logger.info(DM,"replaceStream begin"),this.addStream(e,t)}addStream(e,t,r){const i=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,n=this.getStreamTrackInfo(e),o={localStream:e,streamId:e.getLocalId(),localTrackPublishInfos:new Map};n.forEach((e=>{this.addTrack(i,e,t,o,r)})),this.localStreams.set(i,o),this.logger.info(DM,"addStream, add stream ".concat(e.getLocalId()," successfully ,\n ").concat(NM.getString4TrackPublishInfos(o.localTrackPublishInfos)))}generatePubInfoWhenUnPublish(e){const t=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,r={allTracks2Publish:[],tracks2KeepPublish:[],tracks2NewPublish:[],tracks2UnPublish:[]},i=this.localStreams.get(t);return i?(Array.from(i.localTrackPublishInfos.values()).filter((e=>e.published)).forEach((e=>{r.tracks2UnPublish.push(e)})),this.buildAll2PublishTrackInfo(r.allTracks2Publish,e.isAuxiliary(),!1),r):(this.logger.warn(DM,"stream not publish"),r.allTracks2Publish=null,r)}removeStream(e){const t=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN;if(!this.localStreams.has(t))throw this.logger.error(DM,"removeStream, stream not exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.localStreams.delete(t)}generatePubInfoWhenWatch(e,t,r,i){if(this.logger.info(DM,"generatePubInfoWhenWatch watch ".concat(e," streams")),!t||!r)return null;const n={allTracks2Publish:null,tracks2KeepPublish:[],tracks2NewPublish:[],tracks2UnPublish:[]},o=this.localStreams.get(e);if(!o)return this.logger.info(DM,"generatePubInfoWhenWatch, stream not exist"),null;const s=Array.from(o.localTrackPublishInfos.values());return 0===t.length&&0===r.length?s.forEach((e=>{this.renewTrack2Update(!1,e,n)})):i===mO.TRACK_TYPE_VIDEO&&0===t.length&&r.length>0&&s.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).forEach((e=>{this.renewTrack2Update(!1,e,n)})),s.forEach((e=>{if(t.length>0&&e.type===mO.TRACK_TYPE_VIDEO){const r=t.find((t=>t===e.upstream.ssrc));this.renewTrack2Update(!!r,e,n)}if(r.length>0&&e.type===mO.TRACK_TYPE_AUDIO){const t=r.find((t=>t===e.upstream.ssrc));this.renewTrack2Update(!!t,e,n)}})),t.forEach((e=>{s.some((t=>e===t.upstream.ssrc))||this.logger.error(DM,"generatePubInfoWhenWatch, watch video ssrc:".concat(e," is not exist"))})),r.forEach((e=>{s.some((t=>e===t.upstream.ssrc))||this.logger.error(DM,"generatePubInfoWhenWatch, watch audio ssrc:".concat(e," is not exist"))})),n}renewTrack2Update(e,t,r){e?t.published?(r.tracks2KeepPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, keep ".concat(t.type," ssrc:").concat(t.ssrc))):(t.watched=!0,r.tracks2NewPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, new publish ".concat(t.type," ssrc:").concat(t.ssrc))):t.published&&(t.watched=!1,r.tracks2UnPublish.push(t),this.logger.info(DM,"generatePubInfoWhenWatch, new unpublish ".concat(t.type," ssrc:").concat(t.ssrc)))}addTrack(e,t,r,i,n){const o=NM.getDefaultWatchFlag(e,t.type,n),s={type:t.type,resolutionId:t.resolutionId,published:!1,watched:o,upstream:t.upstream,ssrc:t.upstream.ssrc,sender:null};s.watched&&r.tracks2NewPublish.push(s),i.localTrackPublishInfos.set(t.resolutionId,s),this.logger.info(DM,"addTrack, add track for resolutionId ".concat(t.resolutionId," successfully"))}static getDefaultWatchFlag(e,t,r){return e===gO.STREAM_TYPE_MAIN&&t===mO.TRACK_TYPE_AUDIO||(null==r?void 0:r.autoPushVideo)&&t===mO.TRACK_TYPE_VIDEO}publishAuxVideoTrackOK(e,t){this.publishTrackSuccess(gO.STREAM_TYPE_AUX,mO.TRACK_TYPE_VIDEO,e,t)}publishMainVideoTrackOK(e,t,r){this.publishTrackSuccess(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO,e,t,r)}publishMainAudioTrackOK(e,t){this.publishTrackSuccess(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO,e,t)}publishTrackSuccess(e,t,r,i,n){const o=this.localStreams.get(e);if(!o)throw this.logger.error(DM,"stream is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const s=this.getTrackInfo(o,t,n);if(!s)throw this.logger.error(DM,"getTrackInfo return empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);s.published&&this.logger.info(DM,"stream already published"),s.published=!0,s.sender=r,this.logger.info(DM,"publish track for trackId: ".concat(n," successfully"))}unPublishTrackSuccess(e,t,r){const i=this.localStreams.get(e);if(!i)throw this.logger.error(DM,"stream is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(t===mO.TRACK_TYPE_VIDEO&&!r)throw this.logger.error(DM,"video trackId is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=this.getTrackInfo(i,t,r);n?(n.published||this.logger.info(DM,"stream already unPublished"),n.published=!1,n.sender=null,this.logger.info(DM,"unPublish track for trackId: ".concat(r," successfully"))):this.logger.info(DM,"getTrackInfo return empty")}getMainStreamVideoPublishInfo(){return this.getTrackPublishInfos(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO)}getPublishedMainVideoTrackInfo(e){const t=this.getTrackPublishInfo(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO,e);return null!=t&&t.published&&t.sender?t:null}getPublishedMainAudioTrackInfo(){const e=this.getTrackPublishInfo(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO);return null!=e&&e.published&&e.sender?e:null}getPublishedAuxVideoTrackInfo(){const e=this.getTrackPublishInfo(gO.STREAM_TYPE_AUX,mO.TRACK_TYPE_VIDEO);return null!=e&&e.published&&e.sender?e:null}getPublishedMainVideoTrackInfos(){const e=this.getTrackPublishInfos(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO);return(null==e?void 0:e.length)>0?e.filter((e=>e.published&&e.sender)):null}getPublishedMainStreamInfos(){const e=this.getTrackPublishInfos(gO.STREAM_TYPE_MAIN);return(null==e?void 0:e.length)>0?e.filter((e=>e.published&&e.sender)):null}getPublishedAuxStreamInfo(){const e=this.localStreams.get(gO.STREAM_TYPE_AUX);if(!e)return null;return Array.from(e.localTrackPublishInfos.values()).find((e=>e.published&&e.sender))?e:null}getTrackPublishInfos(e,t){const r=this.localStreams.get(e);return r?t?Array.from(r.localTrackPublishInfos.values()).filter((e=>e.type===t)):Array.from(r.localTrackPublishInfos.values()):(this.logger.info(DM,"getTrackPublishInfos, not found"),null)}getTrackPublishInfo(e,t,r){const i=this.localStreams.get(e);return i?this.getTrackInfo(i,t,r):null}isAuxVideoTrackPublished(){const e=this.isTrackPublished(gO.STREAM_TYPE_AUX,mO.TRACK_TYPE_VIDEO);return this.logger.info(DM,"isAuxVideoTrackPublished: ".concat(e)),e}isMainStreamPublished(){const e=this.isTrackPublished(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO)||this.isTrackPublished(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO);return this.logger.info(DM,"isMainVideoTrackPublished: ".concat(e)),e}isTrackPublished(e,t,r){const i=this.localStreams.get(e);if(!i)return this.logger.info(DM,"isTrackPublished, not found"),!1;const n=this.getTrackInfo(i,t,r);return n?n.published&&!!n.sender:(this.logger.info(DM,"isTrackPublished, not found"),!1)}getTrackInfo(e,t,r){if(!e||0===e.localTrackPublishInfos.size)return null;if(t===mO.TRACK_TYPE_AUDIO)return Array.from(e.localTrackPublishInfos.values()).find((e=>e.type===mO.TRACK_TYPE_AUDIO));if(r)return Array.from(e.localTrackPublishInfos.values()).find((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.upstream.streamUid.toString()===r));const i=NM.getMaxResolutionId(e);return i?e.localTrackPublishInfos.get(i):null}static getMaxResolutionId(e){var t,r;return null==e||null===(t=e.localStream)||void 0===t||null===(r=t.getMaxResolutionHRTCTrack())||void 0===r?void 0:r.getResolutionId()}unPublishAuxStreamOK(){this.unPublishStreamSuccess(gO.STREAM_TYPE_AUX)}unPublishMainStreamOK(){this.unPublishStreamSuccess(gO.STREAM_TYPE_MAIN)}unPublishStreamSuccess(e){var t;const r=this.localStreams.get(e);r?(null===(t=r.localStream)||void 0===t||t.getHRTCTracks({hasTrack:!0,mediaType:mO.TRACK_TYPE_VIDEO}).forEach((e=>e&&e.setTrackId(""))),this.removeStream(r.localStream),this.logger.info(DM,"unPublishStreamSuccess, ".concat(e))):this.logger.warn(DM,"stream not publish")}isAuxVideoTrackValid(e){return this.isTrackValid(gO.STREAM_TYPE_AUX,mO.TRACK_TYPE_VIDEO,e)}isTrackValid(e,t,r){const i=this.localStreams.get(e);return i?Array.from(i.localTrackPublishInfos.values()).some((e=>e.type===t&&e.upstream.streamUid.toString()===r)):(this.logger.info(DM,"isTrackValid, not found"),!1)}generateOptTags(e,t){const r=[],i=this.localStreams.get(e);if(!i)return r;return Array.from(i.localTrackPublishInfos.values()).filter((e=>e.type===t&&e.published&&e.sender)).forEach((e=>{if(t===mO.TRACK_TYPE_VIDEO){const t=e.upstream?e.upstream.height:0,i=e.upstream?e.upstream.width:0,n="".concat(e.ssrc,":").concat(t,"*").concat(i);r.push(n)}else{var n;const t=null===(n=i.localStream.getAudioHRTCTrack())||void 0===n?void 0:n.getTrackProfile(),o="".concat(e.ssrc,":").concat(t?t.sampleRate:0);r.push(o)}})),r}generateMainAudioOptTag(){const e=this.generateOptTags(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO);return e.length>0?e[0]:null}generateAuxOptTag(){const e=this.generateOptTags(gO.STREAM_TYPE_AUX,mO.TRACK_TYPE_VIDEO);return e.length>0?e[0]:null}generateMainVideoOptTags(){const e=this.generateOptTags(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO);return e.length>0?e:null}}var UM={},xM={exports:{}},LM=xM.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(LM).forEach((function(e){LM[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var o=0;o1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},jM=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n{for(const t in e)ZM.includes(t)||delete e[t]})));return XR.shieldIpAddress(WM(t))}}getMedias(e,t){return e.media.filter((e=>{let{type:r}=e;return r===t}))}deleteUnexpectedMedia(e){e.media&&(e.media=e.media.filter((e=>{let{type:t}=e;return t===mO.TRACK_TYPE_VIDEO||t===mO.TRACK_TYPE_AUDIO||t===mO.TYPE_APPLICATION})),this.portType_===NC.portNormal&&e.groups&&(e.groups=e.groups.filter((e=>{let{type:t}=e;return"BUNDLE"!==t.toLocaleUpperCase()}))))}transformVideoPayload(e){if(!e.rtp)return void this.logger_.warn(this.module_,"transformVideoPayload failed ,rtp is null");let t=null,r=null,i=0;for(const n of e.rtp){if(n.codec.toUpperCase()!==wM.H264)continue;r||(r=n.payload,this.logger_.info(this.module_,"record firstPayload, firstPayload: ".concat(r)));const o=eD.getPacketizationMode(e.fmtp,n.payload),s=eD.getProfileLevelId(e.fmtp,n.payload);if(1===o&&(0===i&&(r=n.payload,i=1),"42e01f"===s)){t=n.payload,this.logger_.info(this.module_,"set retainPayload in transformVideoPayload, retainPayload: ".concat(t));break}}t||(t=r,this.logger_.info(this.module_,"no expected payload, use firstPayload as retainPayload, retainPayload: ".concat(t))),t?(eD.deletePayload(e,t),eD.modifyPayload(e,AM.h264PayLoad),eD.addVideoFec(e),eD.addFmtpAttr(e,AM.h264PayLoad,"max-br","5000000"),eD.addFmtpAttr(e,AM.h264PayLoad,QM,"1"),eD.addFmtpAttr(e,AM.rtxPayLoad,"apt","".concat(AM.h264PayLoad)),eD.addFmtpAttr(e,AM.rtxPayLoad,QM,"1")):this.logger_.error(this.module_,"transformVideoPayload failed,can not find expected payload.")}transformAudioPayload(e){if(!e.rtp)return void this.logger_.warn(this.module_,"transformAudioPayload failed, rtp is null");let t;for(const r of e.rtp)if(r.codec.toLowerCase()===wM.OPUS){t=r.payload;break}t?(eD.deletePayload(e,t),eD.modifyPayload(e,CM.opusPayload),eD.addNack(e)):this.logger_.error(this.module_,"transformAudioPayload failed,can not find expected payload.")}deleteRetransmissionSsrc(e){if(!e.ssrcGroups||!e.ssrcs)return;const t=[];e.ssrcGroups.forEach((e=>{let{ssrcs:r}=e;const i=this.getRetransmissionSsrc(r);null!=i&&t.push(i)})),0!==t.length&&(e.ssrcGroups=void 0,e.ssrcs=e.ssrcs.filter((e=>{let{id:r}=e;return!t.includes(r.toString())})))}addVideoSsrcRange(e,t){!t||t.length<1||(e.invalid||(e.invalid=[]),e.invalid.push({value:"send-ssrc-list:".concat(t.join(","))}))}static addAudioSsrcRange(e,t,r){if(t)if(e.invalid||(e.invalid=[]),r){const r=XR.getRandomUint32();e.invalid.push({value:"send-ssrc-list:".concat(t,",").concat(r)})}else e.invalid.push({value:"send-ssrc-list:".concat(t)})}modifyCandidate(e,t){if(!e.candidates){const r=null==t?void 0:t.find((t=>"".concat(e.mid)==="".concat(t.sdpMid)));if(r){const t=/.*generation\s(\d+).*/.exec(r.candidate)||[],i=/.*network\-id\s(\d+).*/.exec(r.candidate)||[],n=/.*network\-cost\s(\d+).*/.exec(r.candidate)||[];e.candidates=e.candidates||[],e.candidates.push({foundation:r.foundation,component:"rtp"===r.component?1:2,transport:r.protocol,priority:r.priority,ip:r.address,port:r.port,type:r.type,raddr:r.relatedAddress,rport:r.relatedPort,tcptype:r.tcpType,generation:2===t.length?parseInt(t[1]):void 0,"network-id":2===i.length?parseInt(i[1]):void 0,"network-cost":2===n.length?parseInt(n[1]):void 0})}}}static getPacketizationMode(e,t){if(!e)return 1;for(const r of e){if(r.payload!==t)continue;if(!r.config.includes(qM))return 1;const e=JM(r.config);return null==e[qM]?1:parseInt(String(e[qM]),10)}return 1}static getProfileLevelId(e,t){if(!e)return"";for(const r of e){if(r.payload!==t)continue;if(!r.config.includes(XM))return"";const e=JM(r.config);return e[XM]?String(e[XM]):""}return""}static deletePayload(e,t){e.rtp&&(e.rtp=e.rtp.filter((e=>{let{payload:r}=e;return r===t}))),e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>{let{payload:r}=e;return r===t}))),e.fmtp&&(e.fmtp=e.fmtp.filter((e=>{let{payload:r}=e;return r===t}))),e.payloads=t.toString()}static modifyPayload(e,t){e.rtp&&e.rtp.forEach((e=>{e.payload=t})),e.rtcpFb&&e.rtcpFb.forEach((e=>{e.payload=t})),e.fmtp&&e.fmtp.forEach((r=>{r.payload=t,e.type===mO.TRACK_TYPE_AUDIO&&/stereo/.test(r.config)&&(r.config=r.config.replace("stereo=1","stereo=0"))})),e.payloads=t.toString()}static addVideoFec(e){e.rtp||(e.rtp=[]),e.rtp.push({payload:AM.rtxPayLoad,codec:"rtx",rate:9e4}),e.rtp.push({payload:AM.redPayLoad,codec:"red",rate:9e4}),e.rtp.push({payload:AM.ulpfecPayLoad,codec:"ulpfec",rate:9e4}),e.payloads="".concat(AM.rtxPayLoad," ").concat(e.payloads," ").concat(AM.redPayLoad," ").concat(AM.ulpfecPayLoad)}static addFmtpAttr(e,t,r,i){if(!e.fmtp||0===e.fmtp.length)return e.fmtp=[],void e.fmtp.push({payload:t,config:r+"="+i});const n=e.fmtp.find((e=>e.payload===t));if(n){if(JM(n.config)[r])return;n.config=n.config+";"+r+"="+i}else e.fmtp.push({payload:t,config:r+"="+i})}static addNack(e){const t=e.rtp[0].payload;e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.push({payload:t,type:"ccm",subtype:"fir"}),e.rtcpFb.push({payload:t,type:"nack"}),e.rtcpFb.push({payload:t,type:"nack",subtype:"pli"})}getRetransmissionSsrc(e){if(!e)return void this.logger_.warn(this.module_,"getRetransmissionSsrc failed, ssrcs is null");const t=e.split(" ");if(2===t.length)return t[1];this.logger_.warn(this.module_,"getRetransmissionSsrc failed, ssrcs(".concat(e,") is invalid"))}static generateSsrcLabel(){return"".concat(XR.generateRandomId(8,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(4,36),"-").concat(XR.generateRandomId(12,36))}static addSsrcAttr(e,t,r){e.ssrcs||(e.ssrcs=[]);for(let i=0;i{let{id:r}=e;return!t.find((e=>e.toString()===r.toString()))})))}static getNegCmdInfoAndDelete(e){let t="",r="",i=!1;for(let n=0;n{e.value.indexOf("bindCrypto-key")>=0&&(t=e.value.substring(15)),e.value.indexOf("websocket-uri")>=0&&(r=e.value.substring(14))})),e.splice(n,1)):/SCTP/gi.test(e[n].protocol)&&(i=!0));return{bindCryptoKey:t,wsUrl:r,dataChannelEnable:i}}generateSsrcMslabel(){return XR.generateRandomId(36)}containsValidVideoPayload(e){this.logger_.debug(this.module_,"containsValidVideoPayload, offerSdp: ".concat(this.printSdpInfo(e)));const t=this.parseSdp(e);if(!t)return this.logger_.error(this.module_,"containsValidVideoPayload failed,the sdp is invalid"),!1;return this.getMedias(t,mO.TRACK_TYPE_VIDEO).some((e=>{var t;return null===(t=e.rtp)||void 0===t?void 0:t.some((e=>e.codec.toUpperCase()===wM.H264))}))}transformOfferSdp(e){this.logger_.info(this.module_,"transformOfferSdp begin");const t=this.parseSdp(e);if(!t)return void this.logger_.error(this.module_,"transformOfferSdp failed,the sdp is invalid");this.deleteUnexpectedMedia(t);const r=this.getMedias(t,mO.TRACK_TYPE_VIDEO),i=this.getMedias(t,mO.TRACK_TYPE_AUDIO);r.forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e)})),i.forEach((e=>{this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e)}));const n=WM(t);return this.logger_.debug(this.module_,"transformOfferSdp success, sdp: ".concat(this.printSdpInfo(n))),n}editOrigin(e){e.origin&&(e.origin.username=Cw.getBrowserInfo())}modifyAuxSdpInfo(e,t,r){const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyAuxSdpInfo failed,the sdp is invalid : ".concat(e));this.editOrigin(i);const n=this.getMedias(i,mO.TRACK_TYPE_VIDEO);n&&n.length>0&&(this.addVideoSsrcRange(n[0],r),this.modifyCandidate(n[0],t));const o=WM(i);return this.logger_.debug(this.module_,"modifyAuxSdpInfo success, sdp: ".concat(this.printSdpInfo(o))),o}modifyMainSdpInfo(e,t,r,i,n,o){const s=this.parseSdp(e);if(!s)return void this.logger_.error(this.module_,"modifyMainSdpInfo failed, the sdp is invalid : ".concat(e));this.editOrigin(s);const a=this.getMedias(s,mO.TRACK_TYPE_VIDEO),c=this.getMedias(s,mO.TRACK_TYPE_AUDIO);let u="",d="";if(a&&a.length>0&&(this.addVideoSsrcRange(a[0],r),this.modifyCandidate(a[0],t),d=a[0].mid,a.length>1))for(let h=0;h0&&(eD.addAudioSsrcRange(c[0],i,n),this.modifyCandidate(c[0],t),u=c[0].mid);for(const h of s.groups||[])if("BUNDLE"===h.type){h.mids="".concat(u," ").concat(d);break}n&&this.addNegCmdInfo(s,o);const l=WM(s);return this.logger_.debug(this.module_,"modifyMainSdpInfo success, sdp: ".concat(this.printSdpInfo(l))),l}addNegCmdInfo(e,t){if(t){const r=this.parseSdp(t).media.find((e=>e.type===mO.TYPE_APPLICATION)),i=e.media.filter((e=>null==e?void 0:e.type)),n=i[i.length-1];r.mid=["audio","video"].includes(n.mid)?"data":n.mid+1,e.media.push(r),e.groups.forEach((e=>{"BUNDLE"===e.type&&(e.mids="".concat(e.mids," ").concat(r.mid))}))}const r={type:"application",port:443,protocol:"TCP/WSS/RTP *",setup:"active",invalid:[]};r.invalid.push({value:"connection:new"}),r.invalid.push({value:"content:cmd"}),r.invalid.push({value:"bindCrypto-type:0"}),r.invalid.push({value:"bindCrypto-method:hmac-share256"}),e.media.push(r)}getSfuInfo(e,t){const r=this.parseSdp(e),i={ipAddress:"",auxPort:0};let n;const o=this.getMedias(r,mO.TRACK_TYPE_AUDIO);o&&o.length>0&&(i.audioPort=o[0].port,n=o[0].connection);const s=this.getMedias(r,mO.TRACK_TYPE_VIDEO);if(s&&s.length>0&&(i.videoPort=s[0].port,n=s[0].connection),n&&(i.ipAddress=n.ip),t){const e=this.parseSdp(t),r=this.getMedias(e,mO.TRACK_TYPE_VIDEO);r&&r.length>0&&r[0].connection&&(i.auxPort=r[0].port)}return i}}class tD extends eD{static modifyDirection(e){e.ssrcs&&0!==e.ssrcs.length?e.direction=EM.SEND_RECV:e.direction=EM.RECV_ONLY}hasSSRC(e,t){const r=this.parseSdp(e);if(!r)return this.logger_.error(this.module_,"hasSSRC failed"),!1;const i=this.getMedias(r,t);return i&&i.length>0&&!!i[0].ssrcs}getMslabelByCname(e,t){if(!e)return null;if(!e.ssrcs)return null;let r;for(const i of e.ssrcs)if(i.attribute.toLocaleLowerCase()===this.ssrcAttrCname_&&i.value===t){r=i.id;break}if(!r)return null;for(const i of e.ssrcs)if(i.id===r&&i.attribute.toLocaleLowerCase()===this.ssrcAttrMslabel_)return i.value;return null}addSsrc(e,t,r,i,n,o){const s=r,a=this.getMslabelByCname(e,s),c=this.getMslabelByCname(t,s);let u,d,l=!1,h=!1;if(a&&a===i||!n||(h=!0),c&&c===i||!o||(l=!0),h&&(u=c||i||this.generateSsrcMslabel()),l&&(d=i||this.generateSsrcMslabel()),this.logger_.debug(this.module_,"addSsrc, userId: ".concat(r,", audioMslabel: ").concat(u," videooMslabel: ").concat(d)),u){const t=eD.generateSsrcLabel(),r=[[this.ssrcAttrCname_,s],[this.ssrcAttrMslabel_,u],[this.ssrcAttrLabel_,t],[this.ssrcAttrMsid_,u+" "+t]];eD.addSsrcAttr(e,n,r)}if(d){const e=eD.generateSsrcLabel(),r=[[this.ssrcAttrCname_,s],[this.ssrcAttrMslabel_,d],[this.ssrcAttrLabel_,e],[this.ssrcAttrMsid_,d+" "+e]];eD.addSsrcAttr(t,o,r)}return d||u}static modifyMediaSsrc(e,t){if(!e.ssrcs)return;for(let r=0;r0&&(this.portType_===NC.portNormal&&(r[0].rtcpMux=void 0),tD.modifyDirection(r[0])),i&&i.length>0&&(this.portType_===NC.portNormal&&(i[0].rtcpMux=void 0),tD.modifyDirection(i[0])),this.portType_===NC.portNormal&&(t.groups=void 0);const{bindCryptoKey:n,wsUrl:o,dataChannelEnable:s}=eD.getNegCmdInfoAndDelete(t.media),a=WM(t);return this.logger_.debug(this.module_,"transformAnswerSdp success,answerSdp: ".concat(this.printSdpInfo(a))),{remoteDescription:a,bindCryptoKey:n,wsUrl:o,dataChannelEnable:s}}deleteSSRC(e,t,r){if(0===t.length&&!r)return e;this.logger_.info(this.module_,"deleteVideoSSRC ".concat(t,", ").concat(r));const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"deleteVideoSSRC failed");const n=this.getMedias(i,mO.TRACK_TYPE_VIDEO);n&&n.length>0&&(t&&eD.deleteSsrcAttr(n[0],t),tD.modifyDirection(n[0]));const o=this.getMedias(i,mO.TRACK_TYPE_AUDIO);o&&o.length>0&&(r&&eD.deleteSsrcAttr(o[0],[r]),tD.modifyDirection(o[0]));const s=WM(i);return this.logger_.info(this.module_,"deleteVideoSSRC ".concat(t," success")),s}addUser(e,t,r,i){const n=this.parseSdp(e);if(!n)return void this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(e));const o=this.getMedias(n,mO.TRACK_TYPE_VIDEO),s=this.getMedias(n,mO.TRACK_TYPE_AUDIO);let a,c;o&&o.length>0&&(a=o[0]),s&&s.length>0&&(c=s[0]);const u=this.addSsrc(c,a,t,r,i.audioSsrc,i.videoSsrc);a&&tD.modifyDirection(a),c&&tD.modifyDirection(c);const d=WM(n);return this.logger_.debug(this.module_,"addUser success, answerSdp: ".concat(this.printSdpInfo(d))),{answerSdp:d,streamId:u}}deleteUser(e,t,r){const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(e));if((null==t?void 0:t.length)>0){const e=this.getMedias(i,mO.TRACK_TYPE_VIDEO);e&&e.length>0&&(t.forEach((t=>{t&&eD.deleteSsrcAttr(e[0],[t])})),tD.modifyDirection(e[0]))}if((null==r?void 0:r.length)>0){const e=this.getMedias(i,mO.TRACK_TYPE_AUDIO);e&&e.length>0&&(r.forEach((t=>{t&&eD.deleteSsrcAttr(e[0],[t])})),tD.modifyDirection(e[0]))}const n=WM(i);return this.logger_.debug(this.module_,"deleteUser success, answerSdp: ".concat(this.printSdpInfo(n))),n}modifyPublishOfferSdp(e,t,r){this.logger_.debug(this.module_,"modifyPublishOfferSdp start, sdp: ".concat(this.printSdpInfo(e)));const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyPublishOfferSdp failed, the sdp is invalid: ".concat(e));this.deleteUnexpectedMedia(i);const n=this.getMedias(i,mO.TRACK_TYPE_VIDEO),o=this.getMedias(i,mO.TRACK_TYPE_AUDIO);if(n&&n.length>0&&(this.transformVideoPayload(n[0]),this.deleteRetransmissionSsrc(n[0]),t&&t.length>0&&tD.modifyMediaSsrc(n[0],t)),o&&o.length>0&&(this.transformAudioPayload(o[0]),this.deleteRetransmissionSsrc(o[0]),r)){const e=[r];tD.modifyMediaSsrc(o[0],e)}const s=WM(i);return this.logger_.debug(this.module_,"modifyPublishOfferSdp success, sdp: ".concat(this.printSdpInfo(s))),s}}class rD extends eD{static modifyDirectionWhenAddUser(e,t){e&&(e.direction===EM.RECV_ONLY?e.direction=EM.SEND_RECV:e.direction===EM.INACTIVE&&(e.direction=EM.SEND_ONLY)),t&&(t.direction===EM.SEND_ONLY?t.direction=EM.SEND_RECV:t.direction===EM.INACTIVE&&(t.direction=EM.RECV_ONLY))}addSSRC(e,t,r,i){const n=r||this.generateSsrcMslabel();this.logger_.debug(this.module_,"addSSRC, userId:".concat(t,", mslabel:").concat(n,", streamId:").concat(r,", ssrc:").concat(i)),e.ssrcs&&delete e.ssrcs;const o=eD.generateSsrcLabel(),s=[[this.ssrcAttrCname_,t],[this.ssrcAttrMslabel_,n],[this.ssrcAttrLabel_,o],[this.ssrcAttrMsid_,n+" "+o]];return eD.addSsrcAttr(e,i,s),n}static modifyDirectionWhenDelUser(e,t){e.direction===EM.SEND_RECV?e.direction=EM.RECV_ONLY:e.direction===EM.SEND_ONLY&&(e.direction=EM.INACTIVE),t.direction===EM.SEND_RECV?t.direction=EM.SEND_ONLY:t.direction===EM.RECV_ONLY&&(t.direction=EM.INACTIVE)}hasSSRC(e,t){const r=this.parseSdp(e);if(!r)return this.logger_.error(this.module_,"hasSSRC failed"),!1;return this.getMedias(r,t).some((e=>(e.direction===EM.SEND_ONLY||e.direction===EM.SEND_RECV)&&!!e.ssrcs))}delteInvalidLines(e){this.deleteUnexpectedMedia(e);const t=this.getMedias(e,mO.TRACK_TYPE_VIDEO),r=this.getMedias(e,mO.TRACK_TYPE_AUDIO);t.forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e)})),r.forEach((e=>{this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e)}))}getAvailableSenderMedia(e,t){return e.media.filter((e=>{let{type:r,direction:i}=e;return r===t&&(i===EM.SEND_ONLY||i===EM.SEND_RECV)}))}modifyUnifiedMediaSsrc(e,t,r){if(e.ssrcs&&0!==e.ssrcs.length)e.ssrcs.forEach((e=>{e.attribute===this.ssrcAttrCname_&&(e.value=r),e.id=t}));else{const i=[[this.ssrcAttrCname_,r]];eD.addSsrcAttr(e,t,i)}}static modifyBundle(e,t){for(const r of e.groups||[])if("BUNDLE"===r.type){r.mids.split(" ").includes("".concat(t))||(r.mids="".concat(r.mids," ").concat(t));break}}modifyAnswerDirection(e,t){var r;const i=this.parseSdp(e);if(!i)return void this.logger_.error(this.module_,"modifyAnswerDirection failed,the sdp is invalid");const n=null===(r=i.media)||void 0===r?void 0:r.find((e=>"".concat(e.mid)==="".concat(t)));return n&&(n.direction===EM.INACTIVE?n.direction=EM.RECV_ONLY:n.direction===EM.SEND_ONLY&&(n.direction=EM.SEND_RECV)),WM(i)}transformAnswerSdp(e,t){this.logger_.debug(this.module_,"transformAnswerSdp, answerSdp: ".concat(this.printSdpInfo(e)));const r=this.parseSdp(e),i=this.parseSdp(t);if(!r||!i)return void this.logger_.error(this.module_,"transformAnswerSdp failed,the sdp is invalid");this.getMedias(r,mO.TRACK_TYPE_AUDIO).forEach((e=>{this.portType_===NC.portNormal&&(e.rtcpMux=void 0),e.ssrcs||(e.direction=EM.INACTIVE)}));let n=this.getMedias(r,mO.TRACK_TYPE_VIDEO);const o=this.getMedias(i,mO.TRACK_TYPE_VIDEO);if(o.length!==n.length){const e=n.map((e=>"".concat(e.mid)));o.forEach((t=>{if(!e.includes("".concat(t.mid))){const e=JSON.parse(JSON.stringify(n[0]));e.mid=t.mid,r.media.push(e),rD.modifyBundle(r,t.mid)}}))}n=this.getMedias(r,mO.TRACK_TYPE_VIDEO),n.forEach((e=>{this.portType_===NC.portNormal&&(e.rtcpMux=void 0),e.direction=EM.INACTIVE})),this.portType_===NC.portNormal&&(r.groups=void 0);const{bindCryptoKey:s,wsUrl:a,dataChannelEnable:c}=eD.getNegCmdInfoAndDelete(r.media),u=this.getMedias(r,mO.TYPE_APPLICATION);if(r.media=r.media.filter((e=>e.type!==mO.TYPE_APPLICATION)),u.length>0){const e=this.getMedias(r,mO.TRACK_TYPE_VIDEO).map((e=>parseInt("".concat(e.mid))));u[0].mid="".concat(Math.max(...e)+1),Cw.isFirefox()&&(u[0].port=9),r.media.push(...u),rD.modifyBundle(r,"".concat(u[0].mid))}const d=WM(r);return this.logger_.debug(this.module_,"transformAnswerSdp success,answerSdp: ".concat(this.printSdpInfo(d))),{remoteDescription:d,bindCryptoKey:s,wsUrl:a,dataChannelEnable:c}}addUser(e,t,r,i,n,o){var s,a;const c=this.parseSdp(e);if(!c)return this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(e)),null;const u=this.parseSdp(t);if(!u)return this.logger_.error(this.module_,"addUser failed,the sdp is invalid : ".concat(t)),null;this.delteInvalidLines(u);const d=null===(s=u.media)||void 0===s?void 0:s.find((e=>"".concat(e.mid)===r)),l=null===(a=c.media)||void 0===a?void 0:a.find((e=>e.type===d.type)),h=JSON.parse(JSON.stringify(l));h.mid=r,h.direction=EM.SEND_ONLY,h.type===mO.TRACK_TYPE_AUDIO&&this.portType_===NC.portReduce&&delete h.candidates;const f=this.addSSRC(h,i,n,o);c.media.push(h),rD.modifyBundle(c,r),rD.modifyDirectionWhenAddUser(h,d);const p=WM(c),m=WM(u);return this.logger_.debug(this.module_,"addUser success, offer: ".concat(this.printSdpInfo(m)," answer: ").concat(this.printSdpInfo(p))),{offerSdp:m,answerSdp:p,streamId:f}}async deleteUser(e,t,r,i,n){const o=this.parseSdp(e);if(!o)return this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(e)),null;const s=this.parseSdp(t);if(!s)return this.logger_.error(this.module_,"deleteUser failed,the sdp is invalid : ".concat(t)),null;for(const u of o.media)if(u.ssrcs&&u.ssrcs.some((e=>r.includes(parseInt("".concat(e.id)))))){rD.modifyDirectionWhenDelUser(u,s.media.find((e=>e.mid===u.mid))),u.ssrcs.forEach((e=>{e.value="-"}));const e=i.find((e=>"".concat(e.mid)==="".concat(u.mid)));e&&(e.direction=e.currentDirection===EM.SEND_RECV||e.currentDirection===EM.SEND_ONLY?EM.SEND_ONLY:EM.INACTIVE,await n(e.receiver))}const a=WM(o),c=WM(s);return this.logger_.debug(this.module_,"deleteUser success, offer: ".concat(this.printSdpInfo(c)," answer: ").concat(this.printSdpInfo(a))),{offerSdp:c,answerSdp:a}}modifySdpByMid(e,t,r,i,n,o){var s,a;const c=this.parseSdp(e);if(!c)return this.logger_.error(this.module_,"modifySdpByMid failed,the sdp is invalid : ".concat(e)),null;const u=null===(s=c.media)||void 0===s?void 0:s.find((e=>"".concat(e.mid)===r)),d=this.addSSRC(u,i,n,o),l=this.parseSdp(t);l||this.logger_.error(this.module_,"modifySdpByMid failed,the sdp is invalid : ".concat(t));const h=null===(a=l.media)||void 0===a?void 0:a.find((e=>"".concat(e.mid)===r));rD.modifyDirectionWhenAddUser(u,h);const f=WM(c),p=WM(l);return this.logger_.debug(this.module_,"modifySdpByMid success, offer: ".concat(this.printSdpInfo(p)," answer: ").concat(this.printSdpInfo(f))),{offerSdp:p,answerSdp:f,streamId:d}}getAllMidsByType(e,t){var r;const i=this.parseSdp(e),n=[];return i?(null===(r=i.media)||void 0===r||r.forEach((e=>{e.type===t&&n.push("".concat(e.mid))})),n):(this.logger_.error(this.module_,"getAllMidsByType failed,the sdp is invalid : ".concat(e)),n)}getOfferVideoMidBySsrc(e,t,r){var i;const n=this.parseSdp(e);let o=null;return n?(null===(i=n.media)||void 0===i||i.forEach((e=>{e.type===t&&e.ssrcs&&e.ssrcs.length>0&&"".concat(e.ssrcs[0].id)==="".concat(r)&&(o="".concat(e.mid))})),o):(this.logger_.error(this.module_,"getOfferVideoMidBySsrc failed,the sdp is invalid : ".concat(e)),o)}getIdleTransceiverWithSameSsrc(e,t,r){if(!t||0===t.length)return null;const i=this.parseSdp(e);if(!i)return this.logger_.error(this.module_,"getIdleMidWithSameSsrc failed,the sdp is invalid : ".concat(e)),null;const n=i.media.find((e=>!(!e.ssrcs||0===e.ssrcs.length)&&e.ssrcs[0].id===r));let o;for(const s of t)if(n){if("".concat(n.mid)==="".concat(s.mid)){o=t.splice(t.indexOf(s),1)[0];break}}else{const e=i.media.find((e=>"".concat(e.mid)==="".concat(s.mid)));if(!e.ssrcs||0===e.ssrcs.length){o=t.shift();break}}return o}deleteSSRC(e,t,r,i){if(0===r.length&&!i)return e;this.logger_.info(this.module_,"deleteSSRC ".concat(r,", ").concat(i));const n=this.parseSdp(e),o=this.parseSdp(t);if(!n)return void this.logger_.error(this.module_,"deleteSSRC failed");null==r||r.forEach((e=>{n.media.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).forEach((t=>{var r;if(null!==(r=t.ssrcs)&&void 0!==r&&r.find((t=>t.id===e))){var i;const e=null===(i=o.media)||void 0===i?void 0:i.find((e=>"".concat(e.mid)==="".concat(t.mid)));rD.modifyDirectionWhenPublish(t,e,!1),t.ssrcs=void 0}}))})),n.media.filter((e=>e.type===mO.TRACK_TYPE_AUDIO)).forEach((e=>{var t;if(null!==(t=e.ssrcs)&&void 0!==t&&t.find((e=>e.id===i))){var r;const t=null===(r=o.media)||void 0===r?void 0:r.find((t=>"".concat(t.mid)==="".concat(e.mid)));rD.modifyDirectionWhenPublish(e,t,!1),e.ssrcs=void 0}}));const s=WM(n),a=WM(o);return this.logger_.debug(this.module_,"deleteSSRC ".concat(r," success, offer: ").concat(this.printSdpInfo(s)," answer: ").concat(this.printSdpInfo(a))),{offerSdp:s,answerSdp:a}}modifyPublishOfferSdp(e,t,r,i,n){this.logger_.debug(this.module_,"modifyPublishOfferSdp start, sdp: ".concat(this.printSdpInfo(e)));const o=this.parseSdp(e),s=this.parseSdp(t);if(!o)return void this.logger_.error(this.module_,"modifyPublishOfferSdp failed, the sdp is invalid: ".concat(e));if(this.deleteUnexpectedMedia(o),i&&i.length>0){let e=this.getAvailableSenderMedia(o,mO.TRACK_TYPE_VIDEO);null==i||i.forEach((t=>{var i;let n=e.find((e=>{var r;return null===(r=e.ssrcs)||void 0===r?void 0:r.find((e=>"".concat(e.id)==="".concat(t)))}));n?e=e.filter((e=>{var r;return!e.ssrcs||(null===(r=e.ssrcs)||void 0===r?void 0:r.find((e=>"".concat(e.id)!=="".concat(t))))})):n=e.shift(),this.transformVideoPayload(n),this.deleteRetransmissionSsrc(n),this.modifyUnifiedMediaSsrc(n,t,r);const o=null===(i=s.media)||void 0===i?void 0:i.find((e=>"".concat(e.mid)==="".concat(n.mid)));rD.modifyDirectionWhenPublish(n,o,!0)}))}o.media.filter((e=>{let{type:t,direction:r}=e;return t===mO.TRACK_TYPE_VIDEO&&r!==EM.SEND_ONLY&&r!==EM.SEND_RECV})).forEach((e=>{this.transformVideoPayload(e),this.deleteRetransmissionSsrc(e),e.ssrcs=void 0}));const a=this.getAvailableSenderMedia(o,mO.TRACK_TYPE_AUDIO);if(a&&a.length>0){const e=a[0];if(this.transformAudioPayload(e),this.deleteRetransmissionSsrc(e),n){var c;const t=null===(c=s.media)||void 0===c?void 0:c.find((t=>"".concat(t.mid)==="".concat(e.mid)));this.modifyUnifiedMediaSsrc(e,n,r),rD.modifyDirectionWhenPublish(e,t,!0)}}const u=WM(o),d=WM(s);return this.logger_.debug(this.module_,"modifyPublishOfferSdp success, offerSdp: ".concat(this.printSdpInfo(u),", answerSdp: ").concat(this.printSdpInfo(d))),{offerSdp:u,answerSdp:d}}static modifyDirectionWhenPublish(e,t,r){r?e.direction===EM.RECV_ONLY?e.direction=EM.SEND_RECV:e.direction===EM.INACTIVE&&(e.direction=EM.SEND_ONLY):e.direction===EM.SEND_ONLY?e.direction=EM.INACTIVE:e.direction===EM.SEND_RECV&&(e.direction=EM.RECV_ONLY),r?t.direction===EM.SEND_ONLY?t.direction=EM.SEND_RECV:t.direction===EM.INACTIVE&&(t.direction=EM.RECV_ONLY):t.direction===EM.SEND_RECV?t.direction=EM.SEND_ONLY:t.direction===EM.RECV_ONLY&&(t.direction=EM.INACTIVE)}generateMatchedAnswerWithOffer(e,t,r){this.logger_.debug(this.module_,"generateCorrespondingRemoteSdpMedia start, sdp: ".concat(this.printSdpInfo(e)));const i=this.parseSdp(e);this.portType_!==NC.portNormal&&rD.modifyBundle(i,t);const n=this.getMedias(i,r);if(!n||0===n.length)return e;const o=JSON.parse(JSON.stringify(n[0]));o.mid=t,delete o.ssrcs,delete o.candidates,o.direction=EM.INACTIVE,i.media.push(o);const s=WM(i);return this.logger_.debug(this.module_,"generateCorrespondingRemoteSdpMedia success, sdp: ".concat(this.printSdpInfo(s))),s}getBrowserDefaultSsrc(e){const t=this.parseSdp(e),r=this.getMedias(t,mO.TRACK_TYPE_VIDEO),i=this.getMedias(t,mO.TRACK_TYPE_AUDIO),n=[];let o;if(r&&r.length>0&&r.forEach((e=>{e.ssrcs&&e.ssrcs.length>0&&n.push(parseInt(e.ssrcs[0].id.toString()))})),i&&i.length>0)for(const s of i)if(s.ssrcs&&s.ssrcs.length>0){o=parseInt(s.ssrcs[0].id.toString());break}return{videoSsrcs:n,audioSsrc:o}}getLeastMid(e){const t=this.parseSdp(e);if(!t)return void this.logger_.error(this.module_,"getLeastMid failed, the sdp is invalid : ".concat(e));let r;for(const i of t.groups||[])if("BUNDLE"===i.type){const e=(i.mids||"").split(" ");r=e[e.length-1];break}return r}}const iD="PeerConnectionsManager";class nD extends $P{constructor(e,t,r){super({logger:e,stat:t,emitter:r}),i(this,"isFireFox",Cw.isFirefox()),this.peerConnections=new Map,Cw.isOnlySupportUnfiedPlan()?(this.sdpDescMode="unified-plan",this.rtcSdp=new rD(this.logger)):(this.sdpDescMode="plan-b",this.rtcSdp=new tD(this.logger)),this.logger.debug(iD,"ConnectionsManager, SDP mode: ".concat(this.sdpDescMode)),this.setPortType(NC.portReduce),this.mainReceiverPreStatisticMap=new Map,this.auxReceiverPreStatisticMap=new Map}setPortType(e){const t=pO.getParameter(uO)||0;0!==t&&(e=t),e===NC.portNormal&&Cw.isOnlySupportUnfiedPlan()&&(e=NC.portReduce),this.portType=e,this.portType===NC.portNormal&&(this.sdpDescMode="plan-b",this.rtcSdp=new tD(this.logger)),this.logger.debug(iD,"ConnectionsManager, portType: ".concat(1===this.portType?"normal":"reduce")),this.rtcSdp.setPortType(this.portType)}getPortType(){return this.portType}setTurnServer(e){this.turnServerConfig=e}isConnectionsExist(){return this.peerConnections.size>0}getConnectionId(){return this.uniqueId}getReceivers(e){var t;const r=null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection;if("plan-b"===this.sdpDescMode)return null==r?void 0:r.getReceivers();const i=[],n=null==r?void 0:r.getTransceivers();if(!n)return null;for(const o of n)o.currentDirection!==EM.SEND_RECV&&o.currentDirection!==EM.RECV_ONLY||i.push(o.receiver);return i}getSenders(e){var t;const r=null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection;if("plan-b"===this.sdpDescMode)return null==r?void 0:r.getSenders();const i=[],n=null==r?void 0:r.getTransceivers();if(!n)return null;for(const o of n)o.currentDirection!==EM.SEND_RECV&&o.currentDirection!==EM.SEND_ONLY||i.push(o.sender);return i}calcChangedStatistic(e,t,r){if(this.mainReceiverPreStatisticMap.has(e)||this.auxReceiverPreStatisticMap.has(e)){const i=this.mainReceiverPreStatisticMap.get(e)||this.auxReceiverPreStatisticMap.get(e);if("number"==typeof t)return Object.prototype.hasOwnProperty.call(i,r[0])?t>=i[r[0]]?t-i[r[0]]:(this.clearReveiverPreStatisticBySsrcLabel(e),t):t;this.doCalcChangedStatisticObject(e,t,i,r)}else if("number"==typeof t)return t}doCalcChangedStatisticObject(e,t,r,i){if(i&&i.length>0){let n=0;for(const e of i)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]>=r[e]?t[e]=t[e]-r[e]:n++);n>=i.length-1&&this.clearReveiverPreStatisticBySsrcLabel(e)}else{let i=0;for(const e in t)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]>=r[e]?t[e]=t[e]-r[e]:i++);i===Object.keys(t).length&&this.clearReveiverPreStatisticBySsrcLabel(e)}}clearReveiverPreStatisticBySsrcLabel(e){this.mainReceiverPreStatisticMap.delete(e)||this.auxReceiverPreStatisticMap.delete(e)}async initConnectionAndSdp(e,t,r,i){this.uniqueId=e;const n=this.createPeerConnection(t),o="main"!==t;let s=await this.createOffer(t,{offerToReceiveAudio:!o,offerToReceiveVideo:!0});if(this.isFireFox){t===gO.STREAM_TYPE_MAIN&&(await n.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(s.sdp)}),n.connection.addTransceiver("video",{direction:EM.INACTIVE}),s=await n.connection.createOffer());const e=this.rtcSdp.getBrowserDefaultSsrc(s.sdp);n.videoSendSsrcs=e.videoSsrcs,n.sendSsrcsMapping=new Map,e.videoSsrcs.forEach(((e,t)=>{n.sendSsrcsMapping.set(t,e)})),!o&&e.audioSsrc&&(n.audioSendSsrc=e.audioSsrc,n.sendSsrcsMapping.set(2,e.audioSsrc))}const a=this.rtcSdp.transformOfferSdp(s.sdp);if(await n.connection.setLocalDescription({type:"offer",sdp:a}),await this.iceAddressCollect(n.connection),!this.isFireFox){const e=n.connection.localDescription.sdp;this.logger.debug(iD,"setLocalDescription, ".concat(t,"sdp offer: ").concat(this.rtcSdp.printSdpInfo(e))),await n.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(e)})}o?this.onConnection(n,r.onTrackHandler,!0):this.rtcSdp.containsValidVideoPayload(s.sdp)||i?this.onConnection(n,r.onTrackHandler,!1):(this.destroyPeerConnection(t),this.logger.error(iD,"initConnectionAndSdp, no H264 payload and try createOffer again"),await this.initConnectionAndSdp(e,t,r,!0))}setSsrcsMapping(e){const t=this.peerConnections.get(gO.STREAM_TYPE_MAIN);t.sendSsrcsMapping&&t.sendSsrcsMapping.size>0&&(t.sendSsrcsMapping.has(0)&&(t.sendSsrcsMapping.set(e.video.sendSsrcBegin,t.sendSsrcsMapping.get(0)),t.sendSsrcsMapping.delete(0)),t.sendSsrcsMapping.has(1)&&(t.sendSsrcsMapping.set(e.video.sendSsrcEnd,t.sendSsrcsMapping.get(1)),t.sendSsrcsMapping.delete(1)),t.sendSsrcsMapping.has(2)&&(t.sendSsrcsMapping.set(e.audio.sendSsrcBegin,t.sendSsrcsMapping.get(2)),t.sendSsrcsMapping.delete(2)));const r=this.peerConnections.get(gO.STREAM_TYPE_AUX);r.sendSsrcsMapping&&r.sendSsrcsMapping.size>0&&r.sendSsrcsMapping.has(0)&&(r.sendSsrcsMapping.set(e.desktopVideo.sendSsrcBegin,r.sendSsrcsMapping.get(0)),r.sendSsrcsMapping.delete(0))}getMappingSsrcs(e,t){if(!e)return;let r;return t||"number"!=typeof e?(r=this.peerConnections.get(t),!r.sendSsrcsMapping||r.sendSsrcsMapping.size<1?e:"number"==typeof e?r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):e:e.map((e=>r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):e))):(r=this.peerConnections.get(gO.STREAM_TYPE_MAIN),r.sendSsrcsMapping.has(e)?r.sendSsrcsMapping.get(e):(r=this.peerConnections.get(gO.STREAM_TYPE_AUX),r.sendSsrcsMapping.get(e)||e))}async createOffer(e,t){const r=this.peerConnections.get(e).connection,i=await r.createOffer(t);return"plan-b"!==this.sdpDescMode&&r.getTransceivers().forEach((e=>{e.direction=EM.INACTIVE})),i}iceCandidateListener(e,t){this.logger.info(iD,"iceCandidateListener of ".concat(t)),e.connection.onicecandidate=r=>{var i;r.candidate&&"udp"===r.candidate.protocol&&(this.logger.info(iD,"".concat(t," onicecandidate: ").concat(XR.shieldIpAddress(null===(i=r.candidate)||void 0===i?void 0:i.candidate))),e.candidate||(e.candidate=[]),e.candidate.push(r.candidate))}}iceRestart(e,t,r){if(this.stat.setConnectionStatusInfo(QC.CLOSED,XC.MEDIA),e.connectFailedTimes++,this.logger.error(iD,"".concat(t?"aux":"main"," connection statechange, connectFailedTimes: ").concat(e.connectFailedTimes,".")),e.connectFailedTimes<=30&&(this.logger.error(iD,"".concat(t?"aux":"main"," connection statechange, emit media error event.")),e.connectFailedTimes%2==0&&this.eventEmitter.emit(UC.Error,{errCode:Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR,errDesc:"".concat(t?"aux":"main"," peerConnection: ").concat(Jc[Gc.RTC_ERR_CODE_MEDIA_NETWORK_ERROR])}),30===e.connectFailedTimes))return this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:t?"aux":"main",state:LC.DisConnected}),void(e.connectFailedTimes=0);e.connection.createOffer({iceRestart:!0}).then((r=>{this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:t?"aux":"main",state:LC.Reconnecting}),e.connection.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r.sdp)}),e.connection.setRemoteDescription({sdp:e.connection.remoteDescription.sdp,type:"answer"})})).finally((()=>{r&&r()}))}onConnection(e,t,r){e.connection.ontrack=e=>{t(e,r)},e.connection.onconnectionstatechange=()=>{if(this.logger.info(iD,"onconnectionstatechange, ".concat(r?"aux":"main"," connect state is: ").concat(e.connection.connectionState," ;iceConnectionState: ").concat(e.connection.iceConnectionState)),"disconnected"!==e.connection.iceConnectionState)clearTimeout(e.disConnectDelayHandleTimer),e.disConnectDelayHandleTimer=null,"failed"===e.connection.iceConnectionState||"closed"===e.connection.iceConnectionState?(this.logger.info(iD,"connect state failed go iceRestart: ".concat(e.connection.iceConnectionState)),this.iceRestart(e,r)):"connected"===e.connection.iceConnectionState&&(this.logger.info(iD,"connect state connect: ".concat(e.connection.iceConnectionState)),this.stat.setConnectionStatusInfo(QC.CONNECTED,XC.MEDIA),e.connectFailedTimes=0,this.eventEmitter.emit(UC.MediaConnectionStateChanged,{roomId:this.uniqueId,type:r?"aux":"main",state:LC.Connected}),e.connection.getStats().then((e=>{let t=null;e.forEach((e=>{"candidate-pair"===e.type&&(this.isFireFox&&e.selected||e.nominated)&&(t=e.localCandidateId)})),t&&e.forEach((e=>{e.id===t&&(this.logger.info(iD,"transport protocol changed, candidateType: ".concat(e.candidateType,", protocol: ").concat(e.protocol)),this.eventEmitter.emit(UC.TransportProtocolChanged,{protocol:e.protocol,candidateType:e.candidateType}))}))})));else{if(e.disConnectDelayHandleTimer)return;e.disConnectDelayHandleTimer=setTimeout((()=>{this.logger.info(iD,"disConnect state delay handler, go iceRestart: ".concat(e.connection.iceConnectionState)),this.iceRestart(e,r,(()=>{clearTimeout(e.disConnectDelayHandleTimer),e.disConnectDelayHandleTimer=null}))}),5e3)}}}async iceAddressCollect(e){await new Promise((t=>{let r=null;const i=()=>{this.logger.info(iD,"ICE collect Gathering State change: ".concat(e.iceGatheringState)),"complete"===e.iceGatheringState&&(clearTimeout(r),this.logger.info(iD,"ICE collect complete"),e.removeEventListener("icegatheringstatechange",i),t())};e.addEventListener("icegatheringstatechange",i),r=setTimeout((()=>{this.logger.error(iD,"ICE collect timeout"),clearTimeout(r),t()}),6e3)}))}createPeerConnection(e){const t={rtcpMuxPolicy:this.portType===NC.portReduce?"require":"negotiate",bundlePolicy:this.portType===NC.portReduce?"max-bundle":"balanced"},r=[];if(this.turnServerConfig){for(const e of this.turnServerConfig.turnServers)r.push("turn:".concat(e,":").concat(this.turnServerConfig.udpPort||3478,"?transport=udp"));t.iceServers=[{urls:r,username:this.turnServerConfig.userName,credential:this.turnServerConfig.credential}],t.iceTransportPolicy="relay"}t.sdpSemantics=this.sdpDescMode;const i=new RTCPeerConnection(t);var n;this.peerConnections.has(e)&&(null===(n=this.peerConnections.get(e).connection)||void 0===n||n.close());const o={connection:i,connectFailedTimes:0};return this.peerConnections.set(e,o),this.iceCandidateListener(o,e),o}destroyPeerConnection(e,t){const r=this.peerConnections.get(e);r&&(clearTimeout(r.disConnectDelayHandleTimer),r.connectFailedTimes=0,"closed"!==r.connection.signalingState&&(null==t||t.forEach((e=>r.connection.removeTrack(e))),r.connection.close()),"main"===e?this.mainReceiverPreStatisticMap.clear():this.auxReceiverPreStatisticMap.clear(),this.peerConnections.delete(e))}async modifySdpInfo(e,t){const r=this.peerConnections.get(e);let i=null;if(r)if("main"===e){const e=await this.getDataChannelTemplate(t);i=this.rtcSdp.modifyMainSdpInfo(r.connection.localDescription.sdp,r.candidate,r.videoSendSsrcs,r.audioSendSsrc,t,e)}else i=this.rtcSdp.modifyAuxSdpInfo(r.connection.localDescription.sdp,r.candidate,r.videoSendSsrcs);return i}async getDataChannelTemplate(e){let t=null;if(!e)return t;let r=null;try{r=new RTCPeerConnection,r.createDataChannel("dataChannelTemplate"),t=(await r.createOffer()).sdp}catch(jN){this.logger.error(iD,"getDataChannelTemplate failed, unsupport datachannel: ".concat(jN))}finally{r&&r.close()}return t}async setLocalDescriptionShim(e,t){let r;!this.isFireFox&&t||(r=(await e.createOffer()).sdp),await e.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r||t)})}async handleAnswerSdpFromServer(e,t,r){const i=this.peerConnections.get(e).connection,{remoteDescription:n,bindCryptoKey:o,wsUrl:s,dataChannelEnable:a}=this.rtcSdp.transformAnswerSdp(t,i.localDescription.sdp);let c;this.logger.debug(iD,"handleAnswerSdpFromServer, ".concat(e," sdp answer: ").concat(this.rtcSdp.printSdpInfo(n))),c=r?await r({remoteDescription:n,bindCryptoKey:o,wsUrl:s,dataChannelEnable:a}):{answerSdp:n},c.offerSdp&&c.offerSdp!==i.localDescription.sdp&&await this.setLocalDescriptionShim(i,c.offerSdp);try{await i.setRemoteDescription({type:"answer",sdp:c.answerSdp})}catch(jN){throw this.logger.error(iD,"setRemoteDescription error, answer sdp invalid or offer sdp invalid"),new qc(Gc.RTC_ERR_CODE_ANSWER_SDP_INVALID,(null==jN?void 0:jN.message)||"setRemoteDescription error, answer sdp invalid or offer sdp invalid")}}getSfuInfoFromSdp(e,t){return this.rtcSdp.getSfuInfo(e,t)}async generateAndSetOfferSdpByHandler(e,t){const r=this.peerConnections.get(e).connection;let i;i=t?await t(r.localDescription.sdp):r.localDescription.sdp,await this.setLocalDescriptionShim(r,i)}async generateAndSetAnswerSdpByHandler(e,t){const r=this.peerConnections.get(e).connection;let i;i=t?(await t(r.remoteDescription.sdp)).answerSdp:r.remoteDescription.sdp,await r.setRemoteDescription({type:"answer",sdp:i})}async deleteUser(e,t,r){const i=this.peerConnections.get(e).connection,n=i.remoteDescription.sdp;let o={offerSdp:i.localDescription.sdp,answerSdp:n};if("plan-b"===this.sdpDescMode)o.answerSdp=this.rtcSdp.deleteUser(o.answerSdp,t,r);else{const n=i.getTransceivers();t&&t.length>0&&(o=await this.rtcSdp.deleteUser(o.answerSdp,o.offerSdp,t,n,(t=>this.recordCurrentReceiverStatistic(e,t)))),r&&r.length>0&&(o=await this.rtcSdp.deleteUser(o.answerSdp,o.offerSdp,r,n,(t=>this.recordCurrentReceiverStatistic(e,t))))}await this.setLocalDescriptionShim(i,o.offerSdp),await i.setRemoteDescription({type:"answer",sdp:o.answerSdp})}async recordCurrentReceiverStatistic(e,t){const r=await t.getStats();r&&r.forEach(((t,r)=>{(this.isFireFox||/RTCInboundRTP(Video|Audio)Stream_.*/gi.test(r))&&this["main"===e?"mainReceiverPreStatisticMap":"auxReceiverPreStatisticMap"].set(r,t)}))}getAllIdleReceiverTransceivers(e,t,r){const i=e.getTransceivers(),n=this.rtcSdp.getAllMidsByType(r,t);return i.filter((e=>n.includes("".concat(e.mid))&&e.currentDirection!==EM.SEND_RECV&&e.currentDirection!==EM.RECV_ONLY))}getIdleSendTransceiver(e,t,r,i){const n=e.getTransceivers();if(this.isFireFox&&i){const e=this.rtcSdp.getOfferVideoMidBySsrc(r,t,this.getMappingSsrcs(i));return null==n?void 0:n.find((t=>t.mid===e))}const o=this.rtcSdp.getAllMidsByType(r,t);return null==n?void 0:n.find((e=>o.includes("".concat(e.mid))&&e.currentDirection!==EM.SEND_ONLY&&e.currentDirection!==EM.SEND_RECV))}async addTrack(e,t,r,i){const n=this.peerConnections.get(e).connection;if("plan-b"===this.sdpDescMode)return n.addTrack(t,r);const o=n.localDescription.sdp;let s=this.getIdleSendTransceiver(n,"audio"===t.kind?mO.TRACK_TYPE_AUDIO:mO.TRACK_TYPE_VIDEO,o,i);if(s){await s.sender.replaceTrack(t),s.direction=s.currentDirection===EM.RECV_ONLY?EM.SEND_RECV:EM.SEND_ONLY;const e=this.rtcSdp.modifyAnswerDirection(n.remoteDescription.sdp,s.mid);await this.setLocalDescriptionShim(n),await n.setRemoteDescription({type:"answer",sdp:e})}else this.logger.info(iD,"addTrack, no available sender, addTranscevier"),s=await this.addTransceiver(n,"audio"===t.kind?mO.TRACK_TYPE_AUDIO:mO.TRACK_TYPE_VIDEO),await s.sender.replaceTrack(t),s.direction=s.currentDirection===EM.RECV_ONLY?EM.SEND_RECV:EM.SEND_ONLY;return s.sender}removeTrack(e,t){const r=this.peerConnections.get(e).connection;"closed"!==r.signalingState&&r.removeTrack(t)}async modifyPublishOfferSdp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;const s=this.peerConnections.get(e).connection;let a,c,u=(await s.createOffer()).sdp;return(n&&n.length>0||o)&&("plan-b"===this.sdpDescMode?u=this.rtcSdp.deleteSSRC(u,n,o):a=this.rtcSdp.deleteSSRC(u,s.remoteDescription.sdp,this.getMappingSsrcs(n,e),this.getMappingSsrcs(o,e))),"plan-b"===this.sdpDescMode?u=this.rtcSdp.modifyPublishOfferSdp(u,r,i):a=this.rtcSdp.modifyPublishOfferSdp(a?a.offerSdp:u,a?a.answerSdp:s.remoteDescription.sdp,t,this.getMappingSsrcs(r,e),this.getMappingSsrcs(i,e)),"plan-b"===this.sdpDescMode?(await s.setLocalDescription({type:"offer",sdp:u}),await s.setRemoteDescription(s.remoteDescription),c=u):(await this.setLocalDescriptionShim(s,a.offerSdp),await s.setRemoteDescription({type:"answer",sdp:a.answerSdp}),c=a.offerSdp),c}async addTopAudioUserBatch(e,t,r,i){const n=this.peerConnections.get("main").connection;let o,s={offerSdp:n.localDescription.sdp,answerSdp:e};"plan-b"!==this.sdpDescMode&&(o=this.getAllIdleReceiverTransceivers(n,mO.TRACK_TYPE_AUDIO,s.answerSdp));for(let a=0;a{clearTimeout(e),t.receiver.track.enabled=!0}),300)}}else t=await this.addTransceiver(r,mO.TRACK_TYPE_VIDEO,a);t.direction=t.currentDirection===EM.SEND_ONLY?EM.SEND_RECV:EM.RECV_ONLY,a=this.rtcSdp.modifySdpByMid(a.answerSdp,a.offerSdp,t.mid,c,e.streamId,e.videoSsrc)}await this.setLocalDescriptionShim(r,a.offerSdp),await r.setRemoteDescription({type:"answer",sdp:a.answerSdp})}}async addTransceiver(e,t,r){var i;e.addTransceiver(t,{direction:EM.INACTIVE});const n=await e.createOffer();await this.setLocalDescriptionShim(e,n.sdp);const o=this.rtcSdp.getLeastMid(n.sdp),s=this.rtcSdp.generateMatchedAnswerWithOffer((null==r?void 0:r.answerSdp)||e.remoteDescription.sdp,o,t);return r&&(r.offerSdp=n.sdp,r.answerSdp=s),await e.setRemoteDescription({type:"answer",sdp:s}),null===(i=e.getTransceivers())||void 0===i?void 0:i.find((e=>"".concat(e.mid)===o))}getConnection(e){var t;return this.isConnectionsExist()&&this.peerConnections.get(e)?null===(t=this.peerConnections.get(e))||void 0===t?void 0:t.connection:null}getConnectionRTT(){let e=0;if(!this.isConnectionsExist())return e;const t=CO.getLatestReport(this.uniqueId,gO.STREAM_TYPE_MAIN);if(t){const r=t.get("candidate-pair");e=r&&r.currentRoundTripTime||0}return e}getICETransportStat(e){if(!e)throw this.logger.error(iD,"getICETransportStat, pcType is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"pcType is null");const t=CO.getLatestReport(this.uniqueId,e);if(!t)return null;try{const e=t.get("candidate-pair");return{currentRoundTripTime:e.currentRoundTripTime||0,availableOutgoingBitrate:e.availableOutgoingBitrate||0,bytesSent:e.bytesSent||0,bytesReceived:e.bytesReceived||0}}catch(jN){return this.logger.error(iD,"getICETransportStat failed",jN),null}}getInfo(){return{moduleName:"PeerConnectionsManager"}}async refreshOffer(e){const t=this.peerConnections.get(e).connection,r=await t.createOffer();return await t.setLocalDescription({type:"offer",sdp:this.rtcSdp.transformOfferSdp(r.sdp)}),r}}var oD={exports:{}};!function(e,t){self,e.exports=function(){var e={d:function(t,r){for(var i in r)e.o(r,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{GrsBaseInfo:function(){return O},GrsClient:function(){return M},GrsErrorCode:function(){return s},Logger:function(){return l}});var r=function(e){return"string"!=typeof e||""==e},i=function(e){return void 0===e||null==e||"{}"==JSON.stringify(e)},n=function(e){return!(void 0!==e&&e instanceof Array&&"[]"!=JSON.stringify(e))},o=function(e){if("string"!=typeof e||""==e)return{};try{var t=JSON.parse(e);return void 0===t||null==t?{}:t}catch(e){return{}}},s={ERR_OK:0,ERR_INTERNAL_ERROR:1,ERR_INVALID_PARAM:2,ERR_INIT:3,GRS_SET_ROUTER_DIR:4,GRS_SET_SYSTEM_INFO:5,GRS_SERVICE_CONFIGURE_NO_FILE:6,GRS_SERVICE_CONFIGURE_READ_ERROR:7,GRS_SET_CA_FILE:8,GRS_SERVICE_CONFIGURE_PARSE_ERROR:9,GRS_SERVICE_CONFIGURE_PARSE_VALUE_ERROR:10,GRS_ROUTER_CONFIGURE_EMPTY:11,GRS_ROUTER_APP_CONFIGURE_READ_ERROR:12,GRS_ROUTER_SDK_CONFIGURE_READ_ERROR:13,GRS_ROUTER_CONFIGURE_PARSE_VALUE_ERROR:14,GRS_ROUTER_SERVER_NAME_EMPTY:15,GRS_ROUTER_BY_EMPTY:16,GRS_APK_ROUTER_NO_APPLICATION:17,GRS_NOT_FIND:18,GRS_NOT_FIND_APPLICATION:19,GRS_NOT_FIND_SERVICE_LIST:20,GRS_NOT_FIND_SERVING_COUNTRY_GROUP:21,GRS_NOT_FIND_SERVICE:22,GRS_NOT_FIND_ADDRESS:23,GRS_NOT_FIND_COUNTRY:24};function a(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r");for(var c in a){if("ser_country"===a[c]&&!r(t)){s=t;break}if("reg_country"===a[c]&&!r(i)){s=i;break}if("issue_country"===a[c]&&!r(n)){s=n;break}if("geo_ip"===a[c]&&!r(o)){s=o;break}}return s},p=function(e,t){var r="";for(var i in e)if(e[i].countriesOrAreas.includes(t)){r=e[i].id;break}return r},m=function(e,t){var r={};if(i(e))return r;var n=e.errorList;if(!i(n)&&t in n)return r.results=n[t],r.status="failure",r;var o=e.services;return!i(o)&&t in o?(r.results=o[t],r.status="success",r):(r.results="GRS_NOT_FIND_SERVICE",r.status="notFindService",r)},g=function(e,t,r,i){var n="",o=m(e,r);if("success"===o.status&&i in o.results)return l.i("getGrsUrl","Return The Server Cached Data"),o.results[i];l.i("getGrsUrl","Cannot find "+r+"("+i+") in serverUrlInfo: ",JSON.stringify(e));var s=m(t,r);return"success"===s.status&&i in s.results?(l.i("getGrsUrl","Return The Local JSON Data"),n=s.results[i]):l.i("getGrsUrl","Cannot find "+r+"("+i+") in localUrlInfo: ",JSON.stringify(t)),n},_=function(e,t,r){var i={},n=m(e,r);if("success"===n.status)return l.i("getGrsUrl","Return The Server Cached Data"),n.results;l.i("getGrsUrl","Cannot find "+r+" in serverUrlInfo: ",JSON.stringify(e));var o=m(t,r);return"success"===o.status?i=o.results:l.i("getGrsUrl","Cannot find "+r+" in localUrlInfo: ",JSON.stringify(t)),i};function S(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function v(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,i=new Array(t);r=(new Date).getTime())return l.i("getGrsDataFromServerOrCache","During The Suppression Or The Cache Not Expired"),void t(a);c=r(a.header.ETag)?"&":a.header.ETag,b(t,e,a,s,c)}))},b=function(e,t,n,o,s){C(t,s).then((function(t){if(l.d("getGrsDataFromServerOrCache","handleGrsDataFromServer: ",t),t.success){if(200===t.statusCode)return localStorage.setItem(o,JSON.stringify(t)),void e(t);if(304===t.statusCode)return n["cache-time"]=(new Date).getTime(),n.header=t.header,localStorage.setItem(o,JSON.stringify(n)),void e(n);if(503===t.statusCode)return void function(e,t,n,o){i(e)||r(e)?(t.header["cache-control"]="private,max-age="+t.header["Retry-After"],localStorage.setItem(n,JSON.stringify(t)),o(t)):(e["cache-time"]=(new Date).getTime(),e.header["cache-control"]="private,max-age="+t.header["Retry-After"],localStorage.setItem(n,JSON.stringify(e)),o(e))}(n,t,o,e);i(n)||r(n)?(t.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(t)),e(t)):(n["cache-time"]=(new Date).getTime(),n.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(n)),e(n))}})).catch((function(t){l.i("getGrsDataFromServerOrCache","handleGrsDataFromServer catch: ",t),i(n)||r(n)?(localStorage.setItem(o,JSON.stringify(t)),e(t)):(n["cache-time"]=(new Date).getTime(),n.header["cache-control"]="private,max-age=300",localStorage.setItem(o,JSON.stringify(n)),e(n))}))},C=function(e,t){var r=e.getServerConfig().grs_server.grs_query_timeout,i=e.getServerConfig().grs_server.grs_base_url,n=e.getServerConfig().grs_server.grs_query_endpoint,o=[];for(var s in i)o.push(i[s]+n+"?"+e.getGrsReqParamJoint());return function(e,t,r,i){l.i("post","urls: ",e);var n=[];return e.forEach((function(e){n.push(R(e,t,r,1e3*i))})),Promise.race(n)}(o,e._servicList,{"Content-Type":"application/json;charset=UTF-8","User-Agent":e.getUserAgent(),"If-None-Match":t},r)};function A(e){return function(e){if(Array.isArray(e))return w(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return w(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?w(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r0?t.match(/msie [\d.]+;/gi):t.indexOf("firefox")>0?t.match(/firefox\/[\d.]+/gi):t.indexOf("chrome")>0?t.match(/chrome\/[\d.]+/gi):t.indexOf("safari")>0&&t.indexOf("chrome")<0?t.match(/safari\/[\d.]+/gi):void 0)[0].replace("/","; ")}catch(t){e="unknown; web-browser"}return this.packageName+"/"+this.versionName+" ("+e+"; NA) network-grs-web/5.0.9.300 "+this.serviceName}}])&&k(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function P(e,t){for(var r=0;r{r.userState===IO.Joined&&(r.mainStream&&r.mainStream.remoteTrackInfos&&r.mainStream.remoteTrackInfos.forEach((r=>{r.cssrc===e&&(t=r.mute)})),r.auxStream&&r.auxStream.remoteTrackInfos&&r.auxStream.remoteTrackInfos.forEach((r=>{r.cssrc===e&&(t=r.mute)})))})),t}checkRemoteTop3NeedReport(){let e=0;return this.remoteUserInfos.forEach((t=>{t.userState===IO.Joined&&t.mainStream&&t.mainStream.remoteTrackInfos&&t.mainStream.remoteTrackInfos.forEach((t=>{t.type===mO.TRACK_TYPE_AUDIO&&e++}))})),!(e<3)}initialize(e,t){e&&t&&(this.localUserId=e,this.audioCssrcs=this.getCssrcRangeByType(t,_D.audio),this.mainVideoCssrcs=this.getCssrcRangeByType(t,_D.mainVideo),this.auxVideoCssrcs=this.getCssrcRangeByType(t,_D.auxVideo))}getStreamInfoByPStreamUid(e){let t=null;return Array.from(this.remoteUserInfos.values()).forEach((r=>{var i,n,o;if(null!==(i=r.mainStream)&&void 0!==i&&i.remoteTrackInfos.get(e.toString()))t=null===(o=r.mainStream)||void 0===o?void 0:o.remoteTrackInfos.get(e.toString());else if(null!==(n=r.auxStream)&&void 0!==n&&n.remoteTrackInfos.get(e.toString())){var s;t=null===(s=r.auxStream)||void 0===s?void 0:s.remoteTrackInfos.get(e.toString())}})),t}getCssrcRangeByType(e,t){if(!e)throw this.logger.error(SD,"sdpRepInfo is null"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);const r=t===_D.audio?e.audio:t===_D.mainVideo?e.video:e.desktopVideo,i=null==r?void 0:r.receiveSsrcBegin,n=null==r?void 0:r.receiveSsrcEnd;if(!i||!n||i>=n)throw this.logger.error(SD,"begin or end is invalid"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);return vD.getCssrcRange(i,n)}static getCssrcRange(e,t){const r=[];let i;for(i=e;i<=t;i++)r.push(i);return r}refreshRemoteUserList(e,t,r){const i=[],n=this.getUserStreamUpdatedList(e,t);return n?(n.addedUsers.forEach((t=>{const n=this.addUser(t,e,r);n&&i.push(n)})),n.updatedUsers.forEach((t=>{const n=this.updateUser(t,e,r);n&&i.push(n)})),n.removedUsers.forEach((t=>{const n=this.removeUser(t,e,r);n&&i.push(n)})),this.logger.info(SD,"refreshRemoteUserStreamList success, ".concat(this.getTracksUpdateInfosString(i))),i):null}addUser(e,t,r){return this.updateUser(e,t,r)}updateUser(e,t,r){var i,n,o;if(e.userId===this.localUserId)return null;const s={userId:e.userId,userUid:e.userUid,nickname:e.appData.nickname,roomId:t,relaySrcRoomId:null===(i=e.relayUserSrcInfo)||void 0===i?void 0:i.roomId},a=null===(n=e.videoStreams)||void 0===n?void 0:n.filter((e=>e.content!==CC.desktop)),c=null===(o=e.videoStreams)||void 0===o?void 0:o.filter((e=>e.content===CC.desktop)),u=e.audioStreams,d=this.getUserInfoById(s.userId,s.roomId),l=this.doRefreshRemoteStreamList(s,gO.STREAM_TYPE_MAIN,a,u,r),h=this.doRefreshRemoteStreamList(s,gO.STREAM_TYPE_AUX,c,null,r),f=this.getUserInfoById(s.userId,s.roomId);return{userInfo:f.userInfo,preUserState:d?f.userState:IO.NotJoin,curUserState:f.userState,isUserNameChanged:null,mainStream:l,auxStream:h}}removeUser(e,t,r){if(e.userId===this.localUserId)return null;const i={userId:e.userId,userUid:e.userUid,nickname:e.appData.nickname,roomId:t};this.doRefreshRemoteStreamList(i,gO.STREAM_TYPE_MAIN,[],[],r),this.doRefreshRemoteStreamList(i,gO.STREAM_TYPE_AUX,[],[],r);const n={status:pD.exitRoom,userId:e.userId,userUid:e.userUid},o=this.updateUserListInfo(t,[n]);return o&&0!==o.length?o[0]:null}getUserStreamUpdatedList(e,t){const r=this.getAllUserInfos(e),i=[],n=[],o=[];return r.forEach((e=>{if(e.userInfo.userId===wC)return;const r=t.find((t=>t.userId===e.userInfo.userId)),i=this.getAllTracksByMediaType(e.userInfo.roomId,e.userInfo.userId,mO.TRACK_TYPE_VIDEO),s=this.getAllTracksByMediaType(e.userInfo.roomId,e.userInfo.userId,mO.TRACK_TYPE_AUDIO);if(r){r.audioStreams&&(r.audioStreams=r.audioStreams.filter((e=>"main"===e.content)));const e={userId:r.userId,userUid:r.userUid,appData:r.appData,videoStreams:r.videoStreams,audioStreams:r.audioStreams,relayUserSrcInfo:r.relayUserSrcInfo};n.push(e)}else{const t=i.map((e=>({content:e.content,codec:e.codec,fps:e.fps,height:e.height,maxFs:e.maxFs,maxMbps:e.maxMbps,mute:e.mute,pt:e.pt,ssrc:e.pssrc,streamData:e.streamData,streamUid:parseInt(e.trackId),width:e.width}))),r=s.map((e=>({content:e.content,codec:e.codec,maxMbps:e.maxMbps,mute:e.mute,pt:e.pt,ssrc:e.pssrc,streamData:e.streamData,streamUid:parseInt(e.trackId),channels:e.channels,sampleRate:e.sampleRate}))),n={userId:e.userInfo.userId,userUid:e.userInfo.userUid,appData:{nickname:e.userInfo.nickname},videoStreams:t,audioStreams:r};o.push(n)}})),t.forEach((e=>{if(!r.some((t=>t.userInfo.userId===e.userId))){e.audioStreams&&(e.audioStreams=e.audioStreams.filter((e=>"main"===e.content)));const t={userId:e.userId,userUid:e.userUid,appData:e.appData,videoStreams:e.videoStreams,audioStreams:e.audioStreams,relayUserSrcInfo:e.relayUserSrcInfo};i.push(t)}})),{addedUsers:i,updatedUsers:n,removedUsers:o}}updateUserListInfo(e,t){if(!t||!e)return null;const r=[],i=[];return t.forEach((t=>{var n;const o={userId:t.userId,userUid:t.userUid,roomId:e,nickname:t.appData?t.appData.nickname:null,relaySrcRoomId:null===(n=t.relayUserSrcInfo)||void 0===n?void 0:n.roomId},s=this.updateUserInfo(o,t.status);s&&r.push(s),i.push(t.userId)})),r.push(...this.getOtherRemoteUserPublishInfos(i,e)),this.logger.info(SD,"updateUserListInfo success, ".concat(this.getTracksUpdateInfosString(r))),r}updateUserInfo(e,t){if(this.logger.info(SD,"updateUserInfo begin, updateType:".concat(t,", userInfo: ").concat(JSON.stringify(e))),e.userId===this.localUserId)return null;const r=this.getUserInfoById(e.userId,e.roomId),i=r?r.userState:IO.NotJoin,n=!!r&&vD.isUserNameChanged(r.userInfo,null==e?void 0:e.nickname);switch(t){case pD.exitRoom:if(!r)return this.logger.error(SD,"remote user leave, but user not exist"),null;break;case pD.joinRoom:r||this.initializeRemoteUser(e,!0);break;default:this.logger.error(SD,"updateUserInfo, unknown user status:".concat(t))}const o=this.getUserInfoById(e.userId,e.roomId),s=t===pD.joinRoom?vD.getUserUpdateInfoWhenJoin(i,n,o):vD.getUserUpdateInfoWhenQuit(i,o);if(t===pD.exitRoom&&o.userState===IO.NotJoin){const t=vD.generateUniqueId(e.userId,e.roomId);this.remoteUserInfos.delete(t)}return s}static getUserUpdateInfoWhenJoin(e,t,r){return r.userState=e===IO.Rejoining?IO.Joined:r.userState,{userInfo:r.userInfo,preUserState:e,curUserState:r.userState,isUserNameChanged:t,mainStream:null,auxStream:null}}static getUserUpdateInfoWhenQuit(e,t){return t.userState=e===IO.Rejoining?e:IO.NotJoin,{userInfo:t.userInfo,preUserState:e,curUserState:t.userState,isUserNameChanged:null,mainStream:vD.getStreamListUpdateInfoWhenQuitOrRejoin(t,gO.STREAM_TYPE_MAIN,e),auxStream:vD.getStreamListUpdateInfoWhenQuitOrRejoin(t,gO.STREAM_TYPE_AUX,e)}}static getStreamListUpdateInfoWhenQuitOrRejoin(e,t,r){return r===IO.Rejoining?vD.getStreamListUpdateInfoWhenRejoin(e,t):vD.getStreamListUpdateInfoWhenQuit(e,t)}static getStreamListUpdateInfoWhenQuit(e,t){const r=t===gO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,i=vD.getRemoteTrackInfos(r),n=null==i?void 0:i.filter((e=>e.isSubscribed));return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:[],updatedTracks:[],removedTracks:i,subscribedTracks:n,tracks4Subscribe:[],tracks4Unsubscribe:n,allSubscribeTracks:[]}}static getStreamListUpdateInfoWhenRejoin(e,t){const r=t===gO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,i=vD.getRemoteTrackInfos(r),n=null==i?void 0:i.filter((e=>e.isSubscribed));return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:[],updatedTracks:[],removedTracks:i,subscribedTracks:n,tracks4Subscribe:[],tracks4Unsubscribe:[],allSubscribeTracks:n}}getTracks4UnSubscribe(e){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const t=[];return e.forEach((e=>{e.isSubscribed&&(e.isSubscribed=!1,t.push(e))})),this.logger.info(SD,"getTracks4UnSubscribe success, tracks4Unsubscribe: ".concat(JSON.stringify(t))),t}cachePlayInfo(e,t,r,i,n){if(!n)return;const o=this.getUserInfoById(e.userId,e.roomId),s=t===gO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,a=null==s?void 0:s.subscribeOption;return a?vD.isStreamRemoved(r,i)?(a.audio=!1,a.video=!1,void(a.resolutions=null)):void n.forEach((e=>{if(e.isSubscribed){if(a.audio&&e.type===mO.TRACK_TYPE_AUDIO){var t;const r=null==s||null===(t=s.remoteStream)||void 0===t?void 0:t.getAudioHRTCTrack();r&&(a.audioPlayInfo.playElement=r.getElementId(),a.audioPlayInfo.objectFit=r.getObjectFit(),a.audioPlayInfo.muted=r.getTrackMuted(),e.muted=r.getTrackMuted())}if(a.video&&e.type===mO.TRACK_TYPE_VIDEO){var r;const t=null==s||null===(r=s.remoteStream)||void 0===r?void 0:r.getVideoHRTCTrackByTrackId(e.trackId);if(t){var i;const r=null===(i=a.resolutions)||void 0===i?void 0:i.find((t=>t.resolutionId===e.trackId));r&&(r.playElement=t.getElementId(),r.objectFit=t.getObjectFit(),r.muted=t.getTrackMuted(),e.muted=t.getTrackMuted())}}}})):void 0}static isStreamRemoved(e,t){return!(e&&0!==e.length||t&&0!==t.length)}getTracks4Subscribe(e,t,r,i,n){if(this.logger.debug(SD,"getTracks4Subscribe begin"),!(i&&0!==i.length||n&&0!==n.length))return this.logger.debug(SD,"getTracks4Subscribe success, tracks4Subscribe: []"),[];const o=n.filter((e=>e.isSubscribed)),s=[],a=this.isAudioTrackNeedSubscribe(e.userId,e.roomId,t),c=i.find((e=>e.type===mO.TRACK_TYPE_AUDIO));if(a&&c){c.cssrc=this.allocateAudioReceiveSsrc(e.roomId),c.isSubscribed=!0,c.state=TO.resolutionChange;const r=this.getAudioTrackPlayInfo(e.userId,e.roomId,t);r&&(c.playElement=r.playElement,c.objectFit=r.objectFit,c.muted=r.muted);const i=o.find((e=>e.type===mO.TRACK_TYPE_AUDIO));i&&(c.state=i.state,c.muted=i.muted),s.push(c)}const u=o.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)),d=i.filter((e=>e.type===mO.TRACK_TYPE_VIDEO));for(const l of d){const r={resolutionId:l.trackId,width:l.width,height:l.height};if(this.updateVideoSubscribeOption(e.userId,e.roomId,t,r,u)){l.cssrc=this.allocateVideoReceiveSsrc(e.roomId,t),l.isSubscribed=!0,l.state=TO.resolutionChange;const i=this.getVideoTrackPlayInfo(e.userId,e.roomId,t,r);i&&(l.playElement=i.playElement,l.objectFit=i.objectFit,l.muted=i.muted);const n=this.getTrack4Replace(l,u);n&&n.state!==TO.normal&&(l.state=n.state,l.muted=n.muted),s.push(l)}}return this.logger.info(SD,"getTracks4Subscribe success, tracks4Subscribe: ".concat(JSON.stringify(s))),s}getAudioTrackPlayInfo(e,t,r){var i;const n=this.getUserInfoById(e,t);return null===(i=(r===gO.STREAM_TYPE_MAIN?n.mainStream:n.auxStream).subscribeOption)||void 0===i?void 0:i.audioPlayInfo}getVideoTrackPlayInfo(e,t,r,i){var n,o;const s=this.getUserInfoById(e,t),a=null===(n=(r===gO.STREAM_TYPE_MAIN?s.mainStream:s.auxStream).subscribeOption)||void 0===n||null===(o=n.resolutions)||void 0===o?void 0:o.find((e=>e.resolutionId===i.resolutionId));return a?{playElement:a.playElement,objectFit:a.objectFit,muted:a.muted}:null}updateVideoSubscribeOption(e,t,r,i,n){const o=this.getUserInfoById(e,t),s=r===gO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,a=null==s?void 0:s.subscribeOption;if(!a)return!1;if(!a.video)return!1;const c=a.resolutions.find((e=>e.resolutionId===i.resolutionId||e.height===i.height&&e.width===i.width||(null==n?void 0:n.length)));return c&&(c.resolutionId=i.resolutionId),!!c}enableTopThreeAudioMode(e){const t=this.getAllUserInfos(e);null==t||t.forEach((e=>{var t,r;null!==(t=e.mainStream)&&void 0!==t&&t.subscribeOption&&(e.mainStream.subscribeOption.audio=!1),null!==(r=e.auxStream)&&void 0!==r&&r.subscribeOption&&(e.auxStream.subscribeOption.audio=!1)})),this.logger.info(SD,"enableTopThreeAudioMode success")}isAudioTrackNeedSubscribe(e,t,r){var i;const n=this.getUserInfoById(e,t),o=r===gO.STREAM_TYPE_MAIN?n.mainStream:n.auxStream;return null==o||null===(i=o.subscribeOption)||void 0===i?void 0:i.audio}getTrack4Replace(e,t){return(null==t?void 0:t.find((t=>t.trackId===e.trackId||t.height===e.height&&t.width===e.width)))||(null!=t&&t.length?t[0]:null)}getAllUserStreamsByType(e,t,r){return this.getAllUserInfos(e).map((i=>{const n=t&&t!==gO.STREAM_TYPE_MAIN?null:vD.getStreamInfoByType(i,gO.STREAM_TYPE_MAIN,r),o=t&&t!==gO.STREAM_TYPE_AUX?null:vD.getStreamInfoByType(i,gO.STREAM_TYPE_AUX,r);return{userId:i.userInfo.userId,roomId:e,mainStream:n,auxStream:o}}))}static getStreamInfoByType(e,t,r){const i=t===gO.STREAM_TYPE_MAIN?e.mainStream:e.auxStream,n=vD.getRemoteTrackInfos(i),o=vD.getTracksByType(n,r);return{remoteStream:i?i.remoteStream:null,tracks:o}}getUserInfoById(e,t){const r=vD.generateUniqueId(e,t);return this.remoteUserInfos.get(r)}getUserInfoByUid(e,t){let r=null;for(const i of this.remoteUserInfos.values())if(i.userInfo.userUid===e&&i.userInfo.roomId===t){r=i;break}return r}static getTracksByType(e,t){return e&&0!==e.length?t?e.filter((e=>e.type===t)):e:[]}static isUserNameChanged(e,t){return t&&e&&e.nickname&&e.nickname!==t}static getRemoteTrackInfos(e){return null!=e&&e.remoteTrackInfos?Array.from(e.remoteTrackInfos.values()):null}getAllTracksByMediaType(e,t,r){var i,n;const o=vD.generateUniqueId(t,e),s=this.remoteUserInfos.get(o);if(!s)return null;const a=[],c=null===(i=vD.getRemoteTrackInfos(s.mainStream))||void 0===i?void 0:i.filter((e=>e.type===r));c&&a.push(...c);const u=null===(n=vD.getRemoteTrackInfos(s.auxStream))||void 0===n?void 0:n.filter((e=>e.type===r));return u&&a.push(...u),a}getMaxResolutionTrack(e){let t;for(const r of e)r.type!==mO.TRACK_TYPE_AUDIO&&(t?Math.max(r.width,r.height)-Math.max(t.width,t.height)>0&&(t=r):t=r);return this.logger.info(SD,"getMaxResolutionTrackId, maxResolution: ".concat(JSON.stringify(t))),t}getMaxResolutionTrackId(e){var t;if(!e)return null;const r=Array.from(e.remoteTrackInfos.values());let i;for(const n of r)n.type!==mO.TRACK_TYPE_AUDIO&&(i?Math.max(n.width,n.height)-Math.max(i.width,i.height)>0&&(i=n):i=n);return this.logger.info(SD,"getMaxResolutionTrackId, maxResolution: ".concat(JSON.stringify(i))),null===(t=i)||void 0===t?void 0:t.trackId}getAllSubscribedMainStream(e){const t=this.getAllUserInfos(e),r=[];return t.forEach((e=>{var t;null!==(t=e.mainStream)&&void 0!==t&&t.remoteTrackInfos&&Array.from(e.mainStream.remoteTrackInfos.values()).some((e=>e.isSubscribed))&&r.push(e)})),r}batchSubscribeMainStream(e,t){if(!e||!t)return null;const r=this.getAllSubscribedMainStream(e),i=[],n=t.find((e=>e.userId===wC));if(n){this.getUserInfoById(wC,e)||this.createRemoteShadowUser(e,n.resolutionIds)}return this.getAllUserInfos(e).forEach((n=>{const o=t.find((e=>e.userId===n.userInfo.userId));if(o){const t={video:!0,audio:!1,resolutionIds:o.resolutionIds,autoAdjustResolution:o.autoAdjustResolution,minResolution:o.minResolution},r=this.subscribeSingleStream(o.userId,e,gO.STREAM_TYPE_MAIN,t,_O.TOPN_AUDIOPOLICY,!0);i.push(r)}else{var s;const e=vD.getRemoteTrackInfos(n.mainStream),o=null==e?void 0:e.filter((e=>e.isSubscribed)),a=this.needUnsubscribeMainStream(n,t,r),c=vD.getAnotherStreamUpdateInfo(gO.STREAM_TYPE_MAIN,n),u={userInfo:n.userInfo,curUserState:n.userState,preUserState:n.userState,mainStream:{remoteStream:null===(s=n.mainStream)||void 0===s?void 0:s.remoteStream,preTracks:e,curTracks:e,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:o,tracks4Subscribe:null,tracks4Unsubscribe:o,allSubscribeTracks:a?null:o},auxStream:c};i.push(u)}})),this.logger.info(SD,"batchSubscribeMainStream success, infos: ".concat(this.getTracksUpdateInfosString(i))),i}needUnsubscribeMainStream(e,t,r){const i=!t.some((t=>t.userId===e.userInfo.userId)),n=r.some((t=>e.userInfo.userId===t.userInfo.userId));return i&&n}createRemoteShadowUser(e,t){const r={userId:wC,userUid:kC,nickname:"",roomId:e},i=[];null==t||t.forEach((e=>{const t=gD[e]||gD.LD,r={content:CC.main,ssrc:t.pssrc,streamUid:t.streamUid,pt:AM.h264PayLoad,width:t.width,height:t.height};i.push(r)})),this.doRefreshRemoteStreamList(r,gO.STREAM_TYPE_MAIN,i,null,!1),this.logger.info(SD,"createRemoteShadowUser success, upstreams: ".concat(JSON.stringify(i)))}subscribeResultCallback(e,t){if(e)try{e.successSubscribeInfos.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{e.state=TO.normal})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{e.state=TO.normal}))})),e.failSubscribeInfos.forEach((e=>this.releaseResource(e,t))),e.successUnsubscribeInfos.forEach((e=>this.releaseResource(e,!1))),e.failUnsubscribeInfos.forEach((e=>this.recoverUnsubscribeResource(e,t))),this.logger.info(SD,"subscribeResultCallback success")}catch(jN){this.logger.error(SD,"subscribeResultCallback fail, errMsg:".concat(jN))}}releaseResource(e,t){var r,i,n,o;const s=this.getUserInfoById(e.userId,e.roomId);null==e||null===(r=e.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i||i.forEach((r=>{if(this.unAllocateReceiveSsrc(e.roomId,gO.STREAM_TYPE_MAIN,r.type,r.cssrc),r.state=TO.normal,r.isSubscribed=!1,r.isTrackReady=!1,r.cssrc=0,t){const e=s.mainStream.subscribeOption;vD.recoverUnsubscribeOption(e,r)}})),null==e||null===(n=e.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o||o.forEach((r=>{if(this.unAllocateReceiveSsrc(e.roomId,gO.STREAM_TYPE_AUX,r.type,r.cssrc),r.state=TO.normal,r.isSubscribed=!1,r.isTrackReady=!1,r.cssrc=0,t){const e=s.mainStream.subscribeOption;vD.recoverUnsubscribeOption(e,r)}}))}recoverUnsubscribeResource(e,t){var r,i,n,o;const s=this.getUserInfoById(e.userId,e.roomId);null==e||null===(r=e.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i||i.forEach((r=>{var i;this.recoverReceiveSsrc(e.roomId,gO.STREAM_TYPE_MAIN,r.type,r.cssrc),r.isSubscribed=!0;const n=null===(i=s.mainStream)||void 0===i?void 0:i.remoteTrackInfos;if(n.has(r.trackId)||n.set(r.trackId,r),t){const e=s.mainStream.subscribeOption;vD.recoverSubscribeOption(e,r)}})),null==e||null===(n=e.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o||o.forEach((r=>{var i;this.recoverReceiveSsrc(e.roomId,gO.STREAM_TYPE_AUX,r.type,r.cssrc),r.isSubscribed=!0;const n=null===(i=s.auxStream)||void 0===i?void 0:i.remoteTrackInfos;if(n.has(r.trackId)||n.set(r.trackId,r),t){const e=s.mainStream.subscribeOption;vD.recoverSubscribeOption(e,r)}}))}static recoverSubscribeOption(e,t){if(t.type===mO.TRACK_TYPE_AUDIO)e.audio=!0;else{e.video=!0;const r={resolutionId:t.trackId,width:t.width,height:t.height};e.resolutions.push(r)}}static recoverUnsubscribeOption(e,t){if(t.type===mO.TRACK_TYPE_AUDIO)e.audio=!1;else{if(!e.video)return;e.resolutions?e.resolutions.forEach((t=>{var r;const i=null==e||null===(r=e.resolutions)||void 0===r?void 0:r.map((e=>e.resolutionId)).indexOf(t.resolutionId);i>-1&&e.resolutions.splice(i,1)})):(e.video=!1,e.resolutions=null)}}subscribeStream(e,t,r,i,n,o,s){const a=this.subscribeSingleStream(e,t,r,i,n,o),c=[];if(s&&(s.streamIds=[]),a){c.push(a);(r===gO.STREAM_TYPE_MAIN?a.mainStream.tracks4Subscribe:a.auxStream.tracks4Subscribe).forEach((e=>{e.trackId&&s&&s.streamIds.push(e.trackId)}))}return c.push(...this.getOtherRemoteUserPublishInfos([e],t)),this.logger.info(SD,"subscribeStream success, ".concat(this.getTracksUpdateInfosString(c))),c}subscribeSingleStream(e,t,r,i,n){var o,s;let a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],c=arguments.length>6&&void 0!==arguments[6]&&arguments[6];if(!e||!t||!i)return null;const u=this.getUserInfoById(e,t);if(!u)return this.logger.error(SD,"subscribeStream fail, user not exist}"),null;const d=[],l=[],h=[],f=vD.getRemoteTrackInfos(u.mainStream),p=vD.getRemoteTrackInfos(u.auxStream),m=r===gO.STREAM_TYPE_MAIN?f:p,g=null==m?void 0:m.filter((e=>e.isSubscribed));this.updateAudioTrackSubInfo(r,i,c,u,n,d,l,h),this.updateVideoTrackSubInfo(r,i,a,u,d,l,h),this.updateSubscribeOption(e,t,r,i,mD.subscribe);const _={remoteStream:r===gO.STREAM_TYPE_MAIN?null===(o=u.mainStream)||void 0===o?void 0:o.remoteStream:null===(s=u.auxStream)||void 0===s?void 0:s.remoteStream,preTracks:m,curTracks:m,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:g,tracks4Subscribe:d,tracks4Unsubscribe:l,allSubscribeTracks:h},S=vD.getAnotherStreamUpdateInfo(r,u);return{curUserState:u.userState,preUserState:u.userState,userInfo:u.userInfo,mainStream:r===gO.STREAM_TYPE_MAIN?_:S,auxStream:r===gO.STREAM_TYPE_AUX?_:S}}resubscribeMainStreamAudio(e){const t=this.previousAudioSubscribedUsers.get(e),r=t?Array.from(t.values()):null;if(this.logger.info(SD,"resubscribeMainStreamAudio, preAudioSubscribedUsers: ".concat(r)),!r)return null;const i={video:!1,audio:!0},n=[];r.forEach((t=>{var r,o;const s=this.subscribeSingleStream(t,e,gO.STREAM_TYPE_MAIN,i,_O.USER_SUBSCRIBE_AUDIOPOLICY);(null==s||null===(r=s.mainStream)||void 0===r||null===(o=r.tracks4Subscribe)||void 0===o?void 0:o.length)>0&&n.push(s)}));const o=[];return o.push(...n),o.push(...this.getOtherRemoteUserPublishInfos(r,e)),this.logger.info(SD,"resubscribeMainStreamAudio success, ".concat(this.getTracksUpdateInfosString(o))),n}unsubscribeAllMainStreamAudio(e){const t={video:!1,audio:!0},r=[],i=[];return this.getAllUserInfos(e).forEach((n=>{var o;if(null!==(o=n.mainStream)&&void 0!==o&&o.remoteTrackInfos?Array.from(n.mainStream.remoteTrackInfos.values()).some((e=>e.type===mO.TRACK_TYPE_AUDIO&&e.isSubscribed)):null){i.push(n.userInfo.userId);const o=this.unsubscribeSingleStream(n.userInfo.userId,e,gO.STREAM_TYPE_MAIN,t,_O.TOPN_AUDIOPOLICY);r.push(o)}})),r.push(...this.getOtherRemoteUserPublishInfos(i,e)),this.logger.info(SD,"unsubscribeAllMainStreamAudio success, ".concat(this.getTracksUpdateInfosString(r))),r}updateAudioTrackSubInfo(e,t,r,i,n,o,s,a){if(!i)return;const c=vD.getRemoteTrackInfos(i.mainStream),u=vD.getRemoteTrackInfos(i.auxStream),d=e===gO.STREAM_TYPE_MAIN?c:u,l=null==d?void 0:d.find((e=>e.type===mO.TRACK_TYPE_AUDIO));if(!l)return void this.logger.info(SD,"updateAudioTrackSubInfo: ".concat(e,", no audio track exist"));const h=l.isSubscribed?l:null;if(t.audio&&!l.isSubscribed){n===_O.USER_SUBSCRIBE_AUDIOPOLICY?(l.isSubscribed=!0,l.cssrc=this.allocateAudioReceiveSsrc(i.userInfo.roomId),o.push(l)):this.logger.warn(SD,"updateAudioTrackSubInfo, not common audio mode, but audio option is true, reserve it");const e=this.previousAudioSubscribedUsers.get(i.userInfo.roomId);null==e||e.set(i.userInfo.userId,i.userInfo.userId)}if((h||!h&&o.some((e=>e.type===mO.TRACK_TYPE_AUDIO)))&&a.push(l),r&&!t.audio&&h){l.isSubscribed=!1,s.push(l);const e=this.previousAudioSubscribedUsers.get(i.userInfo.roomId);null==e||e.delete(i.userInfo.userId)}}updateVideoTrackSubInfo(e,t,r,i,n,o,s){const a=vD.getRemoteTrackInfos(i.mainStream),c=vD.getRemoteTrackInfos(i.auxStream),u=e===gO.STREAM_TYPE_MAIN?a:c,d=null==u?void 0:u.filter((e=>e.type===mO.TRACK_TYPE_VIDEO));if(!d||0===d.length)return;const l=[];d.filter((e=>e.isSubscribed)).forEach((e=>{l.push(e)}));const h=[];if(t.video)if(t.resolutionIds)t.resolutionIds.forEach((t=>{const r=i.userInfo.userId===wC?gD[t].streamUid.toString():t,o=d.find((e=>e.trackId.toString()===r));o&&(h.push(o),l.some((e=>e.trackId.toString()===r))||(o.isSubscribed=!0,o.cssrc=this.allocateVideoReceiveSsrc(i.userInfo.roomId,e),n.push(o)))}));else{const t=this.getMaxResolutionTrack(d).trackId,r=t&&d.find((e=>e.trackId===t));r&&(h.push(r),l.some((e=>e.trackId===t))||(r.isSubscribed=!0,r.cssrc=this.allocateVideoReceiveSsrc(i.userInfo.roomId,e),n.push(r)))}const f=n.filter((e=>e.type===mO.TRACK_TYPE_VIDEO));f.forEach((e=>{e.autoAdjustResolution=t.autoAdjustResolution||DC.ON,e.minResolution=t.minResolution||"LD"})),s.push(...f),r?l.forEach((e=>{h.some((t=>t.trackId===e.trackId))?s.push(e):(e.isSubscribed=!1,o.push(e))})):s.push(...l)}unAllocateReceiveSsrc(e,t,r,i){r!==mO.TRACK_TYPE_AUDIO?this.unAllocateVideoReceiveSsrc(e,t,i):this.unAllocateAudioReceiveSsrc(e,i)}recoverReceiveSsrc(e,t,r,i){r!==mO.TRACK_TYPE_AUDIO?this.recoverVideoReceiveSsrc(e,t,i):this.recoverAudioReceiveSsrc(e,i)}unAllocateAudioReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const i=r.audioReceiveSsrcs.indexOf(t);-1===i&&this.logger.error(SD,"unAllocateAudioReceiveSsrc error, ".concat(t," not allocated")),r.audioReceiveSsrcs.splice(i,1),this.logger.info(SD,"unAllocateAudioReceiveSsrc success, ".concat(t))}recoverAudioReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);-1===r.audioReceiveSsrcs.indexOf(t)&&r.audioReceiveSsrcs.push(t),this.logger.info(SD,"recoverAudioReceiveSsrc success, ".concat(t))}unAllocateVideoReceiveSsrc(e,t,r){const i=this.roomSsrc.get(e);if(!i)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=i.videoReceiveSsrcs.indexOf(r);-1!==n?(i.videoReceiveSsrcs.splice(n,1),this.logger.info(SD,"unAllocateVideoReceiveSsrc success, ".concat(t,", ").concat(r))):this.logger.error(SD,"unAllocateVideoReceiveSsrc error, ".concat(t,", ").concat(r," not allocated"))}recoverVideoReceiveSsrc(e,t,r){const i=this.roomSsrc.get(e);if(!i)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);-1===i.videoReceiveSsrcs.indexOf(r)&&i.videoReceiveSsrcs.push(r),this.logger.info(SD,"recoverVideoReceiveSsrc success, ".concat(t,", ").concat(r))}allocateAudioReceiveSsrc(e){const t=this.roomSsrc.get(e);if(!t)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!this.audioCssrcs||0===this.audioCssrcs.length)throw this.logger.error(SD,"audio ssrc not found"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);for(const r of this.audioCssrcs)if(!t.audioReceiveSsrcs.includes(r))return t.audioReceiveSsrcs.push(r),this.logger.info(SD,"allocateAudioReceiveSsrc success, ".concat(r)),r;throw this.logger.error(SD,"have no available audio receive ssrc"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}allocateVideoReceiveSsrc(e,t){const r=this.roomSsrc.get(e);if(!r)throw this.logger.error(SD,"no roomId exist"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return t===gO.STREAM_TYPE_AUX?this.doAllocateVideoReceiveSsrc(this.auxVideoCssrcs,r.videoReceiveSsrcs):this.doAllocateVideoReceiveSsrc(this.mainVideoCssrcs,r.videoReceiveSsrcs)}doAllocateVideoReceiveSsrc(e,t){if(!e||0===e.length)throw this.logger.error(SD,"video ssrc not found"),new qc(Gc.RTC_ERR_CODE_RTC_SDK_ERROR);for(const r of e)if(!t.includes(r))return t.push(r),this.logger.info(SD,"allocateVideoReceiveSsrc success, ".concat(r)),r;throw this.logger.error(SD,"have no available video receive ssrc"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}unsubscribeStream(e,t,r,i){const n=this.unsubscribeSingleStream(e,t,r,i,_O.USER_SUBSCRIBE_AUDIOPOLICY);this.updateSubscribeOption(e,t,r,i,mD.unsubscribe);const o=[];return n&&o.push(n),o.push(...this.getOtherRemoteUserPublishInfos([e],t)),this.logger.info(SD,"unsubscribeStream success, ".concat(this.getTracksUpdateInfosString(o))),o}updateSubscribeOption(e,t,r,i,n){if(!i)throw this.logger.error(SD,"updateSubscribeOption fail, trackOption is null}"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const o=this.getUserInfoById(e,t),s=r===gO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream;n===mD.subscribe?s.subscribeOption=this.getFullSubscribeOptions(s,i):(i.audio&&(s.subscribeOption.audio=!1),i.video&&(i.resolutionIds?i.resolutionIds.forEach((e=>{var t,r;const i=null===(t=s.subscribeOption)||void 0===t||null===(r=t.resolutions)||void 0===r?void 0:r.map((e=>e.resolutionId)).indexOf(e);i>-1&&s.subscribeOption.resolutions.splice(i,1)})):(s.subscribeOption.video=!1,s.subscribeOption.resolutions=null)))}getFullSubscribeOptions(e,t){if(!t)throw this.logger.error(SD,"trackOption is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=[],i={};if(t.video)if(t.resolutionIds)t.resolutionIds.forEach((t=>{vD.appendResolutions(e,t,r)}));else{const t=this.getMaxResolutionTrackId(e);vD.appendResolutions(e,t,r)}if(t.audio){const t=Array.from(e.remoteTrackInfos.values()).find((e=>e.type===mO.TRACK_TYPE_AUDIO));null!=t&&t.playElement&&(i.playElement=t.playElement,i.objectFit=t.objectFit,i.muted=t.muted)}return{audio:t.audio,video:t.video,resolutions:r,audioPlayInfo:i,autoAdjustResolution:t.autoAdjustResolution,minResolution:t.minResolution}}static appendResolutions(e,t,r){const i=e.remoteTrackInfos.get(t);if(i){const e={resolutionId:t,width:i.width,height:i.height};i.playElement&&(e.playElement=i.playElement,e.objectFit=i.objectFit,e.muted=i.muted),r.push(e)}}getRemoteUserInfoById(e,t){if(!e||!t)return null;const r=this.getUserInfoById(e,t);return r||(this.logger.error(SD,"unsubscribeSingleStream fail, user not exist}"),null)}unsubscribeSingleStream(e,t,r,i,n){var o,s;const a=this.getRemoteUserInfoById(e,t);if(null===a)return null;const c=vD.getRemoteTrackInfos(a.mainStream),u=vD.getRemoteTrackInfos(a.auxStream),d=r===gO.STREAM_TYPE_MAIN?c:u;if(!d||0===d.length)return this.logger.warn(SD,"unsubscribeSingleStream, no track exist ".concat(e)),null;const l=d.filter((e=>e.isSubscribed)),h=[];if(i.audio){const r=d.find((e=>e.type===mO.TRACK_TYPE_AUDIO&&e.isSubscribed));if(r&&(r.isSubscribed=!1,h.push(r),n===_O.USER_SUBSCRIBE_AUDIOPOLICY)){const r=this.previousAudioSubscribedUsers.get(t);null==r||r.delete(e)}}i.video&&this.unsubscribeVideo(i,l,h,e,d);const f={remoteStream:r===gO.STREAM_TYPE_MAIN?null===(o=a.mainStream)||void 0===o?void 0:o.remoteStream:null===(s=a.auxStream)||void 0===s?void 0:s.remoteStream,preTracks:d,curTracks:d,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:l,tracks4Subscribe:null,tracks4Unsubscribe:h,allSubscribeTracks:Array.from(d.values()).filter((e=>e.isSubscribed))},p=vD.getAnotherStreamUpdateInfo(r,a);return{preUserState:a.userState,curUserState:a.userState,userInfo:a.userInfo,mainStream:r===gO.STREAM_TYPE_MAIN?f:p,auxStream:r===gO.STREAM_TYPE_AUX?f:p}}unsubscribeVideo(e,t,r,i,n){if(e.resolutionIds)e.resolutionIds.forEach((e=>{const t=i===wC?gD[e].streamUid.toString():e,o=null==n?void 0:n.find((e=>e.trackId.toString()===t&&e.isSubscribed));o&&(o.isSubscribed=!1,r.push(o))}));else{const e=null==t?void 0:t.filter((e=>e.type==mO.TRACK_TYPE_VIDEO));null==e||e.forEach((e=>{e.isSubscribed=!1,r.push(e)}))}}updateUserName(e,t,r){const i=this.getUserInfoById(e,t);i?(i.userInfo.nickname=r,this.logger.info(SD,"updateUserName success, userId: ".concat(e,", nickName: ").concat(r))):this.logger.error(SD,"updateUserName fail, user not exist}")}isRemoteUserSubscribed(e,t){var r,i;const n=this.getUserInfoById(e,t);if(!n)return this.logger.info(SD,"isRemoteUserSubscribed, user not exist}"),!1;const o=!(null===(r=n.mainStream)||void 0===r||!r.remoteTrackInfos)&&Array.from(n.mainStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)).length>0,s=!(null===(i=n.auxStream)||void 0===i||!i.remoteTrackInfos)&&Array.from(n.auxStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)).length>0;return o||s}getUserInfoByStreamId(e,t){return this.getAllUserInfos(e).find((e=>{var r,i;return(null===(r=e.mainStream)||void 0===r?void 0:r.remoteTrackInfos.has(t))||(null===(i=e.auxStream)||void 0===i?void 0:i.remoteTrackInfos.has(t))}))}getAllUserInfos(e){return Array.from(this.remoteUserInfos.values()).filter((t=>t.userInfo.roomId===e))}getAllSubscribedUpdateInfos4Unsubscribe(e){return this.getAllUserInfos(e).map((e=>{const t=vD.getRemoteTrackInfos(e.mainStream).filter((e=>e.isSubscribed));t.forEach((e=>{e.isSubscribed=!1}));const r=vD.getRemoteTrackInfos(e.auxStream).filter((e=>e.isSubscribed));return r.forEach((e=>{e.isSubscribed=!1})),{userInfo:e.userInfo,preUserState:e.userState,curUserState:e.userState,mainStream:{remoteStream:e.mainStream.remoteStream,tracks4Unsubscribe:t,allSubscribeTracks:[]},auxStream:{remoteStream:e.auxStream.remoteStream,tracks4Unsubscribe:r,allSubscribeTracks:[]}}}))}initializeRemoteUser(e,t){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r={userInfo:e,userState:t?IO.Joined:IO.NotJoin,mainStream:null,auxStream:null},i=vD.generateUniqueId(e.userId,e.roomId);return this.remoteUserInfos.set(i,r),this.roomSsrc.has(e.roomId)||this.roomSsrc.set(e.roomId,{audioReceiveSsrcs:[],videoReceiveSsrcs:[]}),this.logger.info(SD,"initializeRemoteUser success, userInfo: ".concat(JSON.stringify(e))),r}updateRemoteUser(e){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const t=this.getUserInfoById(e.userId,e.roomId);return t?(e.nickname=e.nickname||t.userInfo.nickname,t.userInfo=e,this.logger.info(SD,"updateRemoteUser success, userInfo: ".concat(JSON.stringify(e))),t):null}initializeRemoteStream(e,t,r){const i=e===gO.STREAM_TYPE_MAIN?"main":"auxiliary",n=new rM({type:i,log:this.logger,userId:t,client:this.client,roomId:r}),o={remoteTrackInfos:new Map,remoteStream:n,subscribeOption:{audio:!1,video:!1}};if(!this.previousAudioSubscribedUsers.has(r)){const e=new Map;this.previousAudioSubscribedUsers.set(r,e)}return this.logger.info(SD,"initializeStreamInfo success, userId: ".concat(t,", type: ").concat(o.remoteStream.getType())),o}refreshRemoteStreamList(e,t,r){const i=null==t?void 0:t.filter((e=>e.content!==CC.desktop)),n=null==t?void 0:t.filter((e=>e.content===CC.desktop)),o=this.getUserInfoById(e.userId,e.roomId),s=this.doRefreshRemoteStreamList(e,gO.STREAM_TYPE_MAIN,i,r,!1),a=this.doRefreshRemoteStreamList(e,gO.STREAM_TYPE_AUX,n,null,!1),c=this.getUserInfoById(e.userId,e.roomId);return this.getAllPublishInfosWhenStreamUpdate(!o,s,a,c)}doRefreshRemoteStreamList(e,t,r,i,n){if(this.logger.info(SD,"doRefreshRemoteStreamList begin, streamType:".concat(t,",isLocalRejoin:").concat(n,",")+"userInfo: ".concat(JSON.stringify(e),", allVideoStreams: ").concat(JSON.stringify(r),", allAudioStreams: ").concat(JSON.stringify(i))),e.userId===this.localUserId)return null;const o=this.getUserInfoById(e.userId,e.roomId);e.relaySrcRoomId=e.relaySrcRoomId||(null==o?void 0:o.userInfo.relaySrcRoomId);const s=o?this.updateRemoteUser(e):this.initializeRemoteUser(e,!0),a=this.getStreamInfoByStreamType(t,s,e),c=vD.getRemoteTrackInfos(a),u=null==c?void 0:c.filter((e=>e.isSubscribed)),d=a.remoteTrackInfos,l=[],h=[],f=[];null==c||c.forEach((e=>{this.isPreTrackInvalid(r,i,e,n)&&(n&&e.isSubscribed&&(e.state=TO.localRejoin),f.push(e),d.delete(e.trackId))})),this.refreshTracks(r,i,c,d,n,l,h,f),this.cachePlayInfo(e,t,r,i,f);const p=this.getTracks4Subscribe(e,t,a.remoteStream,l,f),m=this.getTracks4UnSubscribe(f),g=Array.from(a.remoteTrackInfos.values());return this.updateRemoteStreamTracks(g,a.remoteStream),{remoteStream:a.remoteStream,preTracks:c,curTracks:g,addedTracks:l,updatedTracks:h,removedTracks:f,subscribedTracks:u,tracks4Subscribe:p,tracks4Unsubscribe:m,allSubscribeTracks:null==g?void 0:g.filter((e=>e.isSubscribed))}}refreshTracks(e,t,r,i,n,o,s,a){(null!=e&&e.length||null!=t&&t.length)&&(null==r||r.forEach((e=>{e.state===TO.remoteRejoinCache&&(a.push(e),i.delete(e.trackId))}))),this.refreshVideoStreamTracks(e,r,i,n,o,s),this.refreshAudioStreamTracks(t,r,i,n,o,s)}refreshVideoStreamTracks(e,t,r,i,n,o){null==e||e.forEach((e=>{const s=null==t?void 0:t.find((t=>t.trackId===e.streamUid.toString()));if(s){const t=vD.generateUpdateVideoTrack(e,s);r.set(e.streamUid.toString(),t),s.state===TO.remoteRejoinCache||i?(t.isSubscribed=!1,t.isTrackReady=!1,n.push(t)):vD.isSameResolution(s,e)&&!vD.isMuteStatusChange(s,e)||o.push(s)}else{const t=vD.generateNewVideoTrack(e);r.set(e.streamUid.toString(),t),n.push(t)}}))}refreshAudioStreamTracks(e,t,r,i,n,o){null==e||e.forEach((e=>{if("main"===(null==e?void 0:e.content)){const s=null==t?void 0:t.find((t=>t.trackId===e.streamUid.toString()));if(s){const t=vD.generateUpdateAudioTrack(e,s);r.set(e.streamUid.toString(),t),s.state===TO.remoteRejoinCache||i?(t.isSubscribed=!1,t.isTrackReady=!1,n.push(t)):vD.isMuteStatusChange(s,e)&&o.push(s)}else{const t=vD.generateNewAudioTrack(e);r.set(e.streamUid.toString(),t),n.push(t)}}}))}remoteUserReconnect(e){if(!e)return;const t=this.getUserInfoById(e.userId,e.roomId);if(!t)return this.logger.error(SD,"remoteUserReconnect, user not exist"),null;this.isRemoteUserSubscribed(e.userId,e.roomId)&&this.cacheHistorySubscription(t),t.userState=IO.Rejoining,this.logger.info(SD,"remoteUserReconnect, update user state to rejoining")}cacheHistorySubscription(e){if(!e)return null;const t=this.getSubscribedTracksInfo(e.userInfo.userId,e.userInfo.roomId,gO.STREAM_TYPE_MAIN),r=this.getSubscribedTracksInfo(e.userInfo.userId,e.userInfo.roomId,gO.STREAM_TYPE_AUX);null==t||t.forEach((e=>{e.state=TO.remoteRejoinCache})),null==r||r.forEach((e=>{e.state=TO.remoteRejoinCache}))}getSubscribedTracksInfo(e,t,r){var i,n;const o=this.getUserInfoById(e,t);if(!o)return this.logger.error(SD,"getSubscribedMainTracksInfo, user not exist}"),null;const s=r===gO.STREAM_TYPE_MAIN?null===(i=o.mainStream)||void 0===i?void 0:i.remoteTrackInfos:null===(n=o.auxStream)||void 0===n?void 0:n.remoteTrackInfos;return s&&Array.from(s.values()).filter((e=>e.isSubscribed))}getStreamInfoByStreamType(e,t,r){if(!(e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream)){const i=this.initializeRemoteStream(e,r.userId,r.roomId);e===gO.STREAM_TYPE_MAIN?t.mainStream=i:t.auxStream=i}return e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream}static generateNewVideoTrack(e){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:!1,isTrackReady:!1,pssrc:e.ssrc,cssrc:0,type:mO.TRACK_TYPE_VIDEO,width:e.width,height:e.height,state:TO.normal,mute:e.mute,maxFs:e.maxFs,fps:e.fps}}static generateNewAudioTrack(e){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:!1,isTrackReady:!1,pssrc:e.ssrc,cssrc:0,type:mO.TRACK_TYPE_AUDIO,state:TO.normal,mute:e.mute}}static generateUpdateVideoTrack(e,t){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:t.isSubscribed,isTrackReady:t.isTrackReady,pssrc:t.pssrc,cssrc:t.cssrc,type:mO.TRACK_TYPE_VIDEO,width:e.width,height:e.height,state:t.state,mute:e.mute}}static generateUpdateAudioTrack(e,t){return{pt:e.pt,content:e.content,streamType:e.content===CC.desktop?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,trackId:e.streamUid.toString(),isSubscribed:t.isSubscribed,isTrackReady:t.isTrackReady,pssrc:t.pssrc,cssrc:t.cssrc,type:mO.TRACK_TYPE_AUDIO,state:t.state,mute:e.mute}}updateRemoteStream(e,t,r){const i=null==t?void 0:t.filter((e=>e.content!==CC.desktop)),n=null==t?void 0:t.filter((e=>e.content===CC.desktop)),o=this.doUpdateRemoteStream(e,gO.STREAM_TYPE_MAIN,i,r),s=this.doUpdateRemoteStream(e,gO.STREAM_TYPE_AUX,n,null),a=this.getUserInfoById(e.userId,e.roomId);return{userInfo:a.userInfo,preUserState:a.userState,curUserState:a.userState,isUserNameChanged:null,mainStream:o,auxStream:s}}doUpdateRemoteStream(e,t,r,i){this.logger.info(SD,"updateRemoteStreamInfo begin, streamType:".concat(t)+"userInfo: ".concat(JSON.stringify(e),", videoStreams: ").concat(JSON.stringify(r),", audioStreams: ").concat(JSON.stringify(i),","));if(!this.getUserInfoById(e.userId,e.roomId))return this.logger.error(SD,"updateRemoteStream, user not exist"),null;const n=this.getUserInfoById(e.userId,e.roomId),o=this.getStreamInfoByStreamType(t,n,e),s=vD.getRemoteTrackInfos(o),a=null==s?void 0:s.filter((e=>e.isSubscribed)),c=o.remoteTrackInfos,u=[];null==r||r.forEach((e=>{const t=null==s?void 0:s.find((t=>t.trackId===e.streamUid.toString()));if(t&&(!vD.isSameResolution(t,e)||vD.isMuteStatusChange(t,e))){const r=vD.generateUpdateVideoTrack(e,t);c.set(e.streamUid.toString(),r),u.push(t)}})),null==i||i.forEach((e=>{const t=null==s?void 0:s.find((t=>t.trackId===e.streamUid.toString()));if(t&&vD.isMuteStatusChange(t,e)){const r=vD.generateUpdateAudioTrack(e,t);c.set(e.streamUid.toString(),r),u.push(t)}}));const d=Array.from(o.remoteTrackInfos.values());return this.updateRemoteStreamTracks(d,o.remoteStream),{remoteStream:o.remoteStream,preTracks:s,curTracks:d,addedTracks:[],updatedTracks:u,removedTracks:[],subscribedTracks:a,tracks4Subscribe:[],tracks4Unsubscribe:[],allSubscribeTracks:null==d?void 0:d.filter((e=>e.isSubscribed))}}getAllPublishInfosWhenStreamUpdate(e,t,r,i){const n={userInfo:i.userInfo,preUserState:e?IO.NotJoin:i.userState,curUserState:i.userState,isUserNameChanged:null,mainStream:t,auxStream:r},o=[];return o.push(n),o.push(...this.getOtherRemoteUserPublishInfos([i.userInfo.userId],i.userInfo.roomId)),this.logger.info(SD,"updateRemoteStreamInfo success, ".concat(this.getTracksUpdateInfosString(o))),o}getOtherRemoteUserPublishInfos(e,t){const r=[];return this.getAllUserInfos(t).forEach((t=>{if(!e.includes(t.userInfo.userId)){var i,n,o,s,a,c;const e=null!==(i=t.mainStream)&&void 0!==i&&null!==(n=i.remoteTrackInfos)&&void 0!==n&&n.size?Array.from(t.mainStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)):null,u=null!==(o=t.auxStream)&&void 0!==o&&null!==(s=o.remoteTrackInfos)&&void 0!==s&&s.size?Array.from(t.auxStream.remoteTrackInfos.values()).filter((e=>e.isSubscribed)):null,d={userInfo:t.userInfo,curUserState:t.userState,preUserState:t.userState,mainStream:{remoteStream:null===(a=t.mainStream)||void 0===a?void 0:a.remoteStream,allSubscribeTracks:e},auxStream:{remoteStream:null===(c=t.auxStream)||void 0===c?void 0:c.remoteStream,allSubscribeTracks:u}};r.push(d)}})),r}static getAnotherStreamUpdateInfo(e,t){const r=e===gO.STREAM_TYPE_MAIN?t.auxStream:t.mainStream,i=vD.getRemoteTrackInfos(r),n=i?i.filter((e=>e.isSubscribed)):null;return{remoteStream:null==r?void 0:r.remoteStream,preTracks:i,curTracks:i,addedTracks:null,updatedTracks:null,removedTracks:null,subscribedTracks:n?[...n]:null,tracks4Subscribe:null,tracks4Unsubscribe:null,allSubscribeTracks:n?[...n]:null}}getTracksUpdateInfosString(e){if(!e)return"";let t="";return e.forEach((e=>{t=t+vD.getTracksUpdateInfoString(e)+" "})),t}static getTracksUpdateInfoString(e){var t,r,i,n,o,s,a,c,u,d,l,h,f,p,m,g,_,S,v,y,I,T,R,E,b,C,A,w,k,O,P,M,D,N,U,x,L,B,V,Y,j,F,H,K,z,W,G,J,q,X,Q,$,Z,ee;return e?"userId:".concat(e.userInfo.userId,", preUserState: ").concat(e.preUserState,",curUserState: ").concat(e.curUserState,",")+"main stream:"+"".concat(null!==(t=e.mainStream)&&void 0!==t&&null!==(r=t.preTracks)&&void 0!==r&&r.length?"preTracks:"+JSON.stringify(null===(i=e.mainStream)||void 0===i?void 0:i.preTracks)+",":"")+"".concat(null!==(n=e.mainStream)&&void 0!==n&&null!==(o=n.curTracks)&&void 0!==o&&o.length?"curTracks:"+JSON.stringify(null===(s=e.mainStream)||void 0===s?void 0:s.curTracks)+",":"")+"".concat(null!==(a=e.mainStream)&&void 0!==a&&null!==(c=a.addedTracks)&&void 0!==c&&c.length?"addedTracks:"+JSON.stringify(null===(u=e.mainStream)||void 0===u?void 0:u.addedTracks)+",":"")+"".concat(null!==(d=e.mainStream)&&void 0!==d&&null!==(l=d.updatedTracks)&&void 0!==l&&l.length?"updatedTracks:"+JSON.stringify(null===(h=e.mainStream)||void 0===h?void 0:h.updatedTracks)+",":"")+"".concat(null!==(f=e.mainStream)&&void 0!==f&&null!==(p=f.removedTracks)&&void 0!==p&&p.length?"removedTracks:"+JSON.stringify(null===(m=e.mainStream)||void 0===m?void 0:m.removedTracks)+",":"")+"".concat(null!==(g=e.mainStream)&&void 0!==g&&null!==(_=g.subscribedTracks)&&void 0!==_&&_.length?"subscribedTracks:"+JSON.stringify(null===(S=e.mainStream)||void 0===S?void 0:S.subscribedTracks)+",":"")+"".concat(null!==(v=e.mainStream)&&void 0!==v&&null!==(y=v.tracks4Subscribe)&&void 0!==y&&y.length?"tracks4Subscribe:"+JSON.stringify(null===(I=e.mainStream)||void 0===I?void 0:I.tracks4Subscribe)+",":"")+"".concat(null!==(T=e.mainStream)&&void 0!==T&&null!==(R=T.tracks4Unsubscribe)&&void 0!==R&&R.length?"tracks4Unsubscribe:"+JSON.stringify(null===(E=e.mainStream)||void 0===E?void 0:E.tracks4Unsubscribe)+",":"")+"".concat(null!==(b=e.mainStream)&&void 0!==b&&null!==(C=b.allSubscribeTracks)&&void 0!==C&&C.length?"allSubscribeTracks:"+JSON.stringify(null===(A=e.mainStream)||void 0===A?void 0:A.allSubscribeTracks)+",":"")+"aux stream:"+"".concat(null!==(w=e.auxStream)&&void 0!==w&&null!==(k=w.preTracks)&&void 0!==k&&k.length?"preTracks:"+JSON.stringify(null===(O=e.auxStream)||void 0===O?void 0:O.preTracks)+",":"")+"".concat(null!==(P=e.auxStream)&&void 0!==P&&null!==(M=P.curTracks)&&void 0!==M&&M.length?"curTracks:"+JSON.stringify(null===(D=e.auxStream)||void 0===D?void 0:D.curTracks)+",":"")+"".concat(null!==(N=e.auxStream)&&void 0!==N&&null!==(U=N.addedTracks)&&void 0!==U&&U.length?"addedTracks:"+JSON.stringify(null===(x=e.auxStream)||void 0===x?void 0:x.addedTracks)+",":"")+"".concat(null!==(L=e.auxStream)&&void 0!==L&&null!==(B=L.updatedTracks)&&void 0!==B&&B.length?"updatedTracks:"+JSON.stringify(null===(V=e.auxStream)||void 0===V?void 0:V.updatedTracks)+",":"")+"".concat(null!==(Y=e.auxStream)&&void 0!==Y&&null!==(j=Y.removedTracks)&&void 0!==j&&j.length?"removedTracks:"+JSON.stringify(null===(F=e.auxStream)||void 0===F?void 0:F.removedTracks)+",":"")+"".concat(null!==(H=e.auxStream)&&void 0!==H&&null!==(K=H.subscribedTracks)&&void 0!==K&&K.length?"subscribedTracks:"+JSON.stringify(null===(z=e.auxStream)||void 0===z?void 0:z.subscribedTracks)+",":"")+"".concat(null!==(W=e.auxStream)&&void 0!==W&&null!==(G=W.tracks4Subscribe)&&void 0!==G&&G.length?"tracks4Subscribe:"+JSON.stringify(null===(J=e.auxStream)||void 0===J?void 0:J.tracks4Subscribe)+",":"")+"".concat(null!==(q=e.auxStream)&&void 0!==q&&null!==(X=q.tracks4Unsubscribe)&&void 0!==X&&X.length?"tracks4Unsubscribe:"+JSON.stringify(null===(Q=e.auxStream)||void 0===Q?void 0:Q.tracks4Unsubscribe)+",":"")+"".concat(null!==($=e.auxStream)&&void 0!==$&&null!==(Z=$.allSubscribeTracks)&&void 0!==Z&&Z.length?"allSubscribeTracks:"+JSON.stringify(null===(ee=e.auxStream)||void 0===ee?void 0:ee.allSubscribeTracks):""):""}updateRemoteStreamTracks(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!e)return void this.logger.error(SD,"updateRemoteStreamTracks , curAllTracks is null");const r=new Map;e.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).forEach((e=>{r.set(e.trackId.toString(),{streamId:e.trackId.toString(),width:e.width,height:e.height})}));const i=e.some((e=>e.type===mO.TRACK_TYPE_AUDIO)),n=t.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN;t.updateRemoteResolutions(n,[...r.values()],i)}isPreTrackInvalid(e,t,r,i){return!!i||r.state!==TO.remoteRejoinCache&&(r.type===mO.TRACK_TYPE_VIDEO&&this.isPreVideoTrackRemoved(e,r)||r.type===mO.TRACK_TYPE_AUDIO&&this.isPreAudioTrackRemoved(t,r))}isPreVideoTrackRemoved(e,t){return!(null!=e&&e.some((e=>e.streamUid.toString()===t.trackId)))}isPreAudioTrackRemoved(e,t){return!(null!=e&&e.some((e=>e.streamUid.toString()===t.trackId)))}static isSameResolution(e,t){if(!e||!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e.height===t.height&&e.width===t.width}static isMuteStatusChange(e,t){if(!e||!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e.mute!==t.mute}clear(e){if(e){for(const o of this.remoteUserInfos.keys())if(o.indexOf("#".concat(e))>0){var t,r,i,n;const e=this.remoteUserInfos.get(o);null===(t=e.mainStream)||void 0===t||null===(r=t.remoteStream)||void 0===r||r.close(),null===(i=e.auxStream)||void 0===i||null===(n=i.remoteStream)||void 0===n||n.close(),this.remoteUserInfos.delete(o)}this.roomSsrc.delete(e),this.previousAudioSubscribedUsers.delete(e)}}static generateUniqueId(e,t){if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return"".concat(e,"#").concat(t)}}function yD(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const ID=[200,201,204];const TD=new class{setLogServerConfigs(e){this.logServerConfigs=function(e){for(var t=1;tvA)throw this.logger.error(RD,"relayClients size over maxium: ".concat(vA)),new qc(Gc.RTC_ERR_CODE_CLIENT_RELAY_ROOM_OVER_MAXNUM);if(this.find(e.clientSymbol,t))throw this.logger.error(RD,"addRelayConnection:".concat(t," already exist")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"addRelayConnection:".concat(t," already exist"));return new AN(e.clientConfig,e.clientSymbol)}getRelayConnection(e,t){return this.find(e.clientSymbol,t)}stopRelayConnection(e,t){e.mainRelayRoomSymbol?(this.find(e.mainRelayRoomSymbol,t)||this.logger.error(RD,"stopRelayClient:".concat(t," not exist")),this.remove(e.mainRelayRoomSymbol,t)):t?this.remove(e.clientSymbol,t):this.remove(e.clientSymbol)}roleValidCheck4RelayRoom(e,t){if(t===sM.JOINER){let t=!1;for(const r of this.relayClients.get(e.mainRelayRoomSymbol||e.clientSymbol).values())if(r.userInfo.role===sM.JOINER){t=!0;break}if(t)throw this.logger.error(RD,"only one joiner can include in relayRooms."),new qc(Gc.RTC_ERR_CODE_CLIENT_RELAY_JOINER_OVER_MAXNUM)}}switchRoleParamsCheck(e,t,r){if(t!==sM.JOINER&&t!==sM.PLAYER||null==r||!r.signature||null==r||!r.ctime)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.roleValidCheck4RelayRoom(e,t)}};var bD=Sn,CD="ArrayBuffer",AD=HS[CD];en({global:!0,constructor:!0,forced:c[CD]!==AD},{ArrayBuffer:AD}),bD(CD);var wD={exports:{}};!function(e,t){e.exports=function(){var e=Math.imul,t=Math.clz32;function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var r,i=0;ie.length)&&(t=e.length);for(var r=0,i=Array(t);r=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==r.return||r.return()}finally{if(a)throw o}}}}var R=function(e){var t=Math.abs,n=Math.max,a=Math.floor;function c(e,t){var r;if(i(this,c),(r=u.call(this,e)).sign=t,Object.setPrototypeOf(f(r),c.prototype),e>c.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return r}s(c,e);var u=m(c);return o(c,[{key:"toDebugString",value:function(){var e,t=["BigInt["],r=T(this);try{for(r.s();!(e=r.n()).done;){var i=e.value;t.push((i?(i>>>0).toString(16):i)+", ")}}catch(e){r.e(e)}finally{r.f()}return t.push("]"),t.join("")}},{key:"toString",value:function(){var e=0e||36this.length&&(r=this.length);for(var i=32767&e,n=e>>>15,o=0,s=t,a=0;a>>15,h=c.__imul(d,i),f=c.__imul(d,n),p=c.__imul(l,i),m=s+h+o;o=m>>>30,m&=1073741823,o+=(m+=((32767&f)<<15)+((32767&p)<<15))>>>30,s=c.__imul(l,n)+(f>>>15)+(p>>>15),this.__setDigit(a,1073741823&m)}if(0!==o||0!==s)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(e,t,r){for(var i,n=0,o=0;o>>15,this.__setHalfDigit(t+o,32767&i);return n}},{key:"__inplaceSub",value:function(e,t,r){var i=0;if(1&t){t>>=1;for(var n=this.__digit(t),o=32767&n,s=0;s>>1;s++){var a=e.__digit(s),c=(n>>>15)-(32767&a)-i;i=1&c>>>15,this.__setDigit(t+s,(32767&c)<<15|32767&o),i=1&(o=(32767&(n=this.__digit(t+s+1)))-(a>>>15)-i)>>>15}var u=e.__digit(s),d=(n>>>15)-(32767&u)-i;if(i=1&d>>>15,this.__setDigit(t+s,(32767&d)<<15|32767&o),t+s+1>=this.length)throw new RangeError("out of bounds");0==(1&r)&&(i=1&(o=(32767&(n=this.__digit(t+s+1)))-(u>>>15)-i)>>>15,this.__setDigit(t+e.length,1073709056&n|32767&o))}else{t>>=1;for(var l=0;l>>15)-(f>>>15)-(i=1&p>>>15);i=1&m>>>15,this.__setDigit(t+l,(32767&m)<<15|32767&p)}var g=this.__digit(t+l),_=e.__digit(l),S=(32767&g)-(32767&_)-i;i=1&S>>>15;var v=0;0==(1&r)&&(i=1&(v=(g>>>15)-(_>>>15)-i)>>>15),this.__setDigit(t+l,(32767&v)<<15|32767&S)}return i}},{key:"__inplaceRightShift",value:function(e){if(0!==e){for(var t,r=this.__digit(0)>>>e,i=this.length-1,n=0;n>>e;this.__setDigit(i,r)}}},{key:"__digit",value:function(e){return this[e]}},{key:"__unsignedDigit",value:function(e){return this[e]>>>0}},{key:"__setDigit",value:function(e,t){this[e]=0|t}},{key:"__setDigitGrow",value:function(e,t){this[e]=0|t}},{key:"__halfDigitLength",value:function(){var e=this.length;return 32767>=this.__unsignedDigit(e-1)?2*e-1:2*e}},{key:"__halfDigit",value:function(e){return 32767&this[e>>>1]>>>15*(1&e)}},{key:"__setHalfDigit",value:function(e,t){var r=e>>>1,i=this.__digit(r),n=1&e?32767&i|t<<15:1073709056&i|32767&t;this.__setDigit(r,n)}}],[{key:"BigInt",value:function(e){var t=Number.isFinite;if("number"==typeof e){if(0===e)return c.__zero();if(c.__isOneDigitInt(e))return 0>e?c.__oneDigit(-e,!0):c.__oneDigit(e,!1);if(!t(e)||a(e)!==e)throw new RangeError("The number "+e+" cannot be converted to BigInt because it is not an integer");return c.__fromDouble(e)}if("string"==typeof e){var i=c.__fromString(e);if(null===i)throw new SyntaxError("Cannot convert "+e+" to a BigInt");return i}if("boolean"==typeof e)return!0===e?c.__oneDigit(1,!1):c.__zero();if("object"===r(e)){if(e.constructor===c)return e;var n=c.__toPrimitive(e);return c.BigInt(n)}throw new TypeError("Cannot convert "+e+" to a BigInt")}},{key:"toNumber",value:function(e){var t=e.length;if(0===t)return 0;if(1===t){var r=e.__unsignedDigit(0);return e.sign?-r:r}var i=e.__digit(t-1),n=c.__clz30(i),o=30*t-n;if(1024>>=12;var h=d-12,f=12<=d?0:a<<20+d,p=20+d;for(0>>30-h,f=a<>>30-p,p-=30;var m=c.__decideRounding(e,p,u,a);if((1===m||0===m&&1==(1&f))&&0==(f=f+1>>>0)&&0!=++l>>>20&&(l=0,1023<++s))return e.sign?-1/0:1/0;var g=e.sign?-2147483648:0;return s=s+1023<<20,c.__kBitConversionInts[1]=g|s|l,c.__kBitConversionInts[0]=f,c.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(e){if(0===e.length)return e;var t=e.__copy();return t.sign=!e.sign,t}},{key:"bitwiseNot",value:function(e){return e.sign?c.__absoluteSubOne(e).__trim():c.__absoluteAddOne(e,!0)}},{key:"exponentiate",value:function(e,t){if(t.sign)throw new RangeError("Exponent must be positive");if(0===t.length)return c.__oneDigit(1,!1);if(0===e.length)return e;if(1===e.length&&1===e.__digit(0))return e.sign&&0==(1&t.__digit(0))?c.unaryMinus(e):e;if(1=c.__kMaxLengthBits)throw new RangeError("BigInt too big");if(1===e.length&&2===e.__digit(0)){var i=1+(0|r/30),n=new c(i,e.sign&&0!=(1&r));n.__initializeDigits();var o=1<>=1;0!==r;r>>=1)a=c.multiply(a,a),0!=(1&r)&&(s=null===s?a:c.multiply(s,a));return s}},{key:"multiply",value:function(e,t){if(0===e.length)return e;if(0===t.length)return t;var r=e.length+t.length;30<=e.__clzmsd()+t.__clzmsd()&&r--;var i=new c(r,e.sign!==t.sign);i.__initializeDigits();for(var n=0;nc.__absoluteCompare(e,t))return c.__zero();var r,i=e.sign!==t.sign,n=t.__unsignedDigit(0);if(1===t.length&&32767>=n){if(1===n)return i===e.sign?e:c.unaryMinus(e);r=c.__absoluteDivSmall(e,n,null)}else r=c.__absoluteDivLarge(e,t,!0,!1);return r.sign=i,r.__trim()}},{key:"remainder",value:function(e,t){if(0===t.length)throw new RangeError("Division by zero");if(0>c.__absoluteCompare(e,t))return e;var r=t.__unsignedDigit(0);if(1===t.length&&32767>=r){if(1===r)return c.__zero();var i=c.__absoluteModSmall(e,r);return 0===i?c.__zero():c.__oneDigit(i,e.sign)}var n=c.__absoluteDivLarge(e,t,!1,!0);return n.sign=e.sign,n.__trim()}},{key:"add",value:function(e,t){var r=e.sign;return r===t.sign?c.__absoluteAdd(e,t,r):0<=c.__absoluteCompare(e,t)?c.__absoluteSub(e,t,r):c.__absoluteSub(t,e,!r)}},{key:"subtract",value:function(e,t){var r=e.sign;return r===t.sign?0<=c.__absoluteCompare(e,t)?c.__absoluteSub(e,t,r):c.__absoluteSub(t,e,!r):c.__absoluteAdd(e,t,r)}},{key:"leftShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?c.__rightShiftByAbsolute(e,t):c.__leftShiftByAbsolute(e,t)}},{key:"signedRightShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?c.__leftShiftByAbsolute(e,t):c.__rightShiftByAbsolute(e,t)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(e,t){return 0>c.__compareToBigInt(e,t)}},{key:"lessThanOrEqual",value:function(e,t){return 0>=c.__compareToBigInt(e,t)}},{key:"greaterThan",value:function(e,t){return 0(e=a(e)))throw new RangeError("Invalid value: not (convertible to) a safe integer");if(0===e)return c.__zero();if(e>=c.__kMaxLengthBits)return t;var r=0|(e+29)/30;if(t.length(e=a(e)))throw new RangeError("Invalid value: not (convertible to) a safe integer");if(0===e)return c.__zero();if(t.sign){if(e>c.__kMaxLengthBits)throw new RangeError("BigInt too big");return c.__truncateAndSubFromPowerOfTwo(e,t,!1)}if(e>=c.__kMaxLengthBits)return t;var r=0|(e+29)/30;if(t.length>>i)return t}return c.__truncateToNBits(e,t)}},{key:"ADD",value:function(e,t){if(e=c.__toPrimitive(e),t=c.__toPrimitive(t),"string"==typeof e)return"string"!=typeof t&&(t=t.toString()),e+t;if("string"==typeof t)return e.toString()+t;if(e=c.__toNumeric(e),t=c.__toNumeric(t),c.__isBigInt(e)&&c.__isBigInt(t))return c.add(e,t);if("number"==typeof e&&"number"==typeof t)return e+t;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(e,t){return c.__compare(e,t,0)}},{key:"LE",value:function(e,t){return c.__compare(e,t,1)}},{key:"GT",value:function(e,t){return c.__compare(e,t,2)}},{key:"GE",value:function(e,t){return c.__compare(e,t,3)}},{key:"EQ",value:function(e,t){for(;;){if(c.__isBigInt(e))return c.__isBigInt(t)?c.equal(e,t):c.EQ(t,e);if("number"==typeof e){if(c.__isBigInt(t))return c.__equalToNumber(t,e);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("string"==typeof e){if(c.__isBigInt(t))return null!==(e=c.__fromString(e))&&c.equal(e,t);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("boolean"==typeof e){if(c.__isBigInt(t))return c.__equalToNumber(t,+e);if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else if("symbol"===r(e)){if(c.__isBigInt(t))return!1;if("object"!==r(t))return e==t;t=c.__toPrimitive(t)}else{if("object"!==r(e))return e==t;if("object"===r(t)&&t.constructor!==c)return e==t;e=c.__toPrimitive(e)}}}},{key:"NE",value:function(e,t){return!c.EQ(e,t)}},{key:"DataViewGetBigInt64",value:function(e,t){var r=!!(2>>30),u.__setDigit(2,s>>>28),u.__trim()}},{key:"DataViewSetBigInt64",value:function(e,t,r){var i=!!(3>>2,2t)n=-t-1;else{if(0===r)return-1;r--,i=e.__digit(r),n=29}var o=1<>>20)-1023,i=1+(0|r/30),n=new c(i,0>e),o=1048575&c.__kBitConversionInts[1]|1048576,s=c.__kBitConversionInts[0],a=20,u=r%30,d=0;if(u>>l,o=o<<32-l|s>>>l,s<<=32-l}else if(u===a)d=32,t=o,o=s,s=0;else{var h=u-a;d=32-h,t=o<>>32-h,o=s<>>2,o=o<<30|s>>>2,s<<=30):t=0,n.__setDigit(f,t);return n.__trim()}},{key:"__isWhitespace",value:function(e){return!!(13>=e&&9<=e)||(159>=e?32==e:131071>=e?160==e||5760==e:196607>=e?10>=(e&=131071)||40==e||41==e||47==e||95==e||4096==e:65279==e)}},{key:"__fromString",value:function(e){var t=11073741824/a)return null;var d=new c(0|(29+(a*s+u>>>c.__kBitsPerCharTableShift))/30,!1),l=10>t?t:10,h=10>=c.__kBitsPerCharTableShift;var f=[],p=[],m=!1;do{for(var g,_=0,S=0;;){if(g=void 0,o-48>>>0>>0>>0>>0>>c.__kBitsPerCharTableShift)/30;d.__inplaceMultiplyAdd(R,T,b)}while(!v)}if(n!==i){if(!c.__isWhitespace(o))return null;for(n++;n>>c-(o-=30))}if(0!==n){if(i>=e.length)throw new Error("implementation bug");e.__setDigit(i++,n)}for(;i>>1)+(85&i))>>>2)+(51&i))>>>4)+(15&i),o=t-1,s=e.__digit(r-1),a=0|(30*r-c.__clz30(s)+n-1)/n;if(e.sign&&a++,268435456>>g,h=30-g;h>=n;)u[d--]=c.__kConversionChars[l&o],l>>>=n,h-=n}var _=(l|s<>>n-h;0!==l;)u[d--]=c.__kConversionChars[l&o],l>>>=n;if(e.sign&&(u[d--]="-"),-1!==d)throw new Error("implementation bug");return u.join("")}},{key:"__toStringGeneric",value:function(e,t,r){var i=e.length;if(0===i)return"";if(1===i){var n=e.__unsignedDigit(0).toString(t);return!1===r&&e.sign&&(n="-"+n),n}var o,s,a=30*i-c.__clz30(e.__digit(i-1)),u=c.__kMaxBitsPerChar[t]-1,d=a*c.__kBitsPerCharTableMultiplier,l=1+(d=0|(d+=u-1)/u)>>1,h=c.exponentiate(c.__oneDigit(t,!1),c.__oneDigit(l,!1)),f=h.__unsignedDigit(0);if(1===h.length&&32767>=f){(o=new c(e.length,!1)).__initializeDigits();for(var p,m=0,g=2*e.length-1;0<=g;g--)p=m<<15|e.__halfDigit(g),o.__setHalfDigit(g,0|p/f),m=0|p%f;s=m.toString(t)}else{var _=c.__absoluteDivLarge(e,h,!0,!0);o=_.quotient;var S=_.remainder.__trim();s=c.__toStringGeneric(S,t,!0)}o.__trim();for(var v=c.__toStringGeneric(o,t,!0);s.lengthi?c.__absoluteLess(r):0}},{key:"__compareToNumber",value:function(e,r){if(c.__isOneDigitInt(r)){var i=e.sign,n=0>r;if(i!==n)return c.__unequalSign(i);if(0===e.length){if(n)throw new Error("implementation bug");return 0===r?0:-1}if(1o?c.__absoluteGreater(i):st)return c.__unequalSign(r);if(0===t)throw new Error("implementation bug: should be handled elsewhere");if(0===e.length)return-1;c.__kBitConversionDouble[0]=t;var i=2047&c.__kBitConversionInts[1]>>>20;if(2047==i)throw new Error("implementation bug: handled elsewhere");var n=i-1023;if(0>n)return c.__absoluteGreater(r);var o=e.length,s=e.__digit(o-1),a=c.__clz30(s),u=30*o-a,d=n+1;if(ud)return c.__absoluteGreater(r);var l=1048576|1048575&c.__kBitConversionInts[1],h=c.__kBitConversionInts[0],f=20,p=29-a;if(p!==(0|(u-1)%30))throw new Error("implementation bug");var m,g=0;if(p>>_,l=l<<32-_|h>>>_,h<<=32-_}else if(p===f)g=32,m=l,l=h,h=0;else{var S=p-f;g=32-S,m=l<>>32-S,l=h<>>=0)>(m>>>=0))return c.__absoluteGreater(r);if(s>>2,l=l<<30|h>>>2,h<<=30):m=0;var y=e.__unsignedDigit(v);if(y>m)return c.__absoluteGreater(r);if(yr&&e.__unsignedDigit(0)===t(r):0===c.__compareToDouble(e,r)}},{key:"__comparisonResultToBool",value:function(e,t){return 0===t?0>e:1===t?0>=e:2===t?0t;case 3:return e>=t}if(c.__isBigInt(e)&&"string"==typeof t)return null!==(t=c.__fromString(t))&&c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if("string"==typeof e&&c.__isBigInt(t))return null!==(e=c.__fromString(e))&&c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if(e=c.__toNumeric(e),t=c.__toNumeric(t),c.__isBigInt(e)){if(c.__isBigInt(t))return c.__comparisonResultToBool(c.__compareToBigInt(e,t),r);if("number"!=typeof t)throw new Error("implementation bug");return c.__comparisonResultToBool(c.__compareToNumber(e,t),r)}if("number"!=typeof e)throw new Error("implementation bug");if(c.__isBigInt(t))return c.__comparisonResultToBool(c.__compareToNumber(t,e),2^r);if("number"!=typeof t)throw new Error("implementation bug");return 0===r?et:3===r?e>=t:void 0}},{key:"__absoluteAdd",value:function(e,t,r){if(e.length>>30,o.__setDigit(a,1073741823&n);for(;a>>30,o.__setDigit(a,1073741823&u)}return a>>30,n.__setDigit(s,1073741823&i);for(;s>>30,n.__setDigit(s,1073741823&a)}return n.__trim()}},{key:"__absoluteAddOne",value:function(e,t){var r=2>>30,r.__setDigit(s,1073741823&n);return 0!==o&&r.__setDigitGrow(i,1),r}},{key:"__absoluteSubOne",value:function(e,t){for(var r,i=e.length,n=new c(t=t||i,!1),o=1,s=0;s>>30,n.__setDigit(s,1073741823&r);if(0!==o)throw new Error("implementation bug");for(var a=i;ai?0:e.__unsignedDigit(i)>t.__unsignedDigit(i)?1:-1}},{key:"__multiplyAccumulate",value:function(e,t,r,i){if(0!==t){for(var n=32767&t,o=t>>>15,s=0,a=0,u=0;u>>15,p=c.__imul(h,n),m=c.__imul(h,o),g=c.__imul(f,n);s=(d+=a+p+s)>>>30,d&=1073741823,s+=(d+=((32767&m)<<15)+((32767&g)<<15))>>>30,a=c.__imul(f,o)+(m>>>15)+(g>>>15),r.__setDigit(i,1073741823&d)}for(;0!==s||0!==a;i++){var _=r.__digit(i);_+=s+a,a=0,s=_>>>30,r.__setDigit(i,1073741823&_)}}}},{key:"__internalMultiplyAdd",value:function(e,t,r,i,n){for(var o=r,s=0,a=0;a>>15,t),h=d+((32767&l)<<15)+s+o;o=h>>>30,s=l>>>15,n.__setDigit(a,1073741823&h)}if(n.length>i)for(n.__setDigit(i++,o+s);i>>0,s=0|o/t,a=0|(o=((i=0|o%t)<<15|e.__halfDigit(n-1))>>>0)/t;i=0|o%t,r.__setDigit(n>>>1,s<<15|a)}return r}},{key:"__absoluteModSmall",value:function(e,t){for(var r=0,i=2*e.length-1;0<=i;i--)r=0|((r<<15|e.__halfDigit(i))>>>0)%t;return r}},{key:"__absoluteDivLarge",value:function(e,t,r,i){var n=t.__halfDigitLength(),o=t.length,s=e.__halfDigitLength()-n,a=null;r&&(a=new c(s+2>>>1,!1)).__initializeDigits();var u=new c(n+2>>>1,!1);u.__initializeDigits();var d=c.__clz15(t.__halfDigit(n-1));0>>0;m=0|_/h;for(var S=0|_%h,v=t.__halfDigit(n-2),y=l.__halfDigit(p+n-2);c.__imul(m,v)>>>0>(S<<16|y)>>>0&&(m--,!(32767<(S+=h))););}c.__internalMultiplyAdd(t,m,0,o,u);var I=l.__inplaceSub(u,p,n+1);0!==I&&(I=l.__inplaceAdd(t,p,n),l.__setHalfDigit(p+n,32767&l.__halfDigit(p+n)+I),m--),r&&(1&p?f=m<<15:a.__setDigit(p>>>1,f|m))}if(i)return l.__inplaceRightShift(d),r?{quotient:a,remainder:l}:l;if(r)return a;throw new Error("unreachable")}},{key:"__clz15",value:function(e){return c.__clz30(e)-15}},{key:"__specialLeftShift",value:function(e,t,r){var i=e.length,n=new c(i+r,!1);if(0===t){for(var o=0;o>>30-t;return 0r)throw new RangeError("BigInt too big");var i=0|r/30,n=r%30,o=e.length,s=0!==n&&0!=e.__digit(o-1)>>>30-n,a=o+i+(s?1:0),u=new c(a,e.sign);if(0===n){for(var d=0;d>>30-n;if(s)u.__setDigit(o+i,l);else if(0!==l)throw new Error("implementation bug")}return u.__trim()}},{key:"__rightShiftByAbsolute",value:function(e,t){var r=e.length,i=e.sign,n=c.__toShiftAmount(t);if(0>n)return c.__rightShiftByMaximum(i);var o=0|n/30,s=n%30,a=r-o;if(0>=a)return c.__rightShiftByMaximum(i);var u=!1;if(i)if(0!=(e.__digit(o)&(1<>>s,m=r-o-1,g=0;g>>s;l.__setDigit(m,p)}return u&&(l=c.__absoluteAddOne(l,!0,l)),l.__trim()}},{key:"__rightShiftByMaximum",value:function(e){return e?c.__oneDigit(1,!0):c.__zero()}},{key:"__toShiftAmount",value:function(e){if(1c.__kMaxLengthBits?-1:t}},{key:"__toPrimitive",value:function(e){var t=1>>a}return i.__setDigit(n,s),i.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(e,t,r){for(var i,n=Math.min,o=0|(e+29)/30,s=new c(o,r),a=0,u=o-1,d=0,l=n(u,t.length);a>>30,s.__setDigit(a,1073741823&i);for(;a>>m)-d,h&=g-1}return s.__setDigit(u,h),s.__trim()}},{key:"__digitPow",value:function(e,t){for(var r=1;0>>=1,e*=e;return r}},{key:"__isOneDigitInt",value:function(e){return(1073741823&e)===e}}]),c}(h(Array));return R.__kMaxLength=33554432,R.__kMaxLengthBits=R.__kMaxLength<<5,R.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],R.__kBitsPerCharTableShift=5,R.__kBitsPerCharTableMultiplier=1<>>0)/t)},R.__imul=e||function(e,t){return 0|e*t},R}()}(wD);var kD=wD.exports;const OD="CommandMsgManager";class PD{constructor(e,t){i(this,"RTP_HEADER_V_P_X_CC",144),i(this,"RTP_HEADER_V_P_X_CC_BRODACAST",128),this.event=e,this.remoteUserManager=t,this.cmdMsgPacketSeqNum=0}receivedCmdRtpPacketDecode(e){var t,r;const i=new DataView(e),n=i.getUint16(2),o=i.getUint32(4);iE.getLogger().debug(OD,"receive ".concat(n," msg of timeStamp ").concat(o));const s=i.getUint32(8);if(s!==this.cmdReceiveSsrc)return void iE.getLogger().error(OD,"receive msg ssrc not matched, ".concat(this.cmdReceiveSsrc," - ").concat(s));let a=0;if(0==(16&i.getUint8(0)))a=12;else{a=16+4*i.getUint16(14)}const c=kD.toNumber(kD.DataViewGetBigUint64(i,a)),u=i.buffer.slice(a+16);let d=null;d=this.msgFormat===VC.STRING?MD.ArrayBufferToMsg(u):u,this.event.emit(UC.CmdMsgReceived,{msg:d,srcUserId:null===(t=this.remoteUserManager.getUserInfoByUid(c,this.roomId))||void 0===t||null===(r=t.userInfo)||void 0===r?void 0:r.userId})}genCmdRtpPacketMsg(e){const t=!e.userUid,r=new DataView(new ArrayBuffer(t?28:44));t?r.setUint8(0,this.RTP_HEADER_V_P_X_CC_BRODACAST):r.setUint8(0,this.RTP_HEADER_V_P_X_CC),r.setUint8(1,this.RTP_HEADER_M_PT),r.setUint16(2,this.cmdMsgPacketSeqNum++),r.setUint32(4,Math.floor((new Date).getTime()/1e3)),r.setUint32(8,this.cmdSendSsrc);const{userUid:i=0,msg:n}=e;let o=0;return t?o=12:(r.setUint16(12,4096),r.setUint16(14,3),r.setUint8(16,21),r.setUint8(17,8),kD.DataViewSetBigUint64(r,18,kD.BigInt(i)),r.setUint16(26,0),o=28),kD.DataViewSetBigUint64(r,o,kD.BigInt(this.selfUserUid)),kD.DataViewSetBigUint64(r,o+8,kD.BigInt(0)),MD.concatArrayBuffer(r.buffer,MD.msgBodyToArrayBuffer(n))}sendCommandMsg(e,t,r){let i=0;var n,o;t&&(i=null===(n=this.remoteUserManager.getUserInfoById(t,r))||void 0===n||null===(o=n.userInfo)||void 0===o?void 0:o.userUid);return this.transportChannel.sendMessage(this.genCmdRtpPacketMsg({msg:e,userUid:i}))}setCommandChannelParams(e,t){this.reset(),this.RTP_HEADER_M_PT=t.tranportOptions.payload,this.roomId=e,this.msgFormat=t.msgFormat,this.cmdSendSsrc=t.tranportOptions.sendSsrc,this.cmdReceiveSsrc=t.tranportOptions.receiveSsrc,this.selfUserUid=t.tranportOptions.userUid,this.extraParamsHandle(t),this.initCmdTranportChannel()}}class MD{static msgBodyToArrayBuffer(e){if("string"==typeof e){return(new TextEncoder).encode(e).buffer}return e}static ArrayBufferToMsg(e){return new TextDecoder("utf-8").decode(e)}static concatArrayBuffer(){let e=0;for(var t=arguments.length,r=new Array(t),i=0;iawait this.wsConnectOnce(e,r,i,t)),!1,t,this.getAsyncInterval(n),this.needInterrupted())}getAsyncInterval(e){return t=>"function"==typeof(null==t?void 0:t.getCode)&&t.getCode()===Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT?0:e}needInterrupted(){return e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_WEBSOCKET_INTERRUPTED}async wsConnectOnce(e,t,r,i){this.close(),this.connectionId=XR.generateRandomId(32),this.websocket=new WebSocket(e),this.websocket.binaryType="arraybuffer",iE.getLogger().info(DD,"wsConnectOnce, url:".concat(XR.shieldUrlParameters(e),", begin create websocket ").concat(this.connectionId," connection with server ")),this.websocket.onopen=this.onopen.bind(this),this.websocket.onerror=this.onerror.bind(this),this.websocket.onmessage=this.onmessage.bind(this),this.websocket.onclose=this.onclose.bind(this);try{const e=1===i?t:r;await this.getConnectionResp(e,this.connectionId)}catch(jN){throw iE.getLogger().error(DD,"wsConnectOnce, connect occur exception, error: ".concat(jN)),jN}finally{this.connectionCallbacks.delete(this.connectionId)}}async getConnectionResp(e,t){await mP.callWithTimeout(new Promise(((e,r)=>{this.connectionCallbacks.set(t,(i=>{if(i.isSuccess)iE.getLogger().info(DD,"getConnectionResp, connectId:".concat(t,", connect success")),e();else{const e=Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_ERROR,n=i.code,o="".concat(n||""," websocket connect error"),s=new qc(e,o);iE.getLogger().info(DD,"getConnectionResp, connectId:".concat(t,", connect fail, errMsg=").concat(s)),r(s)}}))})),e).catch((t=>{if(t.getCode()!==Gc.RTC_ERR_CODE_WAIT_RSP_TIMEOUT)throw t;throw iE.getLogger().error(DD,"getConnectionResp, websocket connect timeout after ".concat(e," ms")),this.websocket&&this.websocket.readyState===this.websocket.CONNECTING&&(iE.getLogger().info(DD,"getConnectionResp, websocket connect timeout, close webSocket manual"),this.close()),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_CONNECT_TIMEOUT)})).finally((()=>{this.connectionCallbacks.delete(t)}))}onopen(){iE.getLogger().info(DD,"onopen, wss connection success."),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!0}),this.event_.emit("CMD_CHANNEL_ESTABLISHED")}onmessage(e){e.data?this.event_.emit("CMD_MSG_REVEIVED",e.data):iE.getLogger().error(DD,"onerror, websocket message is null.")}onerror(e){iE.getLogger().error(DD,"onerror, websocket occur error:".concat(JSON.stringify(e))),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!1})}async onclose(e){const t=e.code,r=e.reason;iE.getLogger().warn(DD,"onclose, code:".concat(t,", reason:").concat(r)),this.connectionCallbacks.has(this.connectionId)&&this.connectionCallbacks.get(this.connectionId)({isSuccess:!1,code:t,reason:r}),iE.getLogger().error(DD,"reconnect"),this.event_.emit("CMD_CONNECTION_RECONNECT")}sendMessage(e){if(!this.websocket)return iE.getLogger().error(DD,"send cmd message failed for websocket is null."),!1;try{return this.websocket.send(e),!0}catch(jN){return iE.getLogger().error(DD,"send cmd message failed."),!1}}close(){this.websocket&&(this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onmessage=null,this.websocket.onclose=null,this.websocket.close(),this.websocket=null,this.connectionCallbacks.clear())}}class UD extends PD{constructor(e,t){super(e,t),this.reconnctInterval=[2,5,10,20],this.reconnctIdx=0}initCmdTranportChannel(){this.transportChannel||(this.transportChannel=new ND),this.transportChannel.on("CMD_MSG_REVEIVED",(e=>{this.receivedCmdRtpPacketDecode(e)})),this.transportChannel.on("CMD_CHANNEL_ESTABLISHED",(()=>{iE.getLogger().info(DD,"cmd websocket connection established."),this.event.emit(UC.CmdChannelEstablished,BC.WEBSOCKET),this.reconnctIdx=0,this.transportChannel.sendMessage(this.genCmdBindRtpPacketMsg())})),this.transportChannel.on("CMD_CONNECTION_RECONNECT",(async()=>{if(this.reconnctIdx===this.reconnctInterval.length)iE.getLogger().info(DD,"cmd websocket connection disconnect."),this.event.emit(UC.CmdChannelDisconnect,BC.WEBSOCKET);else try{this.event.emit(UC.CmdChannelReconnecting);const e=this.reconnctInterval[Math.min(this.reconnctIdx,this.reconnctInterval.length-1)];if(iE.getLogger().error(DD,"cmd websocket reconnect wait for ".concat(e,"s.")),await XR.sleep(1e3*e),!this.transportChannel)return;this.reconnctIdx++,iE.getLogger().error(DD,"cmd websocket reconnect begin."),await this.transportChannel.wsConnect(this.cmdSocketUrl,1,1e4,1e4,500)}catch(jN){iE.getLogger().error(DD,"cmd websocket reconnect failed: ".concat(jN))}}));try{this.transportChannel.wsConnect(this.cmdSocketUrl,1,1e4,1e4,500)}catch(jN){iE.getLogger().error(DD,"cmd websocket connect failed: ".concat(jN))}}extraParamsHandle(e){this.bindCryptoKey=e.wsOptions.bindCryptoKey,this.cmdSocketUrl=e.wsOptions.wsDomain?e.wsOptions.wsUrl.replace(/(ws(s)?:\/\/)[^\/|:]+(.*)/,"$1".concat(e.wsOptions.wsDomain,"$3")):e.wsOptions.wsUrl}reset(){this.roomId=null,this.cmdSendSsrc=0,this.cmdReceiveSsrc=0,this.selfUserUid=0,this.bindCryptoKey=null,this.cmdMsgPacketSeqNum=0,this.reconnctIdx=0,this.transportChannel&&(this.transportChannel.off("CMD_MSG_REVEIVED"),this.transportChannel.off("CMD_CHANNEL_ESTABLISHED"),this.transportChannel.off("CMD_CONNECTION_RECONNECT"),this.transportChannel.close(),this.transportChannel=null)}genCmdBindRtpPacketMsg(){const e=new DataView(new ArrayBuffer(20));e.setUint8(0,this.RTP_HEADER_V_P_X_CC),e.setUint8(1,this.RTP_HEADER_M_PT),e.setUint16(2,this.cmdMsgPacketSeqNum++),e.setUint32(4,Math.floor((new Date).getTime()/1e3)),e.setUint32(8,this.cmdSendSsrc),e.setUint16(12,4096),e.setUint16(14,1),e.setUint8(16,24),e.setUint8(17,1),e.setUint8(18,0),e.setUint8(19,0);const t=MD.numberArrayToArrayBuffer(uT.exports.HmacSHA256(uT.exports.lib.WordArray.create(MD.arrayBufferToNumberArray(e)),this.bindCryptoKey).words);return MD.concatArrayBuffer(e.buffer,t)}}const xD="DataChannelMsgManager";class LD{constructor(e){this.event_=new VO,this.dataChannel=e.createDataChannel("commandMsgDataChannel",{ordered:!0}),this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=this.onopen.bind(this),this.dataChannel.onerror=this.onerror.bind(this),this.dataChannel.onmessage=this.onmessage.bind(this),this.dataChannel.onclose=this.onclose.bind(this)}on(e,t){this.event_.on(e,t)}off(e,t){t?this.event_.removeListener(e,t):this.event_.removeAllListeners(e)}sendMessage(e){var t;if(!this.dataChannel||"open"!==this.dataChannel.readyState)return iE.getLogger().error(xD,"send message with dataChannel failed for dataChannel unavaliable: ".concat(null===(t=this.dataChannel)||void 0===t?void 0:t.readyState,".")),!1;try{return this.dataChannel.bufferedAmount>=1024e6&&iE.getLogger().warn(xD,"buffer over high threshold of 1M: ".concat(this.dataChannel.bufferedAmount,", send message may blocked and delay.")),this.dataChannel.send(e),!0}catch(jN){return iE.getLogger().error(xD,"send message with dataChannel occur error: ".concat(jN,".")),!1}}close(){this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onerror=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel.close(),this.dataChannel=null)}onopen(){iE.getLogger().info(xD,"onopen, RTCDataChannel connection status: ".concat(this.dataChannel.readyState)),clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_ESTABLISHED")}onmessage(e){e.data?this.event_.emit("CMD_MSG_REVEIVED",e.data):iE.getLogger().error(xD,"onerror, RTCDataChannel message is null.")}onerror(e){iE.getLogger().error(xD,"onerror, RTCDataChannel occur error: ".concat(e)),this.dataChannelDisConnectTimer||(this.dataChannelDisConnectTimer=setTimeout((()=>{clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_DISCONNECT")}),3e4))}onclose(e){iE.getLogger().info(xD,"onclose, RTCDataChannel closed: ".concat(e)),this.dataChannelDisConnectTimer||(this.dataChannelDisConnectTimer=setTimeout((()=>{clearTimeout(this.dataChannelDisConnectTimer),this.event_.emit("CMD_CHANNEL_DISCONNECT")}),3e4))}}class BD extends PD{initCmdTranportChannel(){this.transportChannel||(this.transportChannel=new LD(this.connection)),this.transportChannel.on("CMD_MSG_REVEIVED",(e=>{super.receivedCmdRtpPacketDecode(e)})),this.transportChannel.on("CMD_CHANNEL_ESTABLISHED",(()=>{iE.getLogger().info(xD,"cmd dataChannel connection established."),this.event.emit(UC.CmdChannelEstablished,BC.DATA_CHANNEL)})),this.transportChannel.on("CMD_CHANNEL_DISCONNECT",(()=>{iE.getLogger().info(xD,"cmd dataChannel connection disconnect."),this.event.emit(UC.CmdChannelDisconnect,BC.DATA_CHANNEL)}))}extraParamsHandle(e){this.connection=e.dataChannelOptions.connection}reset(){this.roomId=null,this.cmdSendSsrc=0,this.cmdReceiveSsrc=0,this.selfUserUid=0,this.cmdMsgPacketSeqNum=0,this.transportChannel&&(this.transportChannel.off("CMD_MSG_REVEIVED"),this.transportChannel.off("CMD_CHANNEL_ESTABLISHED"),this.transportChannel.close(),this.transportChannel=null)}}var VD,YD,jD,FD,HD,KD,zD,WD,GD,JD,qD,XD,QD,$D,ZD,eN,tN,rN,iN,nN,oN,sN,aN,cN,uN,dN,lN,hN,fN,pN,mN,gN,_N,SN,vN,yN,IN,TN;const RN=1e4;var EN=function(e){return e[e.mute=0]="mute",e[e.unmute=1]="unmute",e[e.noChange=2]="noChange",e}(EN||{});const bN={FHD:CC.main,HD:CC.middle1,SD:CC.middle2,LD:CC.slides},CN="Client";let AN=(VD=fP("Client$enableTopThreeAudioMode#boolean#boolean"),YD=lP("".concat(CN,"_switchAudioMode")),jD=fP("Client$getConnectionState#string"),FD=fP("Client$setNetworkBandwidth#void#NetworkBandwidth"),HD=hP("Client$join#Promise#string#JoinConfig"),KD=hP("Client$enableRtcStats#Promise#boolean#number"),zD=hP("Client$leave#Promise"),WD=hP("Client$publish#Promise#Stream#PublishOption"),GD=lP("".concat(CN,"_publishImpl")),JD=hP("Client$unpublish#Promise#Stream"),qD=hP("Client$subscribeAudio#Promise#string"),XD=hP("Client$unSubscribeAudio#Promise#string"),QD=hP("Client$subscribe#Promise#RemoteStream#SubscribeOption"),$D=hP("Client$batchSubscribe#Promise#SubscribeParam[]"),ZD=hP("Client$unsubscribe#Promise#Stream#SubscribeOption"),eN=hP("Client$switchRole#Promise#number#Authorization"),tN=lP("".concat(CN,"_refreshRemoteStreamList")),rN=lP("".concat(CN,"_updateRemoteStream")),iN=lP("".concat(CN,"_removeRemoteStream")),nN=lP("".concat(CN,"_handleWatchMsg")),oN=lP("".concat(CN,"_refreshRoomUserInfos")),sN=fP("Client$setVolume4TopThree#void#number"),aN=fP("Client$muteAudio4TopThree#void#boolean"),cN=hP("Client$setAudioOutput4TopThree#void"),uN=fP("Client$isTopNAudioMuted#boolean"),dN=hP("Client$changeUserName#Promise#string"),lN=hP("Client$startLiveStreaming#Promise#string#string[]#PublishConfig#UserConfig[]"),hN=hP("Client$updateLiveStreaming#Promise#string#string[]#PublishConfig#UserConfig[]"),fN=hP("Client$stopLiveStreaming#Promise#string"),pN=fP("Client$setProxyServer#void#string"),mN=fP("Client$setTurnServer#void#TurnServerConfig"),gN=hP("Client$addMultiRoomMediaRelay#Promise#MultiRoomMediaRelayInfo"),_N=hP("Client$stopMultiRoomMediaRelay#Promise#MultiRoomMediaRelayInfo"),SN=fP("Client$addRelayClient#Client#string"),vN=hP("Client$stopRelayClient#Promise#string"),yN=fP("Client$enableCommandMsg#boolean#boolean"),IN=fP("Client$renewSignature#boolean#ctime#signature"),TN=class e extends $P{constructor(e,t){super({logger:!0,stat:!0,emitter:!0,config:e}),i(this,"status",OC.Idle),i(this,"localRejoinFlag",!1),i(this,"resolutionChangeInfo",{mainResolutionChangeTimer:null,auxResolutionChangeTimer:null,preVideoHeight:new Map}),this.clientSymbol=Symbol("".concat(CN,"_").concat(QP.getSequence())),t&&(this.mainRelayRoomSymbol=t),this.locker=new aP,this.roomId="",this.clientConfig=e,this.userInfo=void 0,this.waitConfigCallbackFunc=void 0,this.topNAudioVolume=100,this.audioPolicy=_O.USER_SUBSCRIBE_AUDIOPOLICY,this.connectState={prevState:"DISCONNECTED",curState:"DISCONNECTED"},this.logger.info(CN,"HRTC VERSION = ".concat(uA,", userAgent = ").concat(navigator.userAgent)),this.top3VolumeUserIds=[],DO.initDeviceChangedNotify(this.eventEmitter,!1),this.accessManager=new fD(this.logger),this.lastCycleFrameDecodedMap=new Map,this.streamInterruptedUsersMap=new Map,this.streamDetectionCriterion=0,this.audioStreams4TopN=new MM,this.downLinkData=null,this.upLinkData=null,this.preNetQuality=null,this.remoteUserManager=new vD(this),this.stat.setRemoteUserManager(this.remoteUserManager),this.connectionsManager=new nD(this.logger,this.stat,this.eventEmitter),this.streamPublishManager=new NM,this.audioLevelInterval=1e3,this.isLoopRejoining=!1,this.upStreamData=null,this.sdpRepInfo=null,this.startupQoSMap=new Map,this.initReport4WindowEvent(),this.cmdMsgAbility={enable:!1,cmdManager:null,msgFormat:VC.STRING},this.roomStreamStatus={},this.isSignatureExpired=!1,this.pktsLostRate={up:0,down:0,preDownRate:[],preRTT:0}}initReport4WindowEvent(){window.onunload=()=>{var e,t;const r=XR.getCurrentTimestamp();null===(e=this.stat)||void 0===e||e.recordCallbackInfoBeacon("window-onunload",null===(t=this.getInfo())||void 0===t?void 0:t.moduleName,r,r,{event:"window-onunload"},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))},window.onbeforeunload=()=>{var e,t;const r=XR.getCurrentTimestamp();null===(e=this.stat)||void 0===e||e.recordCallbackInfoBeacon("window-onbeforeunload",null===(t=this.getInfo())||void 0===t?void 0:t.moduleName,r,r,{event:"window-onbeforeunload"},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))},window.onhashchange=e=>{var t,r;const i=XR.getCurrentTimestamp();null===(t=this.stat)||void 0===t||t.recordCallbackInfoBeacon("window-onhashchange",null===(r=this.getInfo())||void 0===r?void 0:r.moduleName,i,i,{event:"window-onhashchange",newURL:(null==e?void 0:e.newURL)||"",oldURL:(null==e?void 0:e.oldURL)||""},(e=>["object","function"].includes(typeof e)&&e.getStatInfo?JSON.stringify(e.getStatInfo()):JSON.stringify(e||{})))}}getSessionStatus(){return this.status}on(e,t){super.on(e,t,![UC.VolumeIndicator,UC.TransportStats].includes(e.toString()))}off(e,t){super.off(e,t,![UC.VolumeIndicator,UC.TransportStats].includes(e.toString()))}getSymbol(){return this.identifiedID}getInfo(){var e,t;return{moduleName:"Client",appId:this.clientConfig.appId,roomId:this.roomId,userName:null===(e=this.userInfo)||void 0===e?void 0:e.userName,userId:null===(t=this.userInfo)||void 0===t?void 0:t.userId,domain:this.clientConfig.domain,upStreamData:this.upStreamData,sdpRepInfo:this.sdpRepInfo,countryCode:this.clientConfig.countryCode}}enableTopThreeAudioMode(e){return this.enableTopThreeAudioModeImpl(e)}enableTopThreeAudioModeImpl(e){let t=!1;return e&&this.status===OC.Idle&&(this.audioPolicy=_O.TOPN_AUDIOPOLICY,t=!0),t}async switchAudioMode(e){try{if(e!==SO.TOPN_AUDIOPOLICY&&e!==SO.USER_SUBSCRIBE_AUDIOPOLICY)throw this.logger.error(CN,"audioMode is invalid"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);return e%=2,this.logger.info(CN,"switchAudioMode start, new audioPolicy: ".concat(e,", original audioPolicy: ").concat(this.audioPolicy)),this.status===OC.Joined&&(e===_O.USER_SUBSCRIBE_AUDIOPOLICY&&this.audioPolicy===_O.TOPN_AUDIOPOLICY?(this.audioPolicy=e,await this.switchAudioPolicyTop2User()):e===_O.TOPN_AUDIOPOLICY&&this.audioPolicy===_O.USER_SUBSCRIBE_AUDIOPOLICY&&(this.audioPolicy=e,await this.switchAudioPolicyUser2Top(),this.top3VolumeUserIds&&this.top3VolumeUserIds.length>0&&this.eventEmitter.emit(UC.VolumeIndicator,{userVolumeInfos:this.top3VolumeUserIds}))),this.stat.getMediaStat().setAudioPolicy(this.audioPolicy),this.audioPolicy===_O.USER_SUBSCRIBE_AUDIOPOLICY?SO.USER_SUBSCRIBE_AUDIOPOLICY:SO.TOPN_AUDIOPOLICY}catch(jN){this.logger.error(CN,"switchAudioMode, audioPolicy: ".concat(e,", error: ").concat(jN))}return this.audioPolicy}async switchAudioPolicyTop2User(){await this.signal.changeAudioPolicy(_O.USER_SUBSCRIBE_AUDIOPOLICY),await this.unsubscribeAudio4Top();const e=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,mO.TRACK_TYPE_VIDEO);for(const t of e){const e=t.mainStream.tracks;for(const t of e)t.isSubscribed&&await this.resubscribeUserAudio()}}async resubscribeUserAudio(){this.logger.info(CN,"resubscribeUserAudio start");const e=this.remoteUserManager.resubscribeMainStreamAudio(this.roomId);await this.updateSubscribe(e),null==e||e.forEach((e=>{var t,r,i,n;(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Subscribe)||void 0===r?void 0:r.length)>0&&(null===(i=e.mainStream)||void 0===i||null===(n=i.remoteStream)||void 0===n||n.rePlayAudio())}))}async switchAudioPolicyUser2Top(){await this.unsubscribeAudio4SubscribeUsers(),await this.signal.changeAudioPolicy(_O.TOPN_AUDIOPOLICY),this.remoteUserManager.enableTopThreeAudioMode(this.roomId),await this.connectionsManager.generateAndSetOfferSdpByHandler(gO.STREAM_TYPE_MAIN),await this.connectionsManager.generateAndSetAnswerSdpByHandler(gO.STREAM_TYPE_MAIN,this.addSsrc4Top3.bind(this))}async unsubscribeAudio4SubscribeUsers(){this.logger.info(CN,"unsubscribeAudio4SubscribeUsers start");const e=this.remoteUserManager.unsubscribeAllMainStreamAudio(this.roomId);await this.updateSubscribe(e)}async unsubscribeAudio4Top(){await this.unsubscribeUsersAudio()}async unsubscribeAudio4SubscribeAll(){await this.unsubscribeUsersAudio()}async unsubscribeUsersAudio(){const e=[];for(const t of this.audioStreams4TopN.getAudioStreams()){const r=t.ssrc;this.audioStreams4TopN.close(t.streamId),this.logger.info(CN,"delete audio ssrc:".concat(r)),e.push(r)}e.length>0&&await this.connectionsManager.deleteUser(gO.STREAM_TYPE_MAIN,null,e)}async getLocalAudioStats(){const e=new Map,t=this.streamPublishManager.getPublishedMainAudioTrackInfo();if(!t)return this.logger.error(CN,"local stream has not published yet."),e;if("function"!=typeof t.sender.getStats)return this.logger.error(CN,"audio rtpsender is not support getStat"),e;const r={bytesSent:0,packetsSent:0},i=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN),n=this.userInfo.userId||(null==i?void 0:i.getUserId()),o=CO.getLatestStats(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(pC,"_").concat(t.ssrc));return o&&(r.bytesSent=o.bytesSent,r.packetsSent=o.packetsSent,e.set(n,r)),e}async getLocalVideoStats(){const e=new Map,t={mainStream:[],subStream:null};let r=null,i=null;const n=this.streamPublishManager.getMainStreamVideoPublishInfo();if(n){const i=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN),o=this.userInfo.userId||(null==i?void 0:i.getUserId());for(const s of n){r={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0};const i=CO.getLatestStats(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(s.ssrc));i&&(r.bytesSent=XR.getValue(i.bytesSent,0),r.packetsSent=XR.getValue(i.packetsSent,0),r.framesEncoded=XR.getValue(i.framesEncoded,0),r.framesSent=XR.getValue(i.framesSent,0),r.frameWidth=XR.getValue(i.frameWidth,0),r.frameHeight=XR.getValue(i.frameHeight,0),e.has(o)?e.get(o).mainStream.push(r):(t.mainStream.push(r),e.set(o,t)))}}else this.logger.debug(CN,"have no local mainstream collect stats");const o=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(o&&"function"==typeof o.sender.getStats){const r=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN),n=this.userInfo.userId||(null==r?void 0:r.getUserId());i={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0};const s=CO.getLatestStats(this.userInfo.roomId,gO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(o.ssrc));s&&(i.bytesSent=XR.getValue(s.bytesSent,0),i.packetsSent=XR.getValue(s.packetsSent,0),i.framesEncoded=XR.getValue(s.framesEncoded,0),i.framesSent=XR.getValue(s.framesSent,0),i.frameWidth=XR.getValue(s.frameWidth,0),i.frameHeight=XR.getValue(s.frameHeight,0),e.has(n)?e.get(n).subStream=i:(t.subStream=i,e.set(n,t)))}else this.logger.debug(CN,"have no local substream collect stats");return e}async getRemoteAudioStats(){const e=new Map,t=this.remoteUserManager.getAllUserStreamsByType(this.roomId,gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO),r=this.connectionsManager.getReceivers(gO.STREAM_TYPE_MAIN);if(!r||0===r.length)return this.logger.error(CN,"getRemoteAudioStats, peerConnection is not support getReceivers"),e;for(const i of t){const t=i.userId;if(i.mainStream)for(const r of i.mainStream.tracks){const i={bytesReceived:0,packetsReceived:0,packetsLost:0},n=CO.getLatestStats(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(hC,"_").concat(r.cssrc));t&&n&&(i.bytesReceived=XR.getValue(n.bytesReceived,0),i.packetsReceived=XR.getValue(n.packetsReceived,0),i.packetsLost=XR.getValue(n.packetsLost,0),this.connectionsManager.calcChangedStatistic(n.id,i,["bytesReceived","packetsReceived","packetsLost"]),e.set(t,i))}}return e}async getRemoteVideoStats(){const e=new Map,t=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,mO.TRACK_TYPE_VIDEO);for(const r of t)r.mainStream&&await this.getRemoteVideoTracksStatistic(r.userId,gO.STREAM_TYPE_MAIN,!1,r.mainStream.tracks,e),r.auxStream&&await this.getRemoteVideoTracksStatistic(r.userId,gO.STREAM_TYPE_AUX,!0,r.auxStream.tracks,e);return e}isSendingStream(){var e,t;const r=(null===(e=this.connectionsManager.getSenders(gO.STREAM_TYPE_MAIN))||void 0===e?void 0:e.length)>0,i=(null===(t=this.connectionsManager.getSenders(gO.STREAM_TYPE_AUX))||void 0===t?void 0:t.length)>0;return r||i}isReceivingStream(){var e,t;const r=(null===(e=this.connectionsManager.getReceivers(gO.STREAM_TYPE_MAIN))||void 0===e?void 0:e.length)>0,i=(null===(t=this.connectionsManager.getReceivers(gO.STREAM_TYPE_AUX))||void 0===t?void 0:t.length)>0;return r||i}async getRemoteVideoTracksStatistic(e,t,r,i,n){if(i&&0!==i.length)for(const o of i){const i=CO.getLatestStats(this.userInfo.roomId,r?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,"".concat(fC,"_").concat(o.cssrc));if(!i)continue;const s={streamId:o.trackId,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0,frameWidth:0,frameHeight:0,frameRate:0,frameDropped:0};if(s.bytesReceived=XR.getValue(i.bytesReceived,0),s.packetsReceived=XR.getValue(i.packetsReceived,0),s.packetsLost=XR.getValue(i.packetsLost,0),s.framesDecoded=XR.getValue(i.framesDecoded,0),s.frameDropped=XR.getValue(i.framesDropped,0),s.frameRate=XR.getValue(i.framesPerSecond,0),s.frameWidth=i.frameWidth,s.frameHeight=i.frameHeight,this.connectionsManager.calcChangedStatistic(i.id,s,["bytesReceived","packetsReceived","packetsLost","framesDecoded"]),s.frameWidth&&s.frameHeight){const e=i.trackId;if(e){const t=CO.getLatestStats(this.userInfo.roomId,r?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN,e)||{frameWidth:0,frameHeight:0};s.frameWidth=t.frameWidth,s.frameHeight=t.frameHeight}}if(n.has(e))t===gO.STREAM_TYPE_AUX?n.get(e).subStream=s:n.get(e).mainStream.push(s);else{const r={mainStream:[],subStream:null};t===gO.STREAM_TYPE_AUX?r.subStream=s:r.mainStream.push(s),n.set(e,r)}}}async getDownloadStatistic(e){const t=new Map,r=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,e);for(const a of r)await this.getTrackDownloadStatistic([...a.mainStream.tracks,...a.auxStream.tracks],t);if(0===t.size)return this.downLinkData=null,-1;let i=0,n=0,o=0;for(const[a,c]of t)if(this.downLinkData&&this.downLinkData.has(a)){const e=c.packetsReceived-this.downLinkData.get(a).packetsReceived;e>0&&(n+=e,i+=Math.max(c.packetsLost-this.downLinkData.get(a).packetsLost,0),o+=Math.max(c.nackCount-this.downLinkData.get(a).nackCount,0))}else n+=c.packetsReceived,i+=c.packetsLost,o+=c.nackCount;let s=0;if(n<=0)s=-1;else{let e=1e3*this.connectionsManager.getConnectionRTT();e?this.pktsLostRate.preRTT=e:e=this.pktsLostRate.preRTT,s=e<=40?100*o/(o+n):e<=60?.9*o*100/(.9*o+n):e<=100?.8*o*100/(.8*o+n):e<=150?.7*o*100/(.7*o+n):.6*o*100/(.6*o+n),s=Math.min(Math.max(100*i/(i+n),s),100)}return this.downLinkData=t,this.logger.debug(CN,"downLinkData packetsLost:".concat(i,", packetsReceived:").concat(n,",rate:").concat(s)),s}async getTrackDownloadStatistic(e,t){for(const r of e){const e=r.type===mO.TRACK_TYPE_VIDEO?"".concat(fC):"".concat(hC),i=CO.getLatestStats(this.userInfo.roomId,r.streamType,"".concat(e,"_").concat(r.cssrc)),n={packetsReceived:0,packetsLost:0,nackCount:0};i&&(n.packetsReceived=XR.getValue(i.packetsReceived,0),n.packetsLost=XR.getValue(i.packetsLost,0),n.nackCount=XR.getValue(i.nackCount,0),this.connectionsManager.calcChangedStatistic(i.id,n),t.set(r.cssrc.toString(),n))}}static getSenderType(e,t){return"audio"===e||t&&t.sender?gO.STREAM_TYPE_MAIN:gO.STREAM_TYPE_AUX}async getUploadStatistic(t){var r,i;const n=this.streamPublishManager.getPublishedMainVideoTrackInfo(),o=this.streamPublishManager.getPublishedMainAudioTrackInfo(),s=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(!n&&!o&&!s)return-1;const a={packetsLost:0,packetsSent:0,fractionLost:0},c=t===mO.TRACK_TYPE_VIDEO?"".concat(mC):"".concat(pC),u=t===mO.TRACK_TYPE_VIDEO?(null==n?void 0:n.ssrc)||(null==s?void 0:s.ssrc):null==o?void 0:o.ssrc;if(u){const r=CO.getLatestStats(this.userInfo.roomId,e.getSenderType(t,n),"".concat(c,"_").concat(u));if(r&&(a.packetsSent=XR.getValue(r.packetsSent,0),r.remoteId)){const r=t===mO.TRACK_TYPE_VIDEO?"".concat(_C):"".concat(gC),i=CO.getLatestRemoteInboundStats(this.userInfo.roomId,e.getSenderType(t,n),"".concat(r,"_").concat(u));a.packetsLost=XR.getValue(null==i?void 0:i.packetsLost,0),a.fractionLost=XR.getValue(null==i?void 0:i.fractionLost,0)}}let d=0,l=0;this.upLinkData?(l=a.packetsSent-this.upLinkData.packetsSent,d=a.packetsLost-this.upLinkData.packetsLost):(l=a.packetsSent,d=a.packetsLost);const h=(null===(r=this.upLinkData)||void 0===r?void 0:r.deltaPacketsSend)||0,f=(null===(i=this.upLinkData)||void 0===i?void 0:i.deltaPacketsLost)||0;this.upLinkData=a,d<=0?(l=h||this.upLinkData.packetsSent,d=f||this.upLinkData.packetsLost):(this.upLinkData.deltaPacketsSend=l,this.upLinkData.deltaPacketsLost=d);const p=l>0?Math.max(d/l*100,100*(a.fractionLost||0)):-1;return this.logger.debug(CN,"upLinkData packetsLost:".concat(a.packetsLost," ").concat(d," ").concat(100*(a.fractionLost||0),", packetssend:").concat(l,", rate:").concat(p)),p}getConnectionState(){return this.connectState.curState}async getTransportStats(){const e=this.stat.getMediaStat().getTransportMediaStats(),t=this.streamPublishManager.getPublishedMainVideoTrackInfo();if(t){const r=CO.getLatestStats(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(_C,"_").concat(t.ssrc))||{};e.rtt=1e3*(r.roundTripTime||0)}else e.rtt=1e3*this.connectionsManager.getConnectionRTT();return e.upPktsLostRate=this.pktsLostRate.up,e.downPktsLostRate=this.pktsLostRate.down,e}transportStatsRegularReport(){clearTimeout(this.transportStatsTimer),this.transportStatsTimer=setTimeout((()=>{clearTimeout(this.transportStatsTimer),this.calcPktsLostRate().then((async()=>{const e=await this.getTransportStats();if(e.downVideoStreams=await this.getRemoteVideoStats(),this.predownVideoStreams)for(const a of e.downVideoStreams.keys()){var t;for(const t of(null===(r=e.downVideoStreams.get(a))||void 0===r?void 0:r.mainStream)||[]){var r,i;const e=((null===(i=this.predownVideoStreams.get(a))||void 0===i?void 0:i.mainStream)||[]).find((e=>e.streamId===t.streamId));t.bitrate=e?8*Math.max(t.bytesReceived-e.bytesReceived,0):t.bytesReceived,t.frameRate=t.frameRate||(e?Math.max(t.framesDecoded-e.framesDecoded,0):t.framesDecoded)}const o=null===(t=e.downVideoStreams.get(a))||void 0===t?void 0:t.subStream;if(o){var n;const e=null===(n=this.predownVideoStreams.get(a))||void 0===n?void 0:n.subStream;o.bitrate=e?8*Math.max(o.bytesReceived-e.bytesReceived,0):o.bytesReceived,o.frameRate=o.frameRate||(e?Math.max(o.framesDecoded-e.framesDecoded,0):o.framesDecoded)}}else for(const a of e.downVideoStreams.keys()){var o;for(const r of(null===(s=e.downVideoStreams.get(a))||void 0===s?void 0:s.mainStream)||[]){var s;r.bitrate=0}const t=null===(o=e.downVideoStreams.get(a))||void 0===o?void 0:o.subStream;t&&(t.bitrate=0)}this.predownVideoStreams=e.downVideoStreams,this.eventEmitter.emit(UC.TransportStats,e)})).finally(this.transportStatsRegularReport.bind(this,this.predownVideoStreams))}),1e3)}getICETransportStat(e){return this.connectionsManager.getICETransportStat(e)}cleanTransportStats(){this.stat.clearMediaStatBytes()}setNetworkBandwidth(e){if((null==e?void 0:e.maxBandwidth)PC.MAX_BAND_WIDTH)throw this.logger.info(CN,"MaxBandWidth Limits [3072Kpbs, 51200Kpbs]"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);this.bandwidthParam={maxBandwidth:1e3*(null==e?void 0:e.maxBandwidth)||PC.DEFAULT_BANDWIDTH_4M}}async join(e,t){return await this.joinImpl(e,t)}async joinImpl(e,t){iE.addPrivacyString(null==t?void 0:t.userId),iE.addPrivacyString(null==t?void 0:t.userName),iE.addPrivacyString(null==t?void 0:t.signature),this.logger.info(CN,"join room roomId:".concat(e," userId:").concat(t.userId," role:").concat(t.role));const r=[];let i="";this.roomId=e;try{var n,o,s,a;if(this.status!==OC.Idle)throw this.logger.error(CN,"room status error!"),this.stat.reportJoinInfo(jC.ROOM_NOT_AVAILABLE,void 0,!1,void 0,"room status error!"),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR);Zk.checkJoinParams(e,t),this.mainRelayRoomSymbol&&ED.roleValidCheck4RelayRoom(this,t.role);const c=uM.init(this.identifiedID,e,t);this.userInfo=c;const u=await this.accessManager.getAccessInfo(this.clientConfig.countryCode,r);this.stat.getMediaStat().setAudioPolicy(this.audioPolicy),this.stat.setLocalUserInfo(c),await this.locker.lock("".concat(CN,":joinImpl")),this.newSignal(u),this.signalEvent(),this.status=OC.Joining,i=await this.signal.connect(c,r),this.logger.info(CN,"joinImpl, actualAcsIp:".concat(i)),await this.waitNotifyConfig(r),await this.connectionsManager.initConnectionAndSdp(this.roomId,gO.STREAM_TYPE_MAIN,{onTrackHandler:this.onTrackHandler.bind(this)}),await this.connectionsManager.initConnectionAndSdp(this.roomId,gO.STREAM_TYPE_AUX,{onTrackHandler:this.onTrackHandler.bind(this)});const d=await this.connectionsManager.modifySdpInfo(gO.STREAM_TYPE_MAIN,this.cmdMsgAbility.enable),l=await this.connectionsManager.modifySdpInfo(gO.STREAM_TYPE_AUX),h=await this.signal.join(this.userInfo,d,l,this.audioPolicy,null===(n=this.bandwidthParam)||void 0===n?void 0:n.maxBandwidth,this.connectionsManager.getPortType(),this.cmdMsgAbility.enable,this.sfuConfigs);!this.clientConfig.countryCode&&h.countryCode&&this.accessManager.setOpsUrl(h.countryCode),this.sdpRepInfo=h.sdp,h.userInfos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(e.userId,e.userEid)})),null!=h&&h.userEid&&this.stat.getMediaStat().setEncryInfo(this.userInfo.userId,h.userEid.toString());const f=String(h.roomUid);this.stat.setRoomUid(f);const p=null===(o=h.roomStreamStatus)||void 0===o?void 0:o.audience;let m;m=this.audioPolicy===_O.TOPN_AUDIOPOLICY?async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(h,r,i,n),p===YC.PAUSE&&this.userInfo.role===nM?{answerSdp:t}:await this.addSsrc4Top3(t)}:async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(h,r,i,n),{answerSdp:t}};const g=null===(s=h.negSdp.find((e=>e.type===RM.MAIN)))||void 0===s?void 0:s.sdp,_=null===(a=h.negSdp.find((e=>e.type===RM.DESKTOP)))||void 0===a?void 0:a.sdp;this.connectionsManager.setSsrcsMapping(this.sdpRepInfo),await this.connectionsManager.handleAnswerSdpFromServer(gO.STREAM_TYPE_MAIN,g,m),await this.connectionsManager.handleAnswerSdpFromServer(gO.STREAM_TYPE_AUX,_),await this.handleRoomStreamStatus(p),this.upStreamData=h.userInfos.find((e=>{var t;return e.userId===(null===(t=this.userInfo)||void 0===t?void 0:t.userId)})),this.remoteUserManager.initialize(this.userInfo.userId,h.sdp),this.stat.setSFUAddress(this.connectionsManager.getSfuInfoFromSdp(g,_)),this.signal.keepAlive(),this.status=OC.Joined,this.logger.info(CN,"join room success"),this.streamPublishManager.setSdpRepInfo(this.sdpRepInfo),this.statJoinRoomInfo(i,!1,r),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.transportStatsRegularReport(),this.setAudioLevelStatTimer(),ED.addConnectionCache(this.mainRelayRoomSymbol||this.clientSymbol,this.roomId,this),await this.doRefreshRoomUserInfos(this.userInfo.roomId,h.userInfos,!1),this.locker.unlock("".concat(CN,":joinImpl"))}catch(jN){throw this.locker.unlock("".concat(CN,":joinImpl")),this.logger.error(CN,"join occur error: ".concat(jN)),this.cleanup(),this.stat.reportJoinInfo(null==jN?void 0:jN.code,i,!1,r,null==jN?void 0:jN.message),await TD.uploadLogFile(this),jN}}reportLogs(){TD.uploadLogFile(this).then((()=>{this.eventEmitter.emit(UC.LogUploaded,{status:200})})).catch((e=>{this.logger.error(CN,"reportLogs occur error: ".concat(e)),this.eventEmitter.emit(UC.LogUploaded,{status:500})}))}statJoinRoomInfo(e,t,r){this.stat.reportJoinInfo(0,e,t,r,""),this.stat.getMediaStat().setConnectionsManager(this.connectionsManager),CO.addConnection(this.userInfo.roomId,this.connectionsManager),this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos()),this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo()),this.stat.startMediaCollector()}async enableRtcStats(e,t){return await this.enableRtcStatsImpl(e,t)}async enableRtcStatsImpl(e,t){if(this.status!==OC.Joined)throw this.logger.error(CN,"cannot enableRtcStats before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot enableRtcStats before join room");if(!e)return clearTimeout(this.rtcStatsInterval),this.rtcStatsInterval=null,void this.logger.info(CN,"enableRtcStats is disable");if(!Number.isInteger(t)||t<100)throw this.logger.error(CN,"invalid interval"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e&&this.rtcStatsInterval)throw this.logger.error(CN,"enableRtcStats has been invoked, no need do again"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"enableRtcStats has been invoked, no need do again");return this.rtcStatsCriterion=t,this.doEnableRtcStats()}async doEnableRtcStats(){let e=0;const t=()=>{this.rtcStatsInterval=setTimeout((async()=>{const r=(await this.stat.buildRtcStatsDebugInfo(this.rtcStatsCriterion/1e3)).mediaStatsDebugInfo;this.doTriggerRtcStats(r,e),e++,t()}),0===e?0:this.rtcStatsCriterion)};t()}doTriggerRtcStats(e,t){if(0===t)return;if(!e||0==e.length)return;const r=[];e.forEach((e=>{if(!e.event)return;const t=e.streams||[];switch(e.event){case ZC.QoS_UP_STREAM_VIDEO:this.addRtcStatInfos(t,!1,mO.TRACK_TYPE_VIDEO,r);break;case ZC.QoS_UP_STREAM_AUDIO:this.addRtcStatInfos(t,!1,mO.TRACK_TYPE_AUDIO,r,CC.main);break;case ZC.QoS_AUX_UP_STREAM_VIDEO:this.addRtcStatInfos(t,!1,mO.TRACK_TYPE_VIDEO,r,CC.desktop);break;case ZC.QoS_DOWN_STREAM_VIDEO:this.addRtcStatInfos(t,!0,mO.TRACK_TYPE_VIDEO,r);break;case ZC.QoS_DOWN_STREAM_AUDIO:this.addRtcStatInfos(t,!0,mO.TRACK_TYPE_AUDIO,r,CC.main);break;case ZC.QoS_AUX_DOWN_STREAM_VIDEO:this.addRtcStatInfos(t,!0,mO.TRACK_TYPE_VIDEO,r,CC.desktop);break;default:this.logger.debug(CN,"".concat(e.event," no need stats"))}})),this.connectState.curState===vC[yC.CONNECTED]&&r.length>0&&this.eventEmitter.emit(UC.RtcStats,r)}addRtcStatInfos(e,t,r,i,n){let o={};const s=this.userInfo.userName||this.userInfo.userId;for(let v=0;v{this.logger.info(CN,"leave room"),this.status!==OC.Joined&&this.status!==OC.Rejoining?t(new qc(Gc.RTC_ERR_CODE_STATUS_ERROR)):(this.status=OC.Leaving,this.signal.leave().then((r=>{if(r instanceof qc)return this.stat.reportLeavInfo(FC.LEAVE_ROOM_ERROR),this.stat.getMediaStat().clearEncryUserId(),void t(r);this.doLeaveRoom(),this.stat.reportLeavInfo(FC.LEAVE_ROOM_SUCCESS),this.stat.getMediaStat().clearEncryUserId(),this.stopStreamResolutionDetection(),this.logger.info(CN,"leave success"),e()})))}))}doLeaveRoom(){this.cleanup(),this.cleanTransportStats(),this.stat.leaveRoom(),nO.immediateReportRecords(),this.roomStreamStatus={}}resetConnection(){const e=[],t=this.streamPublishManager.getPublishedMainVideoTrackInfo();t&&e.push(t.sender);const r=this.streamPublishManager.getPublishedMainAudioTrackInfo();r&&e.push(r.sender),this.connectionsManager.destroyPeerConnection(gO.STREAM_TYPE_MAIN,e);const i=this.streamPublishManager.getPublishedAuxVideoTrackInfo();this.connectionsManager.destroyPeerConnection(gO.STREAM_TYPE_AUX,i?[i.sender]:[])}async rejoin(e,t){this.logger.info(CN,"rejoin room roomId:".concat(e," JoinConfig:").concat(JSON.stringify(t)));const r=[];let i="";this.roomId=e;try{var n,o,s,a;Zk.checkJoinParams(e,t),this.mainRelayRoomSymbol&&ED.roleValidCheck4RelayRoom(this,t.role);const c=uM.init(this.identifiedID,e,t);if(this.userInfo=c,this.stat.setLocalUserInfo(c),this.resetConnection(),this.streamPublishManager.reset(),clearTimeout(this.netQualityTimer),clearTimeout(this.transportStatsTimer),this.signal)this.signal.reset();else{const e=await this.accessManager.getAccessInfo(this.clientConfig.countryCode,r);this.newSignal(e),this.signalEvent()}this.status=OC.Joining,i=await this.signal.connect(c,r),this.logger.info(CN,"rejoin, actualAcsIp:".concat(i)),await this.waitNotifyConfig(r),await this.connectionsManager.initConnectionAndSdp(this.roomId,gO.STREAM_TYPE_MAIN,{onTrackHandler:this.onTrackHandler.bind(this)}),await this.connectionsManager.initConnectionAndSdp(this.roomId,gO.STREAM_TYPE_AUX,{onTrackHandler:this.onTrackHandler.bind(this)});const u=await this.connectionsManager.modifySdpInfo(gO.STREAM_TYPE_MAIN,this.cmdMsgAbility.enable),d=await this.connectionsManager.modifySdpInfo(gO.STREAM_TYPE_AUX),l=await this.signal.join(this.userInfo,u,d,this.audioPolicy,null===(n=this.bandwidthParam)||void 0===n?void 0:n.maxBandwidth,this.connectionsManager.getPortType(),this.cmdMsgAbility.enable,this.sfuConfigs);!this.clientConfig.countryCode&&l.countryCode&&this.accessManager.setOpsUrl(l.countryCode),this.sdpRepInfo=l.sdp,l.userInfos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(e.userId,e.userEid)})),null!=l&&l.userEid&&this.stat.getMediaStat().setEncryInfo(this.userInfo.userId,l.userEid.toString());const h=String(l.roomUid);this.stat.setRoomUid(h);const f=null===(o=l.roomStreamStatus)||void 0===o?void 0:o.audience;let p;p=this.audioPolicy===_O.TOPN_AUDIOPOLICY?async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(l,r,i,n),f===YC.PAUSE&&this.userInfo.role===nM?{answerSdp:t}:await this.addSsrc4Top3(t)}:async e=>{let{remoteDescription:t,bindCryptoKey:r,wsUrl:i,dataChannelEnable:n}=e;return await this.negTransportChannelHandler(l,r,i,n),{answerSdp:t}};const m=null===(s=l.negSdp.find((e=>e.type===RM.MAIN)))||void 0===s?void 0:s.sdp,g=null===(a=l.negSdp.find((e=>e.type===RM.DESKTOP)))||void 0===a?void 0:a.sdp;this.connectionsManager.setSsrcsMapping(this.sdpRepInfo),await this.connectionsManager.handleAnswerSdpFromServer(gO.STREAM_TYPE_MAIN,m,p),await this.connectionsManager.handleAnswerSdpFromServer(gO.STREAM_TYPE_AUX,g),await this.handleRoomStreamStatus(f),this.upStreamData=l.userInfos.find((e=>{var t;return e.userId===(null===(t=this.userInfo)||void 0===t?void 0:t.userId)})),this.remoteUserManager.initialize(this.userInfo.userId,l.sdp),this.stat.setSFUAddress(this.connectionsManager.getSfuInfoFromSdp(m,g)),this.signal.keepAlive(),this.status=OC.Joined,this.localRejoinFlag=!0,this.streamPublishManager.setSdpRepInfo(this.sdpRepInfo),this.statJoinRoomInfo(i,!0,r),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.transportStatsRegularReport(),this.setAudioLevelStatTimer(),ED.addConnectionCache(this.mainRelayRoomSymbol||this.clientSymbol,this.roomId,this),await this.doRefreshRoomUserInfos(this.userInfo.roomId,l.userInfos,!0),this.logger.info(CN,"rejoin, rejoin room success")}catch(jN){throw this.logger.error(CN,"rejoin room fail, error:".concat(jN)),this.stat.reportJoinInfo(null==jN?void 0:jN.code,i,!0,r,null==jN?void 0:jN.message),await TD.uploadLogFile(this),jN}}async changeStreamMuteStatusNotify(e,t,r,i){const n={"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16),videoStreams:[]};if(t===mO.TRACK_TYPE_VIDEO){const t={ssrc:0,mute:e};if(r===CC.desktop)t.ssrc=this.sdpRepInfo.desktopVideo.sendSsrcBegin;else if(t.ssrc=this.sdpRepInfo.video.sendSsrcBegin,i){const t={ssrc:this.sdpRepInfo.video.sendSsrcEnd,mute:e};n.videoStreams.push(t)}n.videoStreams.push(t)}else{const t={ssrc:this.sdpRepInfo.audio.sendSsrcBegin,mute:e};n.audioStreams=[t]}await this.signal.changeStreamStatus(n)}async setSendBitrate(e,t,r){if(!e)return void this.logger.info(CN,"sender is null");if("function"!=typeof e.getParameters)return void this.logger.info(CN,"sender not support getParameters");if("function"!=typeof e.setParameters)return void this.logger.info(CN,"sender not support setParameters");const i=e.getParameters();i.encodings.length<=0?this.logger.info(CN,"sender has no track, can not set maxBitRate"):(i.encodings[0].maxBitrate=t,await e.setParameters(i),this.logger.info(CN,"success set ".concat(r," sender maxBitrate: ").concat(t)))}static judgeNetworkQuality(e){return-1===e?yO.NETWORK_QUALITY_UNKNOW:e<1?yO.NETWORK_QUALITY_GREAT:e<3?yO.NETWORK_QUALITY_GOOD:e<6?yO.NETWORK_QUALITY_DEFECTS:e<12?yO.NETWORK_QUALITY_WEAK:e<20?yO.NETWORK_QUALITY_BAD:yO.NETWORK_QUALITY_DISCONNECT}async calcPktsLostRate(){const e=this.connectionsManager.getConnection(gO.STREAM_TYPE_MAIN);if(!e||["disconnected","failed","closed"].includes(e.connectionState))return;let t=await this.getUploadStatistic("video");if(t<0&&(t=await this.getUploadStatistic("audio")),this.pktsLostRate.up=Math.round(t),t=await this.getDownloadStatistic(mO.TRACK_TYPE_VIDEO),t<0&&(t=await this.getDownloadStatistic(mO.TRACK_TYPE_AUDIO)),t<0)return void(this.pktsLostRate.down=-1);this.pktsLostRate.preDownRate.push(t),this.pktsLostRate.preDownRate.length>3&&this.pktsLostRate.preDownRate.splice(0,1);const r=this.smoothData(this.pktsLostRate.preDownRate,.9);this.pktsLostRate.down=Math.round(r[r.length-1])}smoothData(e,t){const r=e=>e.reduce((function(e,t){return e+t}),0)/e.length,i=r(e)*t,n=[];for(let o=0;o0?n[o-1]:e[e.length-1],a=o{clearTimeout(this.netQualityTimer);let t={uploadPkgLoss:0,downloadPkgLoss:0};try{const r=this.connectionsManager.getConnection(gO.STREAM_TYPE_MAIN);if(r&&!["disconnected","failed","closed"].includes(r.connectionState)||(t={uploadPkgLoss:yO.NETWORK_QUALITY_DISCONNECT,downloadPkgLoss:yO.NETWORK_QUALITY_DISCONNECT}),t.uploadPkgLoss=e.judgeNetworkQuality(this.pktsLostRate.up),t.downloadPkgLoss=e.judgeNetworkQuality(this.pktsLostRate.down),!this.preNetQuality||this.preNetQuality.uploadPkgLoss!==t.uploadPkgLoss||this.preNetQuality.downloadPkgLoss!==t.downloadPkgLoss){const e={uplinkNetworkQuality:t.uploadPkgLoss,downlinkNetworkQuality:t.downloadPkgLoss};this.logger.info(CN,"emit:".concat(UC.NetworkQuality,", quality:").concat(JSON.stringify(e))),this.eventEmitter.emit(UC.NetworkQuality,e),this.preNetQuality=t}}finally{this.netQualityRegularReport.bind(this)}}),2e3)}validatePublishRequest(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"can not publish stream before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"can not publish stream before join room");if(this.userInfo.role===nM)throw this.logger.error(CN,"the player role can not publish stream"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"the player role can not publish stream");if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e.hasAudioTrack()||e.hasVideoTrack()||this.logger.warn(CN,"stream has no audio and video"),"local"!==e.getType())throw this.logger.error(CN,"stream type: ".concat(e.getType()," cannot publish")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"stream type: ".concat(e.getType()," cannot publish"))}async publish(e,t){try{return await this.publishImpl(e,t),void(e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_START,KC.RESULT_SUCCESS))}catch(Aw){throw e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_START,KC.RESULT_ERROR),Aw}}async publishImpl(e,t){try{if(!e)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");if(await this.publishStream(e,t),!e.isAuxiliary()){if(this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos())&&(e.hasAudioTrack()&&this.buildSendMediaStreamInfo(TC.Audio),t&&e.hasVideoTrack())){const e=this.streamPublishManager.getPublishedMainVideoTrackInfos().map((e=>e.ssrc));this.buildSendMediaStreamInfo(TC.Video,e)}}}catch(jN){throw this.logger.error(CN,"publishImpl fail, errMsg = ".concat(jN)),jN}}async publishStream(e,t){this.logger.info(CN,"publish ".concat(e.isAuxiliary()?"aux":"main"," stream")),this.validatePublishRequest(e);const r=e,i=this.streamPublishManager.generatePubInfoWhenPublish(r,t);await this.sendPublishRequest(i.allTracks2Publish),await this.updateStreamTracks(r,i),this.startStreamResolutionDetection(r),r.addClient(this)}async sendPublishRequest(e){e&&await this.sendPublishReq(e)}startStreamResolutionDetection(e){var t;if(!e||Cw.isFirefox())return;const r=e.isAuxiliary();!r&&this.resolutionChangeInfo.mainResolutionChangeTimer&&(clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer),r&&this.resolutionChangeInfo.auxResolutionChangeTimer&&(clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null),this.logger.info(CN,"startStreamResolutionDetection isAuxiliary: ".concat(r));const i=r?this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_AUX):null===(t=this.streamPublishManager)||void 0===t?void 0:t.getLocalStream(gO.STREAM_TYPE_MAIN);if(i)try{this.resolutionChangeInfo[r?"auxResolutionChangeTimer":"mainResolutionChangeTimer"]=setInterval((async()=>{const e=this.streamPublishManager.getStreamTrackInfo(i),t={"x-nuwa-trace-id":XR.generateRandomId(32,16),"x-nuwa-span-id":XR.generateRandomId(16,16),videoStreams:[]};for(const n of e){if("audio"===n.type)return;if(!(r?CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(n.upstream.ssrc),"packetsSent"):CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(n.upstream.ssrc),"packetsSent")))continue;const e={resolutionId:n.resolutionId,content:n.upstream.content,streamUid:n.upstream.streamUid,ssrc:n.upstream.ssrc,mute:n.upstream.mute,width:0,height:0};this.resolutionChangeInfo.preVideoHeight.has(e.resolutionId)||this.resolutionChangeInfo.preVideoHeight.set(e.resolutionId,i.getVideoHeight(e.resolutionId));let o=!1;r?(e.height=CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(e.ssrc),"frameHeight"),e.width=CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_AUX,"".concat(mC,"_").concat(e.ssrc),"frameWidth")):(e.height=CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(e.ssrc),"frameHeight"),e.width=CO.getLatestValue(this.userInfo.roomId,gO.STREAM_TYPE_MAIN,"".concat(mC,"_").concat(e.ssrc),"frameWidth")),o=Math.abs(this.resolutionChangeInfo.preVideoHeight.get(e.resolutionId)-e.height)/this.resolutionChangeInfo.preVideoHeight.get(e.resolutionId)>.1,o&&(t.videoStreams.push(e),this.resolutionChangeInfo.preVideoHeight.set(e.resolutionId,e.height))}t.videoStreams.length>0&&await this.signal.changeStreamStatus(t)}),5e3)}catch(jN){throw this.logger.error(CN,"startStreamResolutionDetection, occur error: ".concat(jN)),jN}}stopStreamResolutionDetection(e){var t;if(!e)return clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer=null,clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null,void this.resolutionChangeInfo.preVideoHeight.clear();e.isAuxiliary()?(clearInterval(this.resolutionChangeInfo.auxResolutionChangeTimer),this.resolutionChangeInfo.auxResolutionChangeTimer=null):(clearInterval(this.resolutionChangeInfo.mainResolutionChangeTimer),this.resolutionChangeInfo.mainResolutionChangeTimer=null),null===(t=e.getStreamInfo().videoProfiles)||void 0===t||t.forEach((e=>this.resolutionChangeInfo.preVideoHeight.delete(e.resolutionId)))}async updateStreamTracks(e,t){if(!e)return;const r=e.isAuxiliary();t.tracks2UnPublish&&0!==t.tracks2UnPublish.length||t.tracks2NewPublish&&0!==t.tracks2NewPublish.length?r?await this.updateAuxStreamTrack(e,t):await this.updateMainStreamTrack(e,t):this.logger.info(CN,"update ".concat(r?"aux":"main"," streamTracks, no new publish and unpublish, so no need update sdp"))}async updateMainStreamTrack(e,t){const r=t.tracks2UnPublish.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)),i=this.removeTracksWhenPublish(r),n=t.tracks2UnPublish.filter((e=>e.type===mO.TRACK_TYPE_AUDIO)),o=this.removeTracksWhenPublish(n),s=o.length>0?o[0]:null,a=t.tracks2NewPublish.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)),c=await this.addVideoTracksWhenPublish(e,a),u=t.tracks2NewPublish.filter((e=>e.type===mO.TRACK_TYPE_AUDIO)),d=await this.addAudioTrackWhenPublish(e,u),l=t.tracks2KeepPublish.filter((e=>e.type===mO.TRACK_TYPE_AUDIO)),h=this.getKeepAudioTrackSsrcSender(l),f=t.tracks2KeepPublish.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)),p=this.getKeepVideoTracksSsrcSender(f);await this.generateNewOfferSdp(h,d,p,c,i,s),u.length>0&&await this.sendAudioMedia(e,d),a.length>0&&await this.sendVideoMedia(e,c),null==r||r.forEach((e=>{this.streamPublishManager.unPublishTrackSuccess(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO,e.upstream.streamUid.toString())})),null==n||n.forEach((e=>{this.streamPublishManager.unPublishTrackSuccess(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO,e.upstream.streamUid.toString())}))}async updateAuxStreamTrack(e,t){if(t.tracks2NewPublish&&t.tracks2NewPublish.length>0){const r=t.tracks2NewPublish&&t.tracks2NewPublish.filter((e=>e.type===mO.TRACK_TYPE_VIDEO))[0].ssrc,i=await this.connectionsManager.addTrack(gO.STREAM_TYPE_AUX,e.getVideoTrack(),e.getMediaStream());await this.connectionsManager.modifyPublishOfferSdp(gO.STREAM_TYPE_AUX,this.userInfo.userId,[r]),this.logger.info(CN,"aux send bitrate ".concat(e.getScreenSendBitrate())),await this.setSendBitrate(i,e.getScreenSendBitrate(),"auxVideo"),this.streamPublishManager.publishAuxVideoTrackOK(i,r);const n=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_AUX);n&&(n.off(eC,this.addLocalAuxStreamEndedHandler.bind(this)),n.on(eC,this.addLocalAuxStreamEndedHandler.bind(this))),await e.resumeMixScreenAudio()}else{const r=t.tracks2UnPublish;let i=0;r.forEach((e=>{i=e.ssrc,this.connectionsManager.removeTrack(gO.STREAM_TYPE_AUX,e.sender)})),await this.connectionsManager.modifyPublishOfferSdp(gO.STREAM_TYPE_AUX,this.userInfo.userId,[],0,[i]),await e.stopMixScreenAudio()}}async sendAudioMedia(e,t){if(t)try{await this.setSendBitrate(t.sender,e.getAudioSendBitrate(),"audio"),this.streamPublishManager.publishMainAudioTrackOK(t.sender,t.ssrc),this.logger.info(CN,"sendAudioMedia, send audio media successfully")}catch(jN){throw this.logger.error(CN,"sendAudioMedia, occur error: ".concat(jN)),jN}}async sendVideoMedia(e,t){if(0!==t.length)try{const r=[];t.forEach((t=>{r.push(this.setSendBitrate(t.sender,e.getVideoMaxSendBitrate(t.resolutionId),"mainVideo"))})),await Promise.all(r).then((()=>{t.forEach((e=>{this.streamPublishManager.publishMainVideoTrackOK(e.sender,e.ssrc,e.streamId)}))})),this.logger.info(CN,"sendVideoMedia, send video media successfully")}catch(jN){throw this.logger.error(CN,"sendVideoMedia, occur error: ".concat(jN)),jN}}async generateNewOfferSdp(e,t,r,i,n,o){try{const s=[];r.forEach((e=>s.push(e.ssrc))),i.forEach((e=>s.push(e.ssrc)));const a=t?t.ssrc:e?e.ssrc:null,c=[];n.forEach((e=>c.push(e.ssrc)));const u=o?o.ssrc:null,d=await this.connectionsManager.modifyPublishOfferSdp(gO.STREAM_TYPE_MAIN,this.userInfo.userId,s,a,c,u);return this.logger.info(CN,"generateNewOfferSdp successfully"),d}catch(jN){throw this.logger.error(CN,"generateNewOfferSdp, occur error: ".concat(jN)),jN}}async sendPublishReq(e){try{const t=[];e.forEach((e=>{t.push(e.upstream),this.logger.info(CN,"prepare to send publish req, streamId:".concat(e.upstream.streamUid))})),await this.signal.publish(t),this.logger.info(CN,"sendPublishReq successfully")}catch(jN){throw this.logger.error(CN,"sendPublishReq, occur error: ".concat(jN)),jN}}async addVideoTracksWhenPublish(e,t){if(0===t.length)return[];try{const r=[];for(const i of t){const t=e.getVideoTrack(i.resolutionId),n=i.ssrc,o=await this.connectionsManager.addTrack(gO.STREAM_TYPE_MAIN,t,e.getMediaStream(),n);r.push({ssrc:n,sender:o,streamId:i.upstream.streamUid.toString(),resolutionId:i.resolutionId}),this.logger.info(CN,"addVideoTracksWhenPublish, add video track of resolutionId:".concat(i.resolutionId,",")+"physical track id:".concat(t.id,", streamId: ").concat(i.upstream.streamUid," with ssrc: ").concat(n," to connection successfully"))}return r}catch(jN){throw this.logger.error(CN,"addVideoTracksWhenPublish, occur error: ".concat(jN)),jN}}async addAudioTrackWhenPublish(e,t){if(0===t.length)return null;try{const r=e.getPublishAudioTrack(),i=t[0].ssrc,n={ssrc:i,sender:await this.connectionsManager.addTrack(gO.STREAM_TYPE_MAIN,r,e.getMediaStream()),streamId:t[0].upstream.streamUid.toString(),resolutionId:null};return this.logger.info(CN,"addAudioTrackWhenPublish, add audio track for streamId: ".concat(t[0].upstream.streamUid,",")+"physical track id:".concat(null==r?void 0:r.id," to connection successfully")),n}catch(jN){throw this.logger.error(CN,"addAudioTrackWhenPublish, occur error: ".concat(jN)),jN}}removeTracksWhenPublish(e){if(0===e.length)return[];try{const t=[];return e.forEach((e=>{this.connectionsManager.removeTrack(gO.STREAM_TYPE_MAIN,e.sender),t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId}),this.logger.info(CN,"removeTracksWhenPublish, remove ".concat(e.type," track for streamId: ").concat(e.upstream.streamUid," to connection successfully"))})),t}catch(jN){throw this.logger.error(CN,"removeTracksWhenPublish, occur error: ".concat(jN)),jN}}getKeepAudioTrackSsrcSender(e){const t=[];return e.forEach((e=>{t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId})})),t.length>0?t[0]:null}getKeepVideoTracksSsrcSender(e){const t=[];return e.forEach((e=>{t.push({ssrc:e.ssrc,sender:e.sender,streamId:e.upstream.streamUid.toString(),resolutionId:e.resolutionId})})),t}buildSendMediaStreamInfo(e,t){switch(e){case TC.Aux:{const e=this.streamPublishManager.generateAuxOptTag();e&&this.stat.reportStartSendMediaStream(WC.AUX,e);break}case TC.Video:{const e=this.streamPublishManager.generateMainVideoOptTags();e&&e.length>0&&e.forEach((e=>{t.find((t=>-1!=e.indexOf("".concat(t))))&&this.stat.reportStartSendMediaStream(WC.VIDEO,e)}));break}case TC.Audio:{const e=this.streamPublishManager.generateMainAudioOptTag();e&&this.stat.reportStartSendMediaStream(WC.AUDIO,e);break}}}async unpublish(e){try{return await this.unpublishImpl(e),e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_STOP,KC.RESULT_SUCCESS),void this.stopStreamResolutionDetection(e)}catch(Aw){throw e.isAuxiliary()&&this.stat.reportAuxiliaryStreamShareInfo(HC.ACTION_STOP,KC.RESULT_ERROR),Aw}}async unpublishImpl(e){if(this.userInfo.role===nM)throw this.logger.error(CN,"the player role can not unpublish stream"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"the player role can not unpublish stream");if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if("local"!==e.getType())throw this.logger.error(CN,"stream type: ".concat(e.getType()," cannot unpublish")),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"stream type: ".concat(e.getType()," cannot unpublish"));try{await this.locker.lock("".concat(CN,":unpublishImpl")),await this.unPublishStream(e)}finally{this.locker.unlock("".concat(CN,":unpublishImpl"))}}async unPublishStream(e){await this.unpublishSteamAndSignalIfNeed(e,this.sendPublishRequest.bind(this))}async unpublishSteamAndSignalIfNeed(e,t){const r=e.isAuxiliary(),i=r?"aux":"main";try{this.logger.info(CN,"unpublish ".concat(i," stream:").concat(e.getId()));const n=e,o=this.streamPublishManager.generatePubInfoWhenUnPublish(n);t&&await t(o.allTracks2Publish),await this.startStreamResolutionDetection(n),await this.updateStreamTracks(n,o),n.removeClient(this),r?this.streamPublishManager.unPublishAuxStreamOK():this.streamPublishManager.unPublishMainStreamOK(),this.logger.info(CN,"unpublish ".concat(i,"stream success: ").concat(e.getId()))}catch(jN){throw this.logger.error(CN,"unpublish ".concat(i," stream, ").concat(e.getId()," occur error: ").concat(jN)),jN}}async rejoinPublishStreams(e){let t=[];for(const r of e){this.logger.info(CN,"rejoin publish ".concat(r.isAuxiliary()?"aux":"main"," stream"));const e=r;e.removeClient(this),this.validatePublishRequest(r);const i=this.streamPublishManager.generatePubInfoWhenPublish(e);await this.updateStreamTracks(e,i),e.addClient(this),t=[...t,...i.allTracks2Publish]}t=[...new Set(t)],await this.sendPublishRequest(t);for(const r of e){const e=r;await this.startStreamResolutionDetection(e)}}addLocalAuxStreamEndedHandler(e){this.streamPublishManager.isAuxVideoTrackValid(e)&&this.unpublish(this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_AUX))}async subscribeAudio(e){return await this.subscribeAudioImpl(e)}async subscribeAudioImpl(e){if(!e)throw this.logger.error(CN,"subscribeAudioImpl, userId is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userId is null");const t=new rM({type:"main",log:this.logger,userId:e,client:this,roomId:this.roomId});this.logger.info(CN,"subscribeAudioImpl begin, userId:".concat(e)),await this.subscribeImpl(t,{audio:!0,video:!1});const r=this.remoteUserManager.getUserInfoById(e,this.roomId);if(r){let e=!1;for(const t of null===(i=r.mainStream.remoteTrackInfos)||void 0===i?void 0:i.values()){var i;if(t.type===mO.TRACK_TYPE_AUDIO&&t.isSubscribed){e=!0;break}}if(e)return r.mainStream.remoteStream}}async unSubscribeAudio(e){return await this.unSubscribeAudioImpl(e)}async unSubscribeAudioImpl(e){if(!e)throw this.logger.error(CN,"unSubscribeAudioImpl, userId is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"userId is null");const t=new rM({type:"main",log:this.logger,userId:e,client:this,roomId:this.roomId});this.logger.info(CN,"unSubscribeAudioImpl begin, userId:".concat(e)),await this.unsubscribeImpl(t,{audio:!0,video:!1})}startupQoSReportPlay(e,t){const r=this.startupQoSMap.get(e);if(r){const e={timestamp:r.start,traceId:r.traceId,spanId:"0.1.1",originIntfName:r.interfaceName,interfaceName:"play",source:"",target:"",resultCode:"",successFlag:"T",duration:t-r.start,async:"N",extendInfo:JSON.stringify({id:r.id,streamIds:r.streamIds})};this.stat.setFirstFrameInfo(e),r.start=t,r.interfaceName="play"}}startupQoSReportCanPlay(e){const t=XR.getCurrentTimestamp(),r=(null==e?void 0:e.id)&&this.startupQoSMap.get(null==e?void 0:e.id);if(r){const e={timestamp:r.start,traceId:r.traceId,spanId:"0.1.1.1",originIntfName:r.interfaceName,interfaceName:"canplay",source:"",target:"",resultCode:"",successFlag:"T",duration:t-r.start,async:"N",extendInfo:JSON.stringify({id:r.id,streamIds:r.streamIds})};this.stat.setFirstFrameInfo(e)}}async subscribe(e,t){return await this.subscribeImpl(e,t)}async subscribeImpl(e,t){if(this.roomStreamStatus.audience===YC.PAUSE&&this.userInfo.role===nM)throw this.logger.error(CN,"subscribeImpl, room stream status is pause"),new qc(Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED,"room stream status is ".concat(this.roomStreamStatus.audience));const r=XR.getCurrentTimestamp(),i={traceId:XR.generateRandomId(32,16),spanId:"0",originIntfName:"",interfaceName:"subscribe",id:e.getUniqueId(),start:r};if(!e)throw this.logger.error(CN,"subscribeImpl, stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");if(t||(t={video:!0,audio:!0}),t.audio||t.video){if(t.video&&![DC.ON,DC.OFF,null,void 0].includes(t.autoAdjustResolution))throw this.logger.error(CN,"the autoAdjustResolution value must be 1 or 2 or empty."),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);await this.doSubscribe(e,t,i)}}async doSubscribe(e,t,r){if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);const i=e.getUserId(),n=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN;this.logger.info(CN,"start subscribe, ".concat(i,", ").concat(n,", option: ").concat(JSON.stringify(t))),this.audioPolicy!==_O.USER_SUBSCRIBE_AUDIOPOLICY&&t.audio&&this.logger.info(CN,"doSubscribe, ".concat(this.audioPolicy," is not common audio mode, but audio option is true, reserve it"));try{await this.locker.lock("".concat(CN,":doSubscribe"));const e=this.remoteUserManager.subscribeStream(i,this.roomId,n,t,this.audioPolicy,!1,r);return await this.updateSubscribe(e,r)}catch(jN){throw this.logger.error(CN,"subscribe release lock, subscribe userId ".concat(e.getUserId()," occur error ").concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doSubscribe"))}}async batchSubscribe(e){return await this.doBatchSubscribe(e)}checkSubscribeParams(e){e.forEach((e=>{if(![DC.OFF,DC.ON,null,void 0].includes(e.autoAdjustResolution))throw this.logger.error(CN,"the autoAdjustResolution value must be 1 or 2"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(!["FHD","HD","SD","LD",null,void 0].includes(e.minResolution))throw this.logger.error(CN,"the minResolution value must be 'FHD','HD','SD','LD'"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER)}))}async doBatchSubscribe(e){this.logger.info(CN,"doBatchSubscribe, subscribeInfos: ".concat(JSON.stringify(e)));try{this.checkSubscribeParams(e);const t=e.map((e=>({userId:e.userId,resolutionIds:e.resolutionIds,autoAdjustResolution:e.autoAdjustResolution,minResolution:e.minResolution})));await this.locker.lock("".concat(CN,":doBatchSubscribe"));const r=this.remoteUserManager.batchSubscribeMainStream(this.roomId,t);await this.updateSubscribe(r)}catch(jN){throw this.logger.error(CN,"batchSubscribe failed, ".concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doBatchSubscribe"))}}async batchDeleteUnusedSsrcInSdp(e,t,r){(t&&0!==t.length||r&&0!==r.length)&&(this.logger.info(CN,"batchDeleteUnusedSsrcInSdp, streamType: ".concat(e,", videoSsrc2Del: ").concat(t,", audioSsrc2Del:").concat(r)),await this.connectionsManager.deleteUser(e,t,r))}async enableStreamStateDetection(e,t){if(this.status!==OC.Joined)throw this.logger.error(CN,"cannot enable stream detection before join room"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot enable stream detection before join room");if(!e)return clearTimeout(this.streamInterruptedDetectInterval),this.streamInterruptedDetectInterval=null,this.lastCycleFrameDecodedMap.clear(),void this.streamInterruptedUsersMap.clear();if(!Number.isInteger(t)||t<1||t>60)throw this.logger.error(CN,"invalid interval for enable stream detection"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(e&&this.streamInterruptedDetectInterval)throw this.logger.error(CN,"cannot double enable stream detection"),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"cannot double enable stream detection");if(this.streamDetectionCriterion=t,this.lastCycleFrameDecodedMap&&0===this.lastCycleFrameDecodedMap.size){this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,null).forEach((e=>{const t=e.userId;e.mainStream&&this.lastCycleFrameDecodedMap.set(t+",0",{userId:t,decodedFrame:0}),e.auxStream&&this.lastCycleFrameDecodedMap.set(t+",1",{userId:t,decodedFrame:0})}))}await this.startStreamDetection()}async startStreamDetection(){if(!this.streamInterruptedDetectInterval){const e=1e3,t=()=>{this.streamInterruptedDetectInterval=setTimeout((async()=>{const r=await this.stat.collectReceiverDecodedFrameMap(),i=[],n=[],o=Math.round(1e3*this.streamDetectionCriterion/e);this.streamInterruptedUsersMap.forEach(((e,t)=>{r.has(t)||this.streamInterruptedUsersMap.delete(t)})),r.forEach(((e,t)=>{const r=this.lastCycleFrameDecodedMap&&this.lastCycleFrameDecodedMap.get(t);if(r&&r.decodedFrame===e.decodedFrame){const e=this.streamInterruptedUsersMap.get(t);e?this.streamInterruptedUsersMap.set(t,e+1):this.streamInterruptedUsersMap.set(t,1)}if(r&&r.decodedFrame!==e.decodedFrame){if(this.streamInterruptedUsersMap.get(t)>=o){const r=t.split(",");r[0]!==wC&&n.push({userId:r[0],isScreen:e.isAux})}this.streamInterruptedUsersMap.delete(t)}})),this.lastCycleFrameDecodedMap=r,this.streamInterruptedUsersMap&&this.streamInterruptedUsersMap.forEach(((e,t)=>{if(e===o){const e=t.split(",");e[0]!==wC&&(i.push({userId:e[0],isScreen:"1"===e[1]}),this.logger.info(CN,"stream interrupted, userId: ".concat(e[0],", isAux: ").concat(e[1])))}})),i.length>0&&this.connectState.curState===vC[yC.CONNECTED]&&(this.logger.info(CN,"find stream interrupted users, ".concat(JSON.stringify(i))),this.eventEmitter.emit(UC.StreamInterrupted,i)),n.length>0&&this.connectState.curState===vC[yC.CONNECTED]&&(this.logger.info(CN,"find stream recovered users, ".concat(JSON.stringify(n))),this.eventEmitter.emit(UC.StreamRecovered,n)),t()}),e)};t()}}async unsubscribe(e,t){return await this.unsubscribeImpl(e,t)}async unsubscribeImpl(e,t){if(this.logger.info(CN,"start unsubscribe"),this.roomStreamStatus.audience===YC.PAUSE&&this.userInfo.role===nM)throw this.logger.error(CN,"unsubscribeImpl, room stream status is pause"),new qc(Gc.RTC_ERR_CODE_ROOM_STREAM_STATUS_PAUSED,"room stream status is ".concat(this.roomStreamStatus.audience));if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);if(!e)throw this.logger.error(CN,"stream is null"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"stream is null");const r=e.getUserId(),i=e.isAuxiliary()?gO.STREAM_TYPE_AUX:gO.STREAM_TYPE_MAIN;this.logger.info(CN,"start doUnsubscribe, ".concat(r,", ").concat(i,", option: ").concat(JSON.stringify(t)));try{const e=t||{video:!0,audio:!0};await this.locker.lock("".concat(CN,":doUnsubscribe"));const n=this.remoteUserManager.unsubscribeStream(r,this.roomId,i,e);await this.updateSubscribe(n)}catch(jN){throw this.logger.error(CN,"subscribe userId ".concat(e.getUserId()," occur error ").concat(jN)),jN}finally{this.locker.unlock("".concat(CN,":doUnsubscribe"))}}async switchRole(e,t){return await this.switchRoleImpl(e,t)}async switchRoleImpl(e,t){if(this.logger.info(CN,"switchRole from ".concat(this.userInfo.role," to ").concat(e)),this.status!==OC.Joined&&this.status!==OC.Rejoining)throw new qc(Gc.RTC_ERR_CODE_STATUS_ERROR);if(this.userInfo.role===e)throw this.logger.error(CN,"new role same with old role, no need switch."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"new role same with old role, no need switch.");ED.switchRoleParamsCheck(this,e,t);try{if(await this.locker.lock("".concat(CN,":_switchRoleImpl")),this.userInfo.role===iM&&e===nM&&(this.streamPublishManager.isMainStreamPublished()&&await this.unpublishSteamAndSignalIfNeed(this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN)),this.streamPublishManager.isAuxVideoTrackPublished()&&await this.unpublishSteamAndSignalIfNeed(this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_AUX))),!(t&&t.ctime&&t.signature))throw this.logger.error(CN,"authorization is incomplete, please have the correct authorization parameter"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"switchRole authorization parameter is invalid.");{const e=uM.renewSignature(this.identifiedID_,t.ctime,t.signature);this.signal.refreshUserInfo(e)}const r=await this.signal.switchRole(e,t);this.logger.debug(CN,"swithRole resp: ".concat(JSON.stringify(r))),this.userInfo.role===nM&&e===iM&&(this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos()),this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo())),this.userInfo.role=e,e===iM&&this.roomStreamStatus.audience===YC.PAUSE&&await this.handleRoomStreamStatus(YC.NORMAL,_O.TOPN_AUDIOPOLICY===this.audioPolicy,!0),this.stat.reportSwitchRoleInfo(e,JC),this.locker.unlock("".concat(CN,":_switchRoleImpl")),this.logger.info(CN,"switchRole success")}catch(jN){throw this.locker.unlock("".concat(CN,":_switchRoleImpl")),this.logger.error(CN,"switchRole switchRole failed, errMsg = ".concat(jN)),this.stat.reportSwitchRoleInfo(e,qC),jN}}getPublishAudioSender(){var e;return null===(e=this.streamPublishManager.getPublishedMainAudioTrackInfo())||void 0===e?void 0:e.sender}getPublishedMainAudioTrackInfo(){return this.streamPublishManager.getPublishedMainAudioTrackInfo()}getPublishedMainVideoTrackInfos(){return this.streamPublishManager.getPublishedMainVideoTrackInfos()}getPublishVideoSender(e){if(e===gO.STREAM_TYPE_AUX){const e=this.streamPublishManager.getPublishedAuxVideoTrackInfo();if(e)return[e.sender]}const t=[];return this.streamPublishManager.getPublishedMainVideoTrackInfos().forEach((e=>{t.push(e.sender)})),t}getMainStreamSenderByTrack(e){if(!e)return null;const t=this.streamPublishManager.getPublishedMainVideoTrackInfos().find((t=>t.upstream.streamUid.toString()===e));return null==t?void 0:t.sender}async waitForTrackBatch(e){const t=e.map((e=>{var t,r;return(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0?1:0})).reduce(((e,t)=>e+t),0),r=e.map((e=>{var t,r;return(null===(t=e.auxStream)||void 0===t||null===(r=t.tracks)||void 0===r?void 0:r.length)>0?1:0})).reduce(((e,t)=>e+t),0);this.logger.debug(CN,"wait for track batch begin, mainStreamCount:".concat(t,", auxStreamCount:").concat(r," "));for(let i=0;i<100;i++){if(this.computeSucceedStreamCount(gO.STREAM_TYPE_MAIN,t,e)+this.computeSucceedStreamCount(gO.STREAM_TYPE_AUX,r,e)===t+r)break;if(99===i)return void this.logger.error(CN,"waitForTrackBatch subscribe on track timeout");await XR.sleep(50)}}computeSucceedStreamCount(e,t,r){let i=0;return t&&(i=r.map((t=>this.isStreamTrackReady(e,t)?1:0)).reduce(((e,t)=>e+t),0)),i}newSignal(e){this.signal||(this.signal=new PM(this.clientConfig.appId,e,this))}async negTransportChannelHandler(e,t,r,i){if(this.cmdMsgAbility.enable)if(e.sdp.cmd){var n;if(i)return super.off(UC.CmdChannelDisconnect),iE.getLogger().debug(CN,"negTransportChannelHandler init command channel of datachannel."),this.cmdMsgAbility.cmdManager=new BD(this.eventEmitter,this.remoteUserManager),null===(n=this.cmdMsgAbility.cmdManager)||void 0===n||n.setCommandChannelParams(this.roomId,{tranportOptions:{userUid:e.userUid,sendSsrc:e.sdp.cmd.sendSsrc,receiveSsrc:e.sdp.cmd.receiveSsrc,payload:e.sdp.cmd.pt},dataChannelOptions:{connection:this.connectionsManager.getConnection(gO.STREAM_TYPE_MAIN)},msgFormat:this.cmdMsgAbility.msgFormat}),await this.connectionsManager.refreshOffer(gO.STREAM_TYPE_MAIN),void(t&&r&&super.on(UC.CmdChannelDisconnect,(i=>{i===BC.DATA_CHANNEL&&(iE.getLogger().debug(CN,"negTransportChannelHandler downgrade to webocket command channel."),this.websocketChannelInit(e,t,r))}),!1));t&&r&&(iE.getLogger().debug(CN,"negTransportChannelHandler init webocket command channel."),this.websocketChannelInit(e,t,r))}else iE.getLogger().error(CN,"negTransportChannelHandler error, cmd signal info missing.")}websocketChannelInit(e,t,r){var i;null===(i=this.cmdMsgAbility.cmdManager)||void 0===i||i.reset(),this.cmdMsgAbility.cmdManager=new UD(this.eventEmitter,this.remoteUserManager),this.cmdMsgAbility.cmdManager.setCommandChannelParams(this.roomId,{tranportOptions:{userUid:e.userUid,sendSsrc:e.sdp.cmd.sendSsrc,receiveSsrc:e.sdp.cmd.receiveSsrc,payload:e.sdp.cmd.pt},wsOptions:{bindCryptoKey:t,wsUrl:r,wsDomain:e.sdp.domain},msgFormat:this.cmdMsgAbility.msgFormat})}onTrackHandler(e,t){if(this.logger.info(CN,"peerconnection ontrack event: ".concat(e.track.kind)),e.track.kind===mO.TRACK_TYPE_VIDEO||this.audioPolicy===_O.USER_SUBSCRIBE_AUDIOPOLICY&&e.track.kind===mO.TRACK_TYPE_AUDIO){var r,i;const n=e.streams[0].id,o=this.remoteUserManager.getUserInfoByStreamId(this.roomId,n),s=t?null==o||null===(r=o.auxStream)||void 0===r?void 0:r.remoteStream:null==o||null===(i=o.mainStream)||void 0===i?void 0:i.remoteStream;s?(this.logger.info(CN,"connection.ontrack streamId=".concat(n,", hasAudio:").concat(s.hasAudioTrack()," hasVideo:").concat(s.hasVideoTrack())),s.addRemoteTrack(e.track,n)):this.logger.info(CN,"ontrack stream: ".concat(n," is not existed"))}this.logger.info("onConnection","audio policy:".concat(this.audioPolicy,",track kind:").concat(e.track.kind)),this.audioPolicy===_O.TOPN_AUDIOPOLICY&&e.track.kind===mO.TRACK_TYPE_AUDIO&&this.saveAudioStream4TopN(e)}static isStreamAdd(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return 0===r.preTracks.length&&r.curTracks.length>0}static isStreamRemove(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return r.preTracks.length>0&&0===r.curTracks.length}static isStreamUpdate(e,t){if(!t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const r=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return r.addedTracks.length>0||r.updatedTracks.length>0||r.removedTracks.length>0}static getMuteChangeStatus(t,r,i){if(!i)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);const n=t===gO.STREAM_TYPE_MAIN?i.mainStream:i.auxStream;return e.getMediaMuteChangeFlag(n,r)}static getMediaMuteChangeFlag(t,r){const i="noTrack",n=t.preTracks.find((e=>e.type===r)),o=t.curTracks.find((e=>e.type===r)),s=n?n.mute:i,a=o?o.mute:i;return e.getMuteChangeFlag(s,a)}static getMuteChangeFlag(e,t){return e!==t?t?EN.mute:EN.unmute:EN.noChange}async updateSubscribe(t,r,i){if(this.connectState.curState!==vC[yC.CONNECTED])throw this.logger.error(CN,"cannot do subscribe or unSubscribe when network disconnected"),new qc(Gc.RTC_ERR_CODE_WEBSOCKET_NOT_CONNECTED);if(!t||0===t.length)return null;if(!e.isSubscriptionChange(t))return this.logger.info(CN,"no need update subscription"),null;try{const e={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};await this.modifyBrowerSdp(t,e);const n={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};!i&&await this.subscribeSignal(t,n,r),this.clearResource(t);const o=await this.handleRemoteStreamsState(n.successSubscribeInfos),s={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};return(null==o?void 0:o.successSubscribeInfos)&&s.successSubscribeInfos.push(...o.successSubscribeInfos),(null==o?void 0:o.failSubscribeInfos)&&s.failSubscribeInfos.push(...o.failSubscribeInfos),(null==n?void 0:n.failSubscribeInfos)&&s.failSubscribeInfos.push(...n.failSubscribeInfos),(null==n?void 0:n.successUnsubscribeInfos)&&s.successUnsubscribeInfos.push(...n.successUnsubscribeInfos),(null==n?void 0:n.failUnsubscribeInfos)&&s.failUnsubscribeInfos.push(...n.failUnsubscribeInfos),await this.rollbackResource(s.failSubscribeInfos),this.remoteUserManager.subscribeResultCallback(s,!1),this.logger.info(CN,"updateSubscribe end. ".concat(this.getSubscribeResultString(s))),s}catch(jN){this.logger.error(CN,"updateSubscribe fail. errMsg:".concat(jN));const r=this.getSubscribeExceptionResult(t);throw await this.rollbackResource(r.failSubscribeInfos),this.remoteUserManager.subscribeResultCallback(r,!0),this.logger.info(CN,"updateSubscribe fail end. ".concat(this.getSubscribeResultString(r))),jN}}modifyBrowerSdp(t,r){const i=this.buildSubsReq(t,r),n=e.getUserUpdateInfos(i.joinUserUpdateInfos),o=this.buildDefaultSubsRep(i);this.getSubscribeResult(n,o.videoUpstreams,o.audioUpstreams,r,!1);const s=[],a=[],c=[],u=[];r.successUnsubscribeInfos.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{e.type===mO.TRACK_TYPE_VIDEO?s.push(e.cssrc):c.push(e.cssrc)})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{e.type===mO.TRACK_TYPE_VIDEO?a.push(e.cssrc):u.push(e.cssrc)}))}));const d=[];return d.push(this.generateReceiveSdp(gO.STREAM_TYPE_MAIN,r.successSubscribeInfos,s,c)),d.push(this.generateReceiveSdp(gO.STREAM_TYPE_AUX,r.successSubscribeInfos,a,u)),Promise.all(d)}getSubscribeExceptionResult(e){const t={successSubscribeInfos:[],failSubscribeInfos:[],successUnsubscribeInfos:[],failUnsubscribeInfos:[]};return e.forEach((e=>{var r,i,n,o,s,a,c,u;const d={userId:e.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(r=e.mainStream)||void 0===r?void 0:r.remoteStream,tracks:null===(i=e.mainStream)||void 0===i?void 0:i.tracks4Subscribe},auxStream:{remoteStream:null===(n=e.auxStream)||void 0===n?void 0:n.remoteStream,tracks:null===(o=e.auxStream)||void 0===o?void 0:o.tracks4Subscribe}},l={userId:e.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(s=e.mainStream)||void 0===s?void 0:s.remoteStream,tracks:null===(a=e.mainStream)||void 0===a?void 0:a.tracks4Unsubscribe},auxStream:{remoteStream:null===(c=e.auxStream)||void 0===c?void 0:c.remoteStream,tracks:null===(u=e.auxStream)||void 0===u?void 0:u.tracks4Unsubscribe}};this.appendSubscribeResult(t.failSubscribeInfos,d),this.appendSubscribeResult(t.failUnsubscribeInfos,l)})),this.logger.info(CN,"getSubscribeExceptionResult. ".concat(this.getSubscribeResultString(t))),t}getSubscribeResultString(e){var t,r,i,n;let o;return null==e||null===(t=e.successSubscribeInfos)||void 0===t||t.forEach((e=>{o="".concat(o||""," subscribe success list: ").concat(this.getRemoteUserSubscribeInfoString(e),", ")})),null==e||null===(r=e.failSubscribeInfos)||void 0===r||r.forEach((e=>{o="".concat(o||""," subscribe failed list: ").concat(this.getRemoteUserSubscribeInfoString(e),",")})),null==e||null===(i=e.successUnsubscribeInfos)||void 0===i||i.forEach((e=>{o="".concat(o||""," unsubscribe success list: ").concat(this.getRemoteUserSubscribeInfoString(e),",")})),null==e||null===(n=e.failUnsubscribeInfos)||void 0===n||n.forEach((e=>{o="".concat(o||""," unsubscribe failed list: ").concat(this.getRemoteUserSubscribeInfoString(e))})),o}async rollbackResource(e){if(e&&0!==e.length)try{const t=[],r=[],i=[],n=[];e.forEach((e=>{var o,s,a,c;null===(o=e.mainStream)||void 0===o||null===(s=o.tracks)||void 0===s||s.forEach((e=>{e.type===mO.TRACK_TYPE_VIDEO?t.push(e.cssrc):r.push(e.cssrc)})),null===(a=e.auxStream)||void 0===a||null===(c=a.tracks)||void 0===c||c.forEach((e=>{e.type===mO.TRACK_TYPE_VIDEO?i.push(e.cssrc):n.push(e.cssrc)}))})),await this.batchDeleteUnusedSsrcInSdp(gO.STREAM_TYPE_MAIN,t,r),await this.batchDeleteUnusedSsrcInSdp(gO.STREAM_TYPE_AUX,i,n)}catch(jN){this.logger.error(CN,"rollbackResource fail, errMsg:".concat(jN))}}isNormalStateStream(e){const t=e.tracks.filter((e=>e.isTrackReady)),r=e.tracks.filter((e=>e.isTrackReady&&e.state===TO.normal));return t.length&&t.length===r.length}async handleReadyStream(e,t){var r,i,n,o;e===gO.STREAM_TYPE_MAIN&&(null===(r=t.mainStream)||void 0===r||null===(i=r.tracks)||void 0===i?void 0:i.length)>0?await this.handleReadyStreamByType(t.userId,e,t.mainStream):e===gO.STREAM_TYPE_AUX&&(null===(n=t.auxStream)||void 0===n||null===(o=n.tracks)||void 0===o?void 0:o.length)>0&&await this.handleReadyStreamByType(t.userId,e,t.auxStream)}async handleReadyStreamByType(e,t,r){this.logger.debug(CN,"handleReadyStreamByType, ".concat(t,", ").concat(JSON.stringify(r.tracks)));try{if(this.isNormalStateStream(r)&&(this.logger.info(CN,"emit ".concat(UC.StreamSubscribed,", userId: ").concat(e,", ").concat(t)),this.eventEmitter.emit(UC.StreamSubscribed,{stream:r.remoteStream}),t===gO.STREAM_TYPE_MAIN)){const t=setTimeout((async()=>{clearTimeout(t),this.reportMediaStatus(e,this.roomId)}),0)}const i=r.tracks.some((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.isTrackReady));for(const e of r.tracks)e.isTrackReady&&await this.handleReadyTrack(e,r.remoteStream,i)}catch(jN){this.logger.error(CN,"handleReadyStreamByType fail, errMsg:".concat(jN))}}getMediaNotifyInfo(e,t){const r=[],i=this.remoteUserManager.getAllUserStreamsByType(t,null,null);return null==i||i.forEach((i=>{if(i.userId!==e)return;const n=i.mainStream,o=null==n?void 0:n.tracks.find((e=>e.type===mO.TRACK_TYPE_AUDIO&&e.isTrackReady));if(o){const i={mediaType:mO.TRACK_TYPE_AUDIO,roomId:t,userId:e,status:o.mute?IC.MediaStatusUnavailable:IC.MediaStatusAvailable,reason:o.mute?RC.MediaUnmuted:RC.MediaMuted};r.push(i)}const s=null==n?void 0:n.tracks.find((e=>e.type===mO.TRACK_TYPE_VIDEO&&e.isTrackReady));if(s){const t={mediaType:mO.TRACK_TYPE_VIDEO,roomId:this.roomId,userId:e,status:s.mute?IC.MediaStatusUnavailable:IC.MediaStatusAvailable,reason:s.mute?RC.MediaUnmuted:RC.MediaMuted};r.push(t)}})),r}reportMediaStatus(e,t){this.getMediaNotifyInfo(e,t).forEach((t=>{const r=t.mediaType===mO.TRACK_TYPE_AUDIO?t.status===IC.MediaStatusAvailable?"UnmuteAudio":"MuteAudio":t.status===IC.MediaStatusAvailable?"UnmuteVideo":"MuteVideo";this.logger.info(CN,"emit ".concat(UC[r],", userId: ").concat(e,", type: ").concat(t.mediaType,", status: ").concat(t.status)),this.eventEmitter.emit(UC[r],t)}))}async handleReadyTrack(e,t,r){const i=e.type===mO.TRACK_TYPE_VIDEO||e.type===mO.TRACK_TYPE_AUDIO&&!r,n=[TO.remoteRejoinCache,TO.localRejoin,TO.resolutionChange].includes(e.state);i&&e.playElement&&n&&(this.logger.info(CN,"handleReadyTrack, auto play"),this.logger.info(CN,"video track.muted[".concat(e.muted,"]")),await t.play(e.playElement,{objectFit:e.objectFit,muted:e.muted,resolutionId:e.type===mO.TRACK_TYPE_VIDEO?e.trackId:null}));const o=e.type===mO.TRACK_TYPE_AUDIO,s=[TO.remoteRejoinCache,TO.localRejoin,TO.resolutionChange].includes(e.state);if(o&&e.playElement&&s){this.logger.info(CN,"audio track.muted[".concat(e.muted,"]"));const r=t.getAudioHRTCTrack();e.muted?r.muteTrack():r.unmuteTrack()}}async handleRemoteStreamsState(t){if(!t||0===t.length)return null;await this.waitForTrackBatch(t),this.logger.info(CN,"handleRemoteTracksState, waitForTrackBatch return");const r=[],i=[];for(const c of t){var n,o,s,a;const t=e.newRemoteUserSubscribeInfo(c.userId,this.roomId,null===(n=c.mainStream)||void 0===n?void 0:n.remoteStream,null===(o=c.auxStream)||void 0===o?void 0:o.remoteStream),u=e.newRemoteUserSubscribeInfo(c.userId,this.roomId,null===(s=c.mainStream)||void 0===s?void 0:s.remoteStream,null===(a=c.auxStream)||void 0===a?void 0:a.remoteStream);await this.handleRemoteStreamsStateByType(c,gO.STREAM_TYPE_MAIN,t,u),await this.handleRemoteStreamsStateByType(c,gO.STREAM_TYPE_AUX,t,u),(t.mainStream.tracks.length||t.auxStream.tracks.length)&&r.push(t),(u.mainStream.tracks.length||u.auxStream.tracks.length)&&i.push(u),this.stat.getMediaStat().setSubscribeInfo(c)}return{successSubscribeInfos:r,failSubscribeInfos:i,successUnsubscribeInfos:null,failUnsubscribeInfos:null}}isStreamTrackReady(e,t){const r=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream,i=null==r?void 0:r.remoteStream,n=null!=r&&r.tracks?Array.from(r.tracks.values()):null,o=null==n?void 0:n.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).map((e=>e.trackId)),s=null==n?void 0:n.some((e=>e.type===mO.TRACK_TYPE_AUDIO));return null==i?void 0:i.isTracksReady(o,s)}async handleRemoteStreamsStateByType(e,t,r,i){var n;const o=this.isStreamTrackReady(t,e);let s=e.mainStream,a=null===(n=e.mainStream)||void 0===n?void 0:n.tracks,c=r.mainStream,u=i.mainStream;var d;t===gO.STREAM_TYPE_AUX&&(s=e.auxStream,a=null===(d=e.auxStream)||void 0===d?void 0:d.tracks,c=r.auxStream,u=i.auxStream);let l=!1;var h,f;o?(null===(h=a)||void 0===h||h.forEach((e=>{e.isTrackReady=!0,l=!0})),a&&c.tracks.push(...a)):null===(f=a)||void 0===f||f.forEach((e=>{var t;null!==(t=s)&&void 0!==t&&t.remoteStream.isTrackReady(e.type,e.trackId)?(e.isTrackReady=!0,l=!0,c.tracks.push(e)):u.tracks.push(e)}));l&&await this.handleReadyStream(t,e)}getRemoteUserSubscribeInfoString(e){var t,r,i,n;if(!e)return"";let o,s;return null===(t=e.mainStream)||void 0===t||null===(r=t.tracks)||void 0===r||r.forEach((e=>{o="".concat(o||""," ").concat(JSON.stringify(e))})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks)||void 0===n||n.forEach((e=>{s="".concat(s||""," ").concat(JSON.stringify(e))}))," userId:".concat(e.userId,", mainTracks:").concat(o,", auxTracks:").concat(s," ")}releaseTrack(e,t){t.type===mO.TRACK_TYPE_VIDEO?(e.stop({audio:!1,video:!0,resolutionIds:[t.trackId]}),e.removeRemoteVideoTrack(t.trackId),this.logger.info(CN,"releaseTrack ".concat(t.type))):(e.stop({audio:!0}),e.removeRemoteAudioTrack(),this.logger.info(CN,"releaseTrack ".concat(t.type)))}clearResource(e){try{null==e||e.forEach((e=>{var t,r,i,n;null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Unsubscribe)||void 0===r||r.forEach((t=>{this.stat.getMediaStat().deleteSubscribeInfo(e.userInfo.userId,gO.STREAM_TYPE_MAIN,t.trackId),this.releaseTrack(e.mainStream.remoteStream,t)})),null===(i=e.auxStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n||n.forEach((t=>{this.stat.getMediaStat().deleteSubscribeInfo(e.userInfo.userId,gO.STREAM_TYPE_AUX,t.trackId),this.releaseTrack(e.auxStream.remoteStream,t)}))}))}catch(jN){this.logger.error(CN,"clearResource error: ".concat(jN))}}async generateReceiveSdp(e,t,r,i){this.logger.info(CN,"generateReceiveSdp, stream type: ".concat(e,", removeVideoSsrcs: ").concat(r,", removeAudioSsrcs: ").concat(i));const n=t.some((t=>{var r;const i=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream;return(null==i||null===(r=i.tracks)||void 0===r?void 0:r.length)>0})),o=!!r.length||!!i.length;if(!n&&!o)return null;o&&await this.connectionsManager.deleteUser(e,r,i);const s=new Map;for(const u of t){var a,c;const t=e===gO.STREAM_TYPE_MAIN?null===(a=u.mainStream)||void 0===a?void 0:a.tracks:null===(c=u.auxStream)||void 0===c?void 0:c.tracks;if(t&&!(t.length<1))for(const r of t){this.logger.info(CN,"generateReceiveSdp, userId : ".concat(u.userId,", stream type: ").concat(e,", track type: ").concat(r.type,", ssrc: ").concat(r.cssrc));const t={streamId:r.trackId};r.type===mO.TRACK_TYPE_VIDEO?t.videoSsrc=r.cssrc:t.audioSsrc=r.cssrc,s.has(u.userId)?s.get(u.userId).push(t):s.set(u.userId,[t])}}await this.connectionsManager.addUserBatch(e,s)}static getWatchType4Ops(e){return 0===e?"cancel_watch":1===e?"watch":"batch_watch"}static isSubscriptionChange(e){return e.some((e=>{var t,r,i,n,o,s,a,c;return(null===(t=e.mainStream)||void 0===t||null===(r=t.tracks4Subscribe)||void 0===r?void 0:r.length)>0||(null===(i=e.mainStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n?void 0:n.length)>0||(null===(o=e.auxStream)||void 0===o||null===(s=o.tracks4Subscribe)||void 0===s?void 0:s.length)>0||(null===(a=e.auxStream)||void 0===a||null===(c=a.tracks4Unsubscribe)||void 0===c?void 0:c.length)>0}))}appendSubscribeResult(e,t){var r,i,n,o;if(t&&(null!==(r=t.mainStream)&&void 0!==r&&null!==(i=r.tracks)&&void 0!==i&&i.length||null!==(n=t.auxStream)&&void 0!==n&&null!==(o=n.tracks)&&void 0!==o&&o.length)){const r=e.find((e=>e.userId===t.userId&&e.roomId===t.roomId));var s,a;if(r)null!==(s=r.mainStream)&&void 0!==s&&s.tracks?r.mainStream.tracks.push(...t.mainStream.tracks):r.mainStream=t.mainStream,null!==(a=r.auxStream)&&void 0!==a&&a.tracks?r.auxStream.tracks.push(...t.auxStream.tracks):r.auxStream=t.auxStream;else e.push(t)}}buildSubsReq(t,r){const i=[],n=[],o=[];return t.forEach((t=>{if(t.curUserState===IO.NotJoin){var s,a,c,u,d,l;const i=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(s=t.mainStream)||void 0===s?void 0:s.remoteStream,null===(a=t.auxStream)||void 0===a?void 0:a.remoteStream);null===(c=t.mainStream)||void 0===c||null===(u=c.tracks4Unsubscribe)||void 0===u||u.forEach((e=>{i.mainStream.tracks.push(e)})),null===(d=t.auxStream)||void 0===d||null===(l=d.tracks4Unsubscribe)||void 0===l||l.forEach((e=>{i.auxStream.tracks.push(e)})),this.appendSubscribeResult(r.successUnsubscribeInfos,i)}else{var h,f,p,m;o.push(t),null===(h=t.mainStream)||void 0===h||null===(f=h.allSubscribeTracks)||void 0===f||f.forEach((r=>{e.getUserTrackSubscribeInfo(t.userInfo,i,n,r)})),null===(p=t.auxStream)||void 0===p||null===(m=p.allSubscribeTracks)||void 0===m||m.forEach((r=>{e.getUserTrackSubscribeInfo(t.userInfo,i,n,r)}))}})),{videoSubscribeInfos:i,audioSubscribeInfos:n,joinUserUpdateInfos:o}}async subscribeSignal(t,r,i){const n=this.buildSubsReq(t,r);if(!e.isSubscriptionChange(n.joinUserUpdateInfos))return;const o=e.getWatchType4Ops(n.videoSubscribeInfos.length);let s;this.logger.info(CN,"subscribeSignal, fullVideoSubscribeInfos: ".concat(JSON.stringify(n.videoSubscribeInfos)," ,")+"fullAudioSubscribeInfos: ".concat(JSON.stringify(n.audioSubscribeInfos)));let a=null;const c=XR.getCurrentTimestamp();if(i){const e={timestamp:i.start,traceId:i.traceId,spanId:"0",originIntfName:"",interfaceName:"subscribe",source:"",target:"",resultCode:"",successFlag:"T",duration:c-i.start,async:"N",extendInfo:JSON.stringify({id:i.id})};this.stat.setFirstFrameInfo(e)}try{a=this.status!==OC.Leaving?await this.signal.subscribe(n.videoSubscribeInfos,n.audioSubscribeInfos,o):this.buildDefaultSubsRep(n)}catch(Aw){throw s=Aw,Aw}finally{if(i){const e=XR.getCurrentTimestamp(),t={timestamp:c,traceId:i.traceId,spanId:"0.1",originIntfName:i.interfaceName,interfaceName:"subscribeSignal",source:"",target:"",resultCode:"",successFlag:s?"F":"T",duration:e-c,async:"N",extendInfo:JSON.stringify({id:i.id,streamIds:i.streamIds})};this.stat.setFirstFrameInfo(t),i.interfaceName="subscribeSignal",i.start=e,this.startupQoSMap.set(i.id,i)}}a.audioUpstreams||a.videoUpstreams||this.logger.error(CN,"subscribeSignal, subscribe stream subscribed no result record, subsResult:".concat(JSON.stringify(a)));const u=e.getUserUpdateInfos(n.joinUserUpdateInfos);this.getSubscribeResult(u,a.videoUpstreams,a.audioUpstreams,r)}buildDefaultSubsRep(e){const t=[];e.videoSubscribeInfos.forEach((e=>{t.push({cSsrcId:e.cSsrcId,code:0,pSsrcId:e.pSsrcId,pStreamUid:e.pStreamUid,pUserId:e.pUserId,pUserUid:e.pUserUid})}));const r=[];return e.audioSubscribeInfos.forEach((e=>{r.push({cSsrcId:e.cSsrcId,code:0,pSsrcId:e.pSsrcId,pStreamUid:e.pStreamUid,pUserId:e.pUserId,pUserUid:e.pUserUid})})),{audioUpstreams:r,videoUpstreams:t}}static getUserTrackSubscribeInfo(e,t,r,i){const n={pSsrcId:i.pssrc,cSsrcId:i.cssrc,pStreamUid:parseInt(i.trackId),pUserId:e.userId,pUserUid:e.userUid};i.type===mO.TRACK_TYPE_AUDIO?r.push(n):(n.mediaData={width:i.width,height:i.height,maxFps:60},i.autoAdjustResolution===DC.ON&&(n.minReceiveContent=bN[i.minResolution]),t.push(n))}static getUserUpdateInfos(e){return e.filter((e=>{var t,r,i,n,o,s,a,c;return(null===(t=e.mainStream)||void 0===t||null===(r=t.allSubscribeTracks)||void 0===r?void 0:r.length)>0||(null===(i=e.mainStream)||void 0===i||null===(n=i.tracks4Unsubscribe)||void 0===n?void 0:n.length)>0||(null===(o=e.auxStream)||void 0===o||null===(s=o.allSubscribeTracks)||void 0===s?void 0:s.length)>0||(null===(a=e.auxStream)||void 0===a||null===(c=a.tracks4Unsubscribe)||void 0===c?void 0:c.length)>0}))}getSubscribeResult(e,t,r,i,n){const o=new Map;null==t||t.forEach((e=>{const t=e.pUserId+"#"+this.roomId,r=o.get(t);if(r)r.tracks.push(e);else{const r={userId:e.pUserId,userUid:e.pStreamUid,tracks:[e]};o.set(t,r)}})),null==r||r.forEach((e=>{const t=e.pUserId+"#"+this.roomId,r=o.get(t);if(r)r.tracks.push(e);else{const r={userId:e.pUserId,userUid:e.pStreamUid,tracks:[e]};o.set(t,r)}})),e.forEach((e=>{this.getStreamSubscribeResult(e,!0,o,i)})),e.forEach((e=>{this.getStreamSubscribeResult(e,!1,o,i)})),this.logger.info(CN,"isRealSubsAction: ".concat(n,", getSubscribeResult success, ").concat(this.getSubscribeResultString(i)))}getStreamSubscribeResult(t,r,i,n){var o,s,a,c;if(!r)return this.handleUnsubscribeReq(gO.STREAM_TYPE_MAIN,t,n),void this.handleUnsubscribeReq(gO.STREAM_TYPE_AUX,t,n);const u=n.successSubscribeInfos,d=n.failSubscribeInfos,l=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(o=t.mainStream)||void 0===o?void 0:o.remoteStream,null===(s=t.auxStream)||void 0===s?void 0:s.remoteStream),h=e.newRemoteUserSubscribeInfo(t.userInfo.userId,this.roomId,null===(a=t.mainStream)||void 0===a?void 0:a.remoteStream,null===(c=t.auxStream)||void 0===c?void 0:c.remoteStream),f=t.userInfo.userId+"#"+this.roomId,p=i.get(f);var m,g,_,S;if(!p&&this.hasTrackSignalReq(t))return d.push({userId:t.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(m=t.mainStream)||void 0===m?void 0:m.remoteStream,tracks:null===(g=t.mainStream)||void 0===g?void 0:g.tracks4Subscribe},auxStream:{remoteStream:null===(_=t.auxStream)||void 0===_?void 0:_.remoteStream,tracks:null===(S=t.auxStream)||void 0===S?void 0:S.tracks4Subscribe}}),void this.logger.error(CN,"subscribe user ".concat(t.userInfo.userId,", isSubscribe: ").concat(r," subscribed failed,mcs not response"));this.getTracksSubscribeResults(r,t,p,l,h),this.appendToSubscribeResult(l,u,h,d)}appendToSubscribeResult(e,t,r,i){var n,o,s,a,c,u,d,l;((null===(n=e.mainStream)||void 0===n||null===(o=n.tracks)||void 0===o?void 0:o.length)>0||(null===(s=e.auxStream)||void 0===s||null===(a=s.tracks)||void 0===a?void 0:a.length)>0)&&this.appendSubscribeResult(t,e),((null===(c=r.mainStream)||void 0===c||null===(u=c.tracks)||void 0===u?void 0:u.length)>0||(null===(d=r.auxStream)||void 0===d||null===(l=d.tracks)||void 0===l?void 0:l.length)>0)&&this.appendSubscribeResult(i,r)}static newRemoteUserSubscribeInfo(e,t,r,i){return{userId:e,roomId:t,mainStream:{remoteStream:r,tracks:[]},auxStream:{remoteStream:i,tracks:[]}}}handleUnsubscribeReq(e,t,r){const i=e===gO.STREAM_TYPE_MAIN?t.mainStream:t.auxStream,n=null==i?void 0:i.tracks4Unsubscribe;if(null!=n&&n.length){var o,s,a,c,u;const d=null===(o=i.tracks4Subscribe)||void 0===o?void 0:o.some((e=>e.state===TO.remoteRejoinCache)),l=r.successSubscribeInfos.find((e=>e.userId===t.userInfo.userId&&e.roomId===t.userInfo.roomId)),h=e===gO.STREAM_TYPE_MAIN?null==l||null===(s=l.mainStream)||void 0===s?void 0:s.tracks:null==l||null===(a=l.auxStream)||void 0===a?void 0:a.tracks,f=!h||0===(null==h?void 0:h.filter((e=>e.state===TO.remoteRejoinCache)).length),p={userId:t.userInfo.userId,roomId:this.roomId,mainStream:{remoteStream:null===(c=t.mainStream)||void 0===c?void 0:c.remoteStream,tracks:e===gO.STREAM_TYPE_MAIN?n:[]},auxStream:{remoteStream:null===(u=t.auxStream)||void 0===u?void 0:u.remoteStream,tracks:e===gO.STREAM_TYPE_AUX?n:[]}};this.logger.info(CN,"handleUnsubscribeReq, hasSubscribeReq:".concat(d,", allSubscribeReqFailed:").concat(f)),d&&f?this.appendSubscribeResult(r.failUnsubscribeInfos,p):this.appendSubscribeResult(r.successUnsubscribeInfos,p)}}hasTrackSignalReq(e){var t,r,i,n;return(null===(t=e.mainStream)||void 0===t||null===(r=t.allSubscribeTracks)||void 0===r?void 0:r.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).length)>0||(null===(i=e.auxStream)||void 0===i||null===(n=i.allSubscribeTracks)||void 0===n?void 0:n.filter((e=>e.type===mO.TRACK_TYPE_VIDEO)).length)>0}getTracksSubscribeResults(e,t,r,i,n){var o,s,a,c;const u=e?null===(o=t.mainStream)||void 0===o?void 0:o.tracks4Subscribe:null===(s=t.mainStream)||void 0===s?void 0:s.tracks4Unsubscribe;null==u||u.forEach((o=>{this.getTrackSubscribeResult(e,t.userInfo.userId,o,gO.STREAM_TYPE_MAIN,r,i,n)}));const d=e?null===(a=t.auxStream)||void 0===a?void 0:a.tracks4Subscribe:null===(c=t.auxStream)||void 0===c?void 0:c.tracks4Unsubscribe;null==d||d.forEach((o=>{this.getTrackSubscribeResult(e,t.userInfo.userId,o,gO.STREAM_TYPE_AUX,r,i,n)}))}getTrackSubscribeResult(e,t,r,i,n,o,s){var a;const c=i===gO.STREAM_TYPE_MAIN?s.mainStream:s.auxStream,u=i===gO.STREAM_TYPE_MAIN?o.mainStream:o.auxStream,d=null==n||null===(a=n.tracks)||void 0===a?void 0:a.find((e=>e.cSsrcId===r.cssrc));d?0!==d.code?(c.tracks.push(r),this.logger.error(CN,"isSubscribe:".concat(e,", subscribe user ").concat(t," ").concat(i," streamUid:").concat(d.pStreamUid," subscribed failed,code:").concat(d.code))):u.tracks.push(r):this.logger.error(CN,"isSubscribe:".concat(e,", subscribe user ").concat(t,", ").concat(i,"\n track req id: ").concat(r.trackId,", ssrc ").concat(r.cssrc," subscribed failed,mcs not response"))}async updateUserList(e){this.logger.info(CN,"updateUserList start");try{e.infos.forEach((e=>{this.stat.getMediaStat().setEncryInfo(String(e.userId),String(e.userEid))})),await this.locker.lock("".concat(CN,":updateUserList"));const t=this.remoteUserManager.updateUserListInfo(this.roomId,e.infos);if(this.logger.info(CN,"updateUserList , begin"),!t||0===t.length)return void this.logger.error(CN,"updateUserList , userUpdateInfos is null");t.forEach((e=>{if(e.isUserNameChanged&&(this.logger.info(CN,"emit ".concat(UC.UserNameChanged,", ").concat(e.userInfo.userId,"}")),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:e.userInfo.userId,userName:e.userInfo.nickname})),e.preUserState===IO.NotJoin&&e.curUserState===IO.Joined)this.logger.info(CN,"emit ".concat(UC.PeerJoin,", ").concat(e.userInfo.userId,":").concat(e.userInfo.nickname)),this.eventEmitter.emit(UC.PeerJoin,{userId:e.userInfo.userId,userName:e.userInfo.nickname,roomId:e.userInfo.roomId,relayRoomId:e.userInfo.relaySrcRoomId});else if(e.preUserState===IO.Joined&&e.curUserState===IO.NotJoin){var t,r,i,n;(null===(t=e.mainStream)||void 0===t||null===(r=t.removedTracks)||void 0===r?void 0:r.length)>0&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(e.userInfo.userId,", ").concat(gO.STREAM_TYPE_MAIN)),this.eventEmitter.emit(UC.StreamRemoved,{stream:e.mainStream.remoteStream})),(null===(i=e.auxStream)||void 0===i||null===(n=i.removedTracks)||void 0===n?void 0:n.length)>0&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(e.userInfo.userId,", ").concat(gO.STREAM_TYPE_AUX)),this.eventEmitter.emit(UC.StreamRemoved,{stream:e.auxStream.remoteStream})),this.logger.info(CN,"emit ".concat(UC.PeerLeave,", ").concat(e.userInfo.userId)),this.eventEmitter.emit(UC.PeerLeave,{userId:e.userInfo.userId,userName:e.userInfo.nickname,roomId:e.userInfo.roomId,relayRoomId:e.userInfo.relaySrcRoomId,reason:MC.HRTC_LEAVE_REASON_USER_LEAVE_ROOM}),this.stat.getMediaStat().updateAudioStreamInfos(e.userInfo.userId,"removed")}})),await this.updateSubscribe(t)}catch(jN){this.logger.error(CN,"updateUserList occur exception ".concat(jN))}finally{this.locker.unlock("".concat(CN,":updateUserList"))}}async refreshRemoteStreamList(e){this.logger.info(CN,"refreshRemoteStreamList start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};e.allAudioStreams=e.allAudioStreams.filter((e=>"cmd"!==e.content));const r=this.remoteUserManager.refreshRemoteStreamList(t,e.allVideoStreams,e.allAudioStreams);if(this.logger.info(CN,"refreshRemoteStreamList begin"),!r||0===r.length)return void this.logger.error(CN,"refreshRemoteStreamList , userUpdateInfos is null");const i=r.find((t=>t.userInfo.userId===e.userId));this.updateSingleUser(i),await this.updateSubscribe(r)}catch(jN){this.logger.error(CN,"refreshRemoteStreamList occur exception ".concat(jN))}}updateSingleUser(t){var r,i;t.isUserNameChanged&&(this.logger.info(CN,"emit ".concat(UC.UserNameChanged,", ").concat(t.userInfo.userId,"}")),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:t.userInfo.userId,userName:t.userInfo.nickname})),t.preUserState===IO.NotJoin&&t.curUserState===IO.Joined&&(this.logger.info(CN,"emit ".concat(UC.PeerJoin,", ").concat(t.userInfo.userId,":").concat(t.userInfo.nickname)),this.eventEmitter.emit(UC.PeerJoin,{userId:t.userInfo.userId,userName:t.userInfo.nickname,roomId:t.userInfo.roomId,relayRoomId:t.userInfo.relaySrcRoomId}));const n=null===(r=t.mainStream)||void 0===r?void 0:r.remoteStream;n&&(e.isStreamAdd(gO.STREAM_TYPE_MAIN,t)?(this.logger.info(CN,"emit ".concat(UC.StreamAdded,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamAdded,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"add",n)):e.isStreamRemove(gO.STREAM_TYPE_MAIN,t)?(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamRemoved,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"removed",n)):e.isStreamUpdate(gO.STREAM_TYPE_MAIN,t)&&(this.logger.info(CN,"emit ".concat(UC.StreamUpdated,", ").concat(t.userInfo.userId,", ").concat(n.getType(),"}")),this.eventEmitter.emit(UC.StreamUpdated,{stream:n}),this.updateAudioStreamInfo(t.userInfo.userId,"update",n)));const o=null===(i=t.auxStream)||void 0===i?void 0:i.remoteStream;o&&(e.isStreamAdd(gO.STREAM_TYPE_AUX,t)?(this.logger.info(CN,"emit ".concat(UC.StreamAdded,", ").concat(t.userInfo.userId,", ").concat(o.getType(),"}")),this.eventEmitter.emit(UC.StreamAdded,{stream:o})):e.isStreamRemove(gO.STREAM_TYPE_AUX,t)&&(this.logger.info(CN,"emit ".concat(UC.StreamRemoved,", ").concat(t.userInfo.userId,", ").concat(o.getType(),"}")),this.eventEmitter.emit(UC.StreamRemoved,{stream:o}))),t.preUserState===IO.Joined&&t.curUserState===IO.NotJoin&&(this.logger.info(CN,"emit ".concat(UC.PeerLeave,", ").concat(t.userInfo.userId)),this.eventEmitter.emit(UC.PeerLeave,{userId:t.userInfo.userId,userName:t.userInfo.nickname,roomId:t.userInfo.roomId,relayRoomId:t.userInfo.relaySrcRoomId,reason:MC.HRTC_LEAVE_REASON_USER_LEAVE_ROOM}),this.stat.getMediaStat().updateAudioStreamInfos(t.userInfo.userId,"removed")),this.handleMuteStatus(t)}updateAudioStreamInfo(e,t,r){var i;if("add"===t)null!==(i=r.getStreamInfo())&&void 0!==i&&i.audioProfile&&this.stat.getMediaStat().updateAudioStreamInfos(e,"add");else if("removed"===t)this.stat.getMediaStat().updateAudioStreamInfos(e,"removed");else{var n;null!==(n=r.getStreamInfo())&&void 0!==n&&n.audioProfile?this.stat.getMediaStat().updateAudioStreamInfos(e,"add"):this.stat.getMediaStat().updateAudioStreamInfos(e,"removed")}}remoteUserDisconnectNotify(e){e&&this.logger.info(CN,"remoteDisconnectNotify, userId:".concat(e.userId))}remoteUserReconnectNotify(e){if(!e)return;this.logger.info(CN,"remoteReconnectNotify, userId:".concat(e.userId));const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};this.remoteUserManager.remoteUserReconnect(t,e.videoStreams,e.audioStreams)}updateAppData(e){const t=e.userId,r=e.appData.nickname;t&&e.userId!==this.userInfo.userId&&(this.remoteUserManager.updateUserName(t,this.roomId,r),this.eventEmitter.emit(UC.UserNameChanged,{roomId:this.roomId,userId:t,userName:r}))}async updateRemoteStream(e){this.logger.info(CN,"updateRemoteStream start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null},r=this.remoteUserManager.updateRemoteStream(t,e.videoStreams,e.audioStreams);if(this.logger.info(CN,"updateRemoteStream , begin"),!r)return void this.logger.error(CN,"updateRemoteStream , userUpdateInfos is null");this.handleMuteStatus(r)}catch(jN){this.logger.error(CN,"updateRemoteStream occur exception ".concat(jN))}}handleMuteStatus(t){this.logger.info(CN,"handleMuteStatus begin");const r=e.getMuteChangeStatus(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO,t);r!==EN.noChange&&(this.emitMediaStatusChange(t.userInfo.userId,t.userInfo.roomId,mO.TRACK_TYPE_AUDIO,r),r===EN.unmute?this.stat.getMediaStat().updateAudioStreamInfos(this.userInfo.userId,"add"):this.stat.getMediaStat().updateAudioStreamInfos(this.userInfo.userId,"removed"));const i=e.getMuteChangeStatus(gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_VIDEO,t);i!==EN.noChange&&this.emitMediaStatusChange(t.userInfo.userId,t.userInfo.roomId,mO.TRACK_TYPE_VIDEO,i)}async removeRemoteStream(e){this.logger.info(CN,"removeRemoteStream start");try{const t={userId:e.userId,userUid:e.userUid,roomId:this.roomId,nickname:null};e.allAudioStreams=e.allAudioStreams.filter((e=>"cmd"!==e.content));const r=this.remoteUserManager.refreshRemoteStreamList(t,e.allVideoStreams,e.allAudioStreams);if(this.logger.info(CN,"removeRemoteStream begin"),!r||0===r.length)return void this.logger.error(CN,"removeRemoteStream , userUpdateInfos is null");const i=r.find((t=>t.userInfo.userId===e.userId));this.updateSingleUser(i),await this.updateSubscribe(r)}catch(jN){this.logger.error(CN,"removeRemoteStream occur exception ".concat(jN))}}emitMediaStatusChange(e,t,r,i){const n={roomId:t,userId:e,status:i===EN.unmute?IC.MediaStatusAvailable:IC.MediaStatusUnavailable,reason:i===EN.unmute?RC.MediaUnmuted:RC.MediaMuted},o=r===mO.TRACK_TYPE_AUDIO?i===EN.unmute?"UnmuteAudio":"MuteAudio":i===EN.unmute?"UnmuteVideo":"MuteVideo";this.logger.info(CN,"emit ".concat(UC[o],", userId: ").concat(e,", type: ").concat(r,", status: ").concat(n.status)),this.eventEmitter.emit(UC[o],n)}waitNotifyConfig(e){return new Promise(((t,r)=>{const i={id:e.length+1,domain:"",start_ms:XR.getCurrentTimestamp(),delay_ms:0,stepName:"configNotify",rspCode:"",errMsg:""};let n=null;this.waitConfigCallbackFunc=()=>{clearTimeout(n),t(),i.delay_ms=XR.getCurrentTimestamp()-i.start_ms,i.rspCode="OK",e.push(i)},this.validSignatureFunc=e=>{clearTimeout(n),r(new qc(e.code,e.message))},n=setTimeout((()=>{this.logger.error(CN,"wait config timeout"),i.rspCode="".concat(Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL),i.errMsg=Jc[Gc.RTC_ERR_CODE_WAIT_CONFIG_FAIL],i.delay_ms=XR.getCurrentTimestamp()-i.start_ms,e.push(i),t()}),fA)}))}handleConfigNotifyBody(e){const{controlDisconnectTimeout:t="30",controlHoldTimeout:r="120",controlPingPeriod:i="5"}=e.appConfigs||{};this.sfuConfigs={};for(const o of yA)Object.prototype.hasOwnProperty.call(e.appConfigs,o)&&(this.sfuConfigs[o]=e.appConfigs[o]);for(const o of IA)Object.prototype.hasOwnProperty.call(e.appConfigs,o)&&(this.sfuConfigs[o]=e.appConfigs[o]);const n={heartBeatRetryTimes:parseInt(t)/parseInt(i)||mA,connectionTimeout:parseInt(r)||gA,heartBeatPeriod:parseInt(i)||pA};this.waitConfigCallbackFunc&&this.waitConfigCallbackFunc(),this.stat.setTraceInfo(e.traceId),TD.setLogServerConfigs(e.logServerConfigs),this.signal.setConfigParams(n)}async uploadLog(e){await TD.uploadLogFile(this,e)}async handleWatchMsg(e){if(null!=e)try{const t=e,r=t.videoSsrcIds,i=t.audioSsrcIds;if(this.sdpRepInfo.cmd&&(null==i?void 0:i.length)>0&&0===i.filter((e=>this.sdpRepInfo.cmd.sendSsrc!==e)).length)return;const n=r.filter((e=>this.sdpRepInfo.video.sendSsrcRange.find((t=>e===t)))),o=r.filter((e=>this.sdpRepInfo.desktopVideo.sendSsrcRange.find((t=>e===t)))),s=[],a=[],c={mainStreamVideoTracks2Update:{},mainStreamAudioTracks2Update:{},auxStreamTracks2Update:{}},u=this.streamPublishManager.generatePubInfoWhenWatch(gO.STREAM_TYPE_MAIN,n,i||[],mO.TRACK_TYPE_VIDEO);if(await this.publishWhenWatch(gO.STREAM_TYPE_MAIN,u),n&&n.length>0&&(null==u||u.tracks2NewPublish.forEach((e=>{r.find((t=>t===e.ssrc))&&s.push({ssrcId:e.ssrc,status:0})})),null==u||u.tracks2KeepPublish.forEach((e=>{s.push({ssrcId:e.ssrc,status:0})})),c.mainStreamVideoTracks2Update=u),i&&i.length>0){const e=this.streamPublishManager.generatePubInfoWhenWatch(gO.STREAM_TYPE_MAIN,[],i);await this.publishWhenWatch(gO.STREAM_TYPE_MAIN,e),null==e||e.tracks2NewPublish.forEach((e=>{i.find((t=>t===e.ssrc))&&a.push({ssrcId:e.ssrc,status:0})})),null==e||e.tracks2KeepPublish.forEach((e=>{a.push({ssrcId:e.ssrc,status:0})})),c.mainStreamAudioTracks2Update=e}if(o&&o.length>0){const e=this.streamPublishManager.generatePubInfoWhenWatch(gO.STREAM_TYPE_AUX,o,[]);await this.publishWhenWatch(gO.STREAM_TYPE_AUX,e),null==e||e.tracks2NewPublish.forEach((e=>{r.find((t=>t===e.ssrc))&&s.push({ssrcId:e.ssrc,status:0})})),null==e||e.tracks2KeepPublish.forEach((e=>{s.push({ssrcId:e.ssrc,status:0})})),c.auxStreamTracks2Update=e}this.logger.info(CN,"handle watch success, videoSsrcs: ".concat(JSON.stringify(r),", audioSsrcs: ").concat(JSON.stringify(i)));const d=this.stat.getSpanId(t["x-nuwa-span-id"]),l=XR.generateRandomId(16,16);this.stat.setParentSpanId(l,d);const h={type:"WATCH_STREAM_NOTIFY",requestId:t.requestId,traceId:t.traceId,version:t.version,videoSsrcIds:s,audioSsrcIds:a,"x-nuwa-trace-id":t["x-nuwa-trace-id"],"x-nuwa-span-id":l};await this.signal.pushStreamResponse(h),this.reportMediaStreamInfo(c,s),this.logger.info(CN,"handleWatchMsg success")}catch(jN){this.logger.error(CN,"handleWatchMsg occur error ".concat(jN))}else this.logger.error(CN,"message is null")}reportMediaStreamInfo(e,t){var r,i,n,o;if(null!==(r=e.mainStreamVideoTracks2Update)&&void 0!==r&&null!==(i=r.tracks2NewPublish)&&void 0!==i&&i.find((e=>e.type===mO.TRACK_TYPE_VIDEO))){this.stat.getMediaStat().setLocalMainStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedMainStreamInfos())&&this.buildSendMediaStreamInfo(TC.Video,t)}if(null!==(n=e.auxStreamTracks2Update)&&void 0!==n&&null!==(o=n.tracks2NewPublish)&&void 0!==o&&o.filter((e=>e.type===mO.TRACK_TYPE_VIDEO))){this.stat.getMediaStat().setLocalAuxsStreamInfo(this.userInfo.userId,this.streamPublishManager.getPublishedAuxStreamInfo())&&this.buildSendMediaStreamInfo(TC.Aux)}}async publishWhenWatch(e,t){if(!t||0===t.tracks2NewPublish.length&&0===t.tracks2KeepPublish.length&&0===t.tracks2UnPublish.length)return void this.logger.info(CN,"handleWatchMsg, watched track no update");const r=this.streamPublishManager.getLocalStream(e);await this.sendPublishRequest(t.allTracks2Publish),await this.startStreamResolutionDetection(r),await this.updateStreamTracks(r,t),this.logger.info(CN,"handleWatchMsg, published stream")}setCameraCaptureReport(e,t){this.stat.setCameraInfo(e,t)}signalEvent(){this.signal.on(bC.watchStreamNotify,(e=>{this.handleWatchMsg(e)})),this.signal.on(bC.pushStreamNotify,(e=>{this.refreshRemoteStreamList(e)})),this.signal.on(bC.stopPushStreamNotify,(e=>{this.removeRemoteStream(e)})),this.signal.on(bC.changeStreamStatusNotify,(e=>{this.updateRemoteStream(e)})),this.signal.on(bC.appDataChangeNotify,(e=>{this.updateAppData(e)})),this.signal.on(bC.disconnectNotify,(e=>{this.remoteUserDisconnectNotify(e)})),this.signal.on(bC.reconnectNotify,(e=>{this.remoteUserReconnectNotify(e)})),this.signal.on(bC.configNotify,(e=>{this.handleConfigNotifyBody(e)})),this.signal.on(bC.top3AudioVolumeNotify,(e=>{this.handleMaxVolumeNotify(e)})),this.signal.on(bC.statusChangeNotify,(async e=>{await this.updateUserList(e)})),this.signal.on(bC.uploadLogNotify,(async e=>{await this.uploadLog(e)})),this.signal.on(bC.publishStatusNotify,(e=>{this.handlePublishStatusNotify(e)})),this.signal.on(dM.Reconnected,(async()=>{await this.refreshRoomUserInfos()})),this.signal.on(dM.SessionUnavailable,(async()=>{this.logger.info(CN,"".concat(dM.SessionUnavailable));await this.rejoinLoop(120)})),this.signal.on(dM.ConnectionUnavailable,(async()=>{this.logger.info(CN,"".concat(dM.ConnectionUnavailable));await this.rejoinLoop(120)})),this.signal.on(dM.AuthenticateFail,(async()=>{this.logger.info(CN,"".concat(dM.AuthenticateFail)),this.doLeaveRoom()})),this.signal.on(dM.SignatureExpired,(e=>{this.handleNotifySignatureExpired(e)})),this.signal.on(UC.ConnectionStateChanged,(e=>{this.handleNotifyConnectStateChange(e)})),this.signal.on(UC.NetworkQuality,(e=>{this.eventEmitter.emit(UC.NetworkQuality,e)})),this.signal.on(dM.ClientBanned,(()=>{this.kickRoom()})),this.signal.on(bC.roomStreamStatusNotify,(e=>{this.handleNotifyRoomStreamStatus(e)}))}kickRoom(){this.eventEmitter.emit(UC.ClientBanned,{userId:this.userInfo.userId}),this.cleanup(),this.cleanTransportStats(),this.stat.leaveRoom(),nO.immediateReportRecords(),this.logger.info(CN,"kick leave success")}async refreshRoomUserInfos(){const e=await this.signal.queryRoomUsers(null);await this.doRefreshRoomUserInfos(this.roomId,e.userInfos,!1)}async doRefreshRoomUserInfos(e,t,r){try{this.logger.debug(CN,"doRefreshRoomUserInfos, begin");const i=this.remoteUserManager.refreshRemoteUserList(e,t,r);if(!i)return null;i.forEach((e=>{this.updateSingleUser(e)})),await this.updateSubscribe(i)}catch(jN){this.logger.error(CN,"doRefreshRoomUserInfos, error:".concat(jN))}}async rejoinLoop(e){if(this.isLoopRejoining)this.logger.info(CN,"rejoinLoop, isLoopRejoining so return");else try{this.isLoopRejoining=!0;const t=async e=>await this.handleRejoin(e),r=e=>"function"==typeof(null==e?void 0:e.getCode)&&e.getCode()===Gc.RTC_ERR_CODE_STATUS_ERROR;return await mP.callWithRetryTimes(t,!1,e,RN,r)}catch(jN){this.logger.error(CN,"rejoinLoop, rejoin room failed, leave room, error:".concat(jN)),this.localRejoinFlag||(this.connectState={prevState:vC[yC.RECONNECTING],curState:vC[yC.DISCONNECTED]},this.eventEmitter.emit(UC.ConnectionStateChanged,this.connectState));try{await this.leaveImpl()}catch(jN){this.logger.error(CN,"rejoinLoop, leave failed, error:".concat(jN))}}finally{this.isLoopRejoining=!1}}async handleRejoin(e){if(this.logger.info(CN,"handleRejoin, client status: ".concat(this.status,", tryNumber:").concat(e)),this.status===OC.Idle)throw this.logger.error(CN,"handleRejoin, status:".concat(OC.Idle)),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"handleRejoin but status is Idle");if(this.isSignatureExpired){if(this.signatureExpiredRejoinTimeout)return void this.logger.info(CN,"signature expired, try rejoin, timer already exists");this.signatureExpiredRejoinTimeout=setTimeout((()=>{throw this.logger.error(CN,"handleRejoin, signature expired and retry limit, exit"),this.cleanup(),new qc(Gc.RTC_ERR_CODE_STATUS_ERROR,"handleRejoin but signature expired")}),2e4)}try{await this.locker.lock("".concat(CN,":handleRejoin")),this.status=OC.Rejoining,await this.rejoin(this.roomId,uM.transLocalUserToJoinConfig(this.userInfo)),this.getSessionStatus()===OC.Joined&&(this.logger.info(CN,"handleRejoin, rejoin room success"),this.isSignatureExpired=!1,clearTimeout(this.signatureExpiredRejoinTimeout),this.signatureExpiredRejoinTimeout=void 0,this.connectState={prevState:vC[yC.RECONNECTING],curState:vC[yC.CONNECTED]},this.eventEmitter.emit(UC.ConnectionStateChanged,this.connectState),await this.rejoinPublish(),this.localRejoinFlag=!1)}finally{this.locker.unlock("".concat(CN,":handleRejoin"))}}async rejoinPublish(){this.logger.info(CN,"rejoin publish stream"),this.connectState.prevState=vC[yC.DISCONNECTED];const e=[],t=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN),r=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_AUX);t&&e.push(t),r&&e.push(r),e.length>0&&await this.rejoinPublishStreams(e)}handleNotifySignatureExpired(e){this.logger.warn(CN,"handleNotifySignatureExpired");const t={code:0,reason:""};"reconnect"===e.type?(this.logger.warn(CN,"reconnect but signature expired"),t.code=Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]):this.isLoopRejoining?(this.logger.warn(CN,"rejoin but signature expired"),this.isSignatureExpired=!0,t.code=Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_EXPIRED]):(t.code=Gc.RTC_ERR_CODE_SIGNATURE_INVALID,t.reason=Jc[Gc.RTC_ERR_CODE_SIGNATURE_INVALID]),this.validSignatureFunc&&this.validSignatureFunc(t),this.validSignatureFunc=void 0;const r={errorCode:"".concat(t.code),errorMsg:t.reason};this.eventEmitter.emit(UC.SignatureExpired,r)}handleNotifyConnectStateChange(e){this.logger.info(CN,"ConnectStateChange"),this.eventEmitter.emit(UC.ConnectionStateChanged,e),this.connectState.curState=e.curState}cleanNetworkStatistic(){this.preNetQuality=null,this.downLinkData=null,this.upLinkData=null}cleanup(){var e,t,r;null===(e=this.signal)||void 0===e||e.disconnect(),this.signal=void 0,this.resetConnection(),null===(t=this.remoteUserManager)||void 0===t||t.clear(this.roomId);const i=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN);if(i){i.removeClient(this)}this.streamPublishManager.reset(),clearTimeout(this.streamInterruptedDetectInterval),clearTimeout(this.rtcStatsInterval),clearTimeout(this.netQualityTimer),clearTimeout(this.transportStatsTimer),CO.reset(),this.cleanNetworkStatistic(),this.streamInterruptedDetectInterval=null,this.rtcStatsInterval=null,this.lastCycleFrameDecodedMap.clear(),this.streamInterruptedUsersMap.clear(),this.startupQoSMap.clear(),this.status=OC.Idle,this.locker.clear(),clearInterval(this.audioLevelTimer),ED.stopRelayConnection(this,this.roomId),null===(r=this.cmdMsgAbility.cmdManager)||void 0===r||r.reset(),this.isSignatureExpired=!1,clearTimeout(this.signatureExpiredRejoinTimeout),this.signatureExpiredRejoinTimeout=void 0}async addSsrc4Top3(e){var t;return this.audioStreams4TopN.close(),await this.addSsrc2SdpBatch(e,null===(t=this.sdpRepInfo.audio)||void 0===t?void 0:t.topNSsrcBegin)}setAudioLevelStatTimer(){this.audioLevelTimer&&clearInterval(this.audioLevelTimer),this.logger.info(CN,"setAudioLevelStatTimer"),this.audioLevelTimer=setInterval((()=>{try{this.audioStreams4TopN.getAudioLevel().forEach((e=>{const t=Math.round(100*e.level);this.stat.getMediaStat().updateAudioLevel({type:"remotetop3",level:t,ssrc:e.ssrc})}));const e=this.remoteUserManager.getAllUserStreamsByType(this.roomId,gO.STREAM_TYPE_MAIN,mO.TRACK_TYPE_AUDIO),t=[];e.forEach((e=>{const r=e.mainStream.tracks.find((e=>e.isTrackReady&&e.type===mO.TRACK_TYPE_AUDIO&&e.isSubscribed));r&&t.push({userId:e.userId,ssrc:r.cssrc})}));for(const n of t){const e=this.remoteUserManager.getUserInfoById(n.userId,this.roomId),t=Math.round(100*e.mainStream.remoteStream.getAudioLevel());this.stat.getMediaStat().updateAudioLevel({type:"remote",level:t,ssrc:n.ssrc,userId:n.userId})}const r=this.streamPublishManager.getLocalStream(gO.STREAM_TYPE_MAIN),i=Math.round(100*(r?r.getAudioLevel():0));this.stat.getMediaStat().updateAudioLevel({type:"local",level:i})}catch(jN){this.logger.error(CN,"setAudioLevelStatTimer, occur error: ".concat(jN))}}),this.audioLevelInterval)}async addSsrc2SdpBatch(e,t){if(!t)return null;const r={answerSdp:e},i=await this.connectionsManager.addTopAudioUserBatch(r.answerSdp,t,3,((e,t)=>{this.audioStreams4TopN.addAudioStream(e,t)}));return this.stat.getMediaStat().setStartSsrc(t),i}async saveAudioStream4TopN(e){this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, save audio stream, streamId: ".concat(e.streams[0].id));if(null!=this.audioStreams4TopN.getAudioStream(e.streams[0].id)){this.audioStreams4TopN.updateAudioStream(e.streams[0].id,e.track),this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, save audio stream ok, streamId: ".concat(e.streams[0].id));try{await this.audioStreams4TopN.play(e.streams[0].id),this.audioStreams4TopN.setAudioVolume4Id(e.streams[0].id,this.topNAudioVolume),this.logger.info(CN,"AudioPolicy:TOPN_AUDIOPOLICY, auto play audio success, streamId: ".concat(e.streams[0].id))}catch(e){this.logger.error(CN,"AudioPolicy:TOPN_AUDIOPOLICY, auto play audio fail, ".concat(null==e?void 0:e.message,", streamId: ").concat(e.streams[0].id))}}else this.logger.error(CN,"AudioPolicy:TOPN_AUDIOPOLICY, audio stream of streamId: ".concat(e.streams[0].id," not exist"))}handleMaxVolumeNotify(e){try{e.topUserAudios&&e.topUserAudios.length>0?(this.top3VolumeUserIds.length=0,e.topUserAudios.forEach((e=>{e.volume=100*(60-(e.volume>60?60:e.volume))/60,this.top3VolumeUserIds.push({user_id:e.userId,volume:e.volume})})),this.audioPolicy===_O.TOPN_AUDIOPOLICY&&this.eventEmitter.emit(UC.VolumeIndicator,{userVolumeInfos:this.top3VolumeUserIds})):this.logger.error(CN,"handleMaxVolumeNotify error,topUserAudios is null")}catch(Aw){this.logger.error(CN,"handleMaxVolumeNotify error ".concat(null==Aw?void 0:Aw.message))}}handlePublishStatusNotify(e){try{e.urlStatus&&(this.logger.info(CN,"emit ".concat(UC.LiveStreamingUpdated)),this.eventEmitter.emit(UC.LiveStreamingUpdated,e.urlStatus))}catch(Aw){this.logger.error(CN,"handlePublishStatusNotify error ".concat(Aw))}}setVolume4TopThree(e){this.setVolume4TopThreeImpl(e)}setVolume4TopThreeImpl(e){this.logger.debug(CN,"setVolume4TopThreeImpl volume: "+e),e>100||e<0||this.audioPolicy===_O.TOPN_AUDIOPOLICY&&(this.topNAudioVolume=e,this.audioStreams4TopN.setAudioVolume(e))}muteAudio4TopThree(e){this.muteAudio4TopThreeImpl(e)}muteAudio4TopThreeImpl(e){this.logger.debug(CN,"muteAudio4TopThree enable: "+e),this.audioPolicy===_O.TOPN_AUDIOPOLICY&&this.audioStreams4TopN.muteAudio(e)}async setAudioOutput4TopThree(e){this.audioPolicy===_O.TOPN_AUDIOPOLICY&&await this.audioStreams4TopN.setAudioOutput(e)}isTopNAudioMuted(){return this.isTopNAudioMutedImpl()}isTopNAudioMutedImpl(){let e=!1;return this.audioPolicy===_O.TOPN_AUDIOPOLICY&&(e=this.audioStreams4TopN.isAudioMuted(),this.logger.debug(CN,"isTopNAudioMutedImpl : "+e)),e}async changeUserName(e){return await this.changeUserNameImpl(e)}async changeUserNameImpl(e){try{if(Zk.checkUserName(e),this.userInfo.role===nM)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"player can not change user name");return await this.signal.appData(this.userInfo.appData,"nickname",e),this.userInfo.appData.nickname=e,!0}catch(jN){return this.logger.error(CN,"changeUserNameImpl, error:".concat(jN)),!1}}reportAudioMuteInfo(e,t){this.stat.reportAudioMuteInfo(e,t)}reportVideoMuteInfo(e,t){this.stat.reportVideoMuteInfo(e,t)}async startLiveStreaming(e,t,r,i){return await this.startLiveStreamingImpl(e,t,r,i)}async startLiveStreamingImpl(e,t,r,i){if(this.logger.info(CN,"startLiveStreaming: publishConfig: ".concat(JSON.stringify(r),", userConfig: ").concat(JSON.stringify(i))),!(t&&e&&r&&i))throw this.logger.error(CN,"startLiveStreaming failed for parameter error: empty parameter"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(this.status!==OC.Joined||this.userInfo.role!==iM)throw this.logger.error(CN,"startLiveStreaming failed for permission not allowed"),new qc(Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION);const n=this.getLiveStreamingUserInfos(i,99===r.template);if(0===n.length)throw this.logger.error(CN,"startLiveStreaming failed for parameter error:".concat(JSON.stringify(i))),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);try{await this.signal.startLiveStreaming(e,t,r,n),this.logger.info(CN,"startLiveStreaming success, taskId: ".concat(e,", url: ").concat(t))}catch(jN){throw this.logger.error(CN,"startLiveStreaming failed: ".concat(jN)),jN}}getLiveStreamingUserInfos(e,t){if(!e||0===e.length)return null;const r=[],i=this.userInfo.userId;return e.forEach((e=>{const n={userId:e.userId,audioStreams:[],videoStreams:[],layouts:[]};if(t&&!e.layouts)throw this.logger.error(CN,"getLiveStreamingUserInfos, layouts is null when template=99"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);e.userId===i?this.getLocalLiveStreamingUserInfos(e,n,t):this.getRemoteLiveStreamingUserInfos(e,n,t),(n.audioStreams.length||n.videoStreams.length)&&r.push(n)})),this.logger.info(CN,"getLiveStreamingUserInfos, publishInfos : ".concat(JSON.stringify(r))),r}getLocalLiveStreamingUserInfos(t,r,i){const n=this.streamPublishManager.getPublishedMainStreamInfos();if(t.audio){var o;const e=null==n||null===(o=n.find((e=>e.type===mO.TRACK_TYPE_AUDIO)))||void 0===o?void 0:o.ssrc;e&&r.audioStreams.push(e)}if(!t.resolutionIds||0===t.resolutionIds.length)return;const s=this.streamPublishManager.getPublishedAuxVideoTrackInfo();t.resolutionIds.forEach((o=>{var a;const c=null==n||null===(a=n.find((e=>e.resolutionId===o)))||void 0===a?void 0:a.ssrc;c?e.updateSlidePublishInfo(t,r,c,o,i):(null==s?void 0:s.resolutionId)===o&&e.updateSlidePublishInfo(t,r,s.ssrc,o,i)}))}static getSsrcLayout(e,t){return{alpha:t.alpha,localX:t.localX,localY:t.localY,renderMode:t.renderMode,ssrc:e,subBackGroundColor:t.subBackGroundColor,subHeight:t.subHeight,subWidth:t.subWidth,zorder:t.zorder}}getRemoteLiveStreamingUserInfos(t,r,i){const n=this.remoteUserManager.getAllUserStreamsByType(this.roomId,null,null),o=null==n?void 0:n.find((e=>e.userId===t.userId));if(o){if(t.audio){var s,a,c;const e=null===(s=o.mainStream)||void 0===s||null===(a=s.tracks)||void 0===a||null===(c=a.find((e=>e.type===mO.TRACK_TYPE_AUDIO)))||void 0===c?void 0:c.pssrc;e&&r.audioStreams.push(e)}if(!t.resolutionIds||0===t.resolutionIds.length)return;for(const n of t.resolutionIds){var u,d,l;const s=null===(u=o.mainStream)||void 0===u||null===(d=u.tracks)||void 0===d||null===(l=d.find((e=>e.trackId===n)))||void 0===l?void 0:l.pssrc;if(s)e.updateSlidePublishInfo(t,r,s,n,i);else{var h,f,p;const s=null===(h=o.auxStream)||void 0===h||null===(f=h.tracks)||void 0===f||null===(p=f.find((e=>e.trackId===n)))||void 0===p?void 0:p.pssrc;s&&e.updateSlidePublishInfo(t,r,s,n,i)}}}}static updateSlidePublishInfo(t,r,i,n,o){if(r.videoStreams.push(i),o&&t.layouts){const o=t.layouts.find((e=>e.resolutionId===n));if(o){const t=e.getSsrcLayout(i,o);r.layouts.push(t)}}}async updateLiveStreaming(e,t,r,i){return await this.updateLiveStreamingImpl(e,t,r,i)}async updateLiveStreamingImpl(e,t,r,i){if(this.logger.info(CN,"updateLiveStreaming: publishConfig: ".concat(JSON.stringify(r),", userConfig: ").concat(JSON.stringify(i))),!(t&&e&&r&&i))throw this.logger.error(CN,"updateLiveStreaming failed for parameter error: empty param"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);if(this.status!==OC.Joined||this.userInfo.role!==iM)throw this.logger.error(CN,"updateLiveStreaming failed for permission not allowed"),new qc(Gc.RTC_ERR_CODE_ROLE_NO_PERMISSION);const n=this.getLiveStreamingUserInfos(i,99===r.template);try{await this.signal.updateLiveStreaming(e,r,n),this.logger.info(CN,"updateLiveStreaming success, taskId: ".concat(e,", url: ").concat(t))}catch(jN){throw this.logger.error(CN,"updateLiveStreaming failed: ".concat(jN)),jN}}async stopLiveStreaming(e){return await this.stopLiveStreamingImpl(e)}async stopLiveStreamingImpl(e){if(this.logger.info(CN,"stopLiveStreaming: taskId: ".concat(e)),!e)throw this.logger.error(CN,"stopLiveStreaming failed for parameter error: taskId is empty"),new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER);try{await this.signal.stopLiveStreaming(e),this.logger.info(CN,"stopLiveStreaming success, taskId: ".concat(e))}catch(jN){throw this.logger.error(CN,"stopLiveStreaming failed: ".concat(jN)),jN}}setProxyServer(e){eO.setPorxyServer(e)}setTurnServer(e){var t;null===(t=this.connectionsManager)||void 0===t||t.setTurnServer(e)}async addMultiRoomMediaRelay(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"addMultiRoomMediaRelay failed for not joined room."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);Zk.checkSrcMultiRoomInfo(e.srcRoomRelayInfo);for(const n of e.dstRoomRelayInfo)Zk.checkDstMultiRoomInfo(n,this.userInfo.role);const t=new Map;e.dstRoomRelayInfo.forEach((e=>{t.set(e.roomId,e.role)}));const r=await this.signal.mediaRelay(e,!0,this.userInfo),i=[];return r.addResult.forEach((async e=>{i.push({roomId:e.roomId,result:e.resultCode,msg:e.resultMessage}),0===e.resultCode?this.userInfo.addRelayInfo(e.roomId,t.get(e.roomId)):this.logger.error(CN,"addMultiRoomMediaRelay failed, roomId: ".concat(e.roomId,", resultCode: ").concat(e.resultCode,", errMsg: ").concat(e.resultMessage)),this.stat.reportRelayJoinInfo({code:e.resultCode,acsAddr:"",requestId:r.requestId,traceId:r.traceId,roomId:e.roomId,role:t.get(e.roomId),roomUid:e.roomUid,failMessage:e.resultMessage})})),i}async stopMultiRoomMediaRelay(e){if(this.status!==OC.Joined)throw this.logger.error(CN,"stopMultiRoomMediaRelay failed for not joined room."),new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);let t;if(e&&e.dstRoomRelayInfo&&0!==e.dstRoomRelayInfo.length){Zk.checkSrcMultiRoomInfo(e.srcRoomRelayInfo);for(const t of e.dstRoomRelayInfo)Zk.checkDstMultiRoomInfo(t,this.userInfo.role);t=e}else t={dstRoomRelayInfo:this.userInfo.getRelayInfos()};const r=await this.signal.mediaRelay(t,!1,this.userInfo),i=[];return r.addResult.forEach((async e=>{i.push({roomId:e.roomId,result:e.resultCode,msg:e.resultMessage}),0===e.resultCode?this.userInfo.removeRelayInfo(e.roomId):this.logger.error(CN,"stopMultiRoomMediaRelay failed, roomId: ".concat(e.roomId,", resultCode: ").concat(e.resultCode,", errMsg: ").concat(e.resultMessage)),this.stat.reportRelayLeavInfo({code:e.resultCode,requestId:r.requestId,traceId:r.traceId,roomId:e.roomId,roomUid:e.roomUid})})),i}addRelayClient(e){return ED.addRelayConnection(this,e)}async stopRelayClient(e){const t=ED.getRelayConnection(this,e);t&&await t.leave()}enableCommandMsg(e,t){if(this.status!==OC.Idle&&e)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call enableCommandMsg interface before join room first.");var r;e?this.cmdMsgAbility.msgFormat=(null==t?void 0:t.msgFormat)===VC.ARRAY_BUFFER?VC.ARRAY_BUFFER:VC.STRING:(null===(r=this.cmdMsgAbility.cmdManager)||void 0===r||r.reset(),this.cmdMsgAbility.cmdManager=null);return this.cmdMsgAbility.enable=e,!0}sendCommandMsg(e,t){var r;if(!this.cmdMsgAbility.enable)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call enableCommandMsg interface before join room first.");if(this.status!==OC.Joined)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"pls call this interface after joined room.");if((null===(r=this.userInfo)||void 0===r?void 0:r.roleSignalType)!==oM.JOINER)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"only joiner can send comand message.");return Zk.checkCmdMsgValid(e),this.cmdMsgAbility.cmdManager.sendCommandMsg(e,t,this.roomId)}async handleNotifyRoomStreamStatus(e){const{audienceState:t}=e;this.logger.info(CN,"handleNotifyRoomStreamStatus handle room stream status : "+t+" role:"+this.userInfo.role),await this.handleRoomStreamStatus(t,_O.TOPN_AUDIOPOLICY===this.audioPolicy&&this.userInfo.role===nM&&YC.NORMAL===t)}async handleRoomStreamStatus(e,t,r){this.logger.info(CN,"handle room stream status : "+e),this.roomStreamStatus={audience:e};try{if(this.userInfo.role===nM&&e===YC.PAUSE){this.logger.info(CN,"player handle room stream status : "+e);const t=this.remoteUserManager.getAllSubscribedUpdateInfos4Unsubscribe(this.roomId);await this.updateSubscribe(t,null,!0),_O.TOPN_AUDIOPOLICY===this.audioPolicy&&(this.logger.info(CN,"player handle room stream status : "+e+" and topN unsubscribeUsersAudio"),await this.unsubscribeUsersAudio()),this.logger.info(CN,"player handle room stream status : "+e+" and clear intervals"),this.cleanNetworkStatistic(),this.netQualityRegularReport(),this.cleanTransportStats(),this.setAudioLevelStatTimer()}t&&(this.logger.info(CN,"".concat(this.userInfo.role," handle room stream status : ")+e+" and topN addSsrc4Top3"),this.remoteUserManager.enableTopThreeAudioMode(this.roomId),await this.connectionsManager.generateAndSetOfferSdpByHandler(gO.STREAM_TYPE_MAIN),await this.connectionsManager.generateAndSetAnswerSdpByHandler(gO.STREAM_TYPE_MAIN,this.addSsrc4Top3.bind(this))),(r||this.userInfo.role===nM&&[YC.PAUSE,YC.NORMAL].includes(e))&&(this.logger.info(CN,"eventEmitter RoomStreamStatus : "+e),this.eventEmitter.emit(UC.RoomStreamStatus,e))}catch(Aw){this.logger.error(CN,"RoomStreamStatus : "+e+" error:"+Aw)}}renewSignature(e,t){if("string"!=typeof e||"string"!=typeof t)throw new qc(Gc.RTC_ERR_CODE_INVALID_PARAMETER,"ctime or signature must be string");const r=uM.renewSignature(this.identifiedID,e,t);var i;return r?(this.userInfo=r,null===(i=this.signal)||void 0===i||i.refreshUserInfo(r),this.logger.info(CN,"renewSignature success"),!0):(this.logger.info(CN,"renewSignature fail"),!1)}},n(TN.prototype,"enableTopThreeAudioMode",[VD],Object.getOwnPropertyDescriptor(TN.prototype,"enableTopThreeAudioMode"),TN.prototype),n(TN.prototype,"switchAudioMode",[YD],Object.getOwnPropertyDescriptor(TN.prototype,"switchAudioMode"),TN.prototype),n(TN.prototype,"getConnectionState",[jD],Object.getOwnPropertyDescriptor(TN.prototype,"getConnectionState"),TN.prototype),n(TN.prototype,"setNetworkBandwidth",[FD],Object.getOwnPropertyDescriptor(TN.prototype,"setNetworkBandwidth"),TN.prototype),n(TN.prototype,"join",[HD],Object.getOwnPropertyDescriptor(TN.prototype,"join"),TN.prototype),n(TN.prototype,"enableRtcStats",[KD],Object.getOwnPropertyDescriptor(TN.prototype,"enableRtcStats"),TN.prototype),n(TN.prototype,"leave",[zD],Object.getOwnPropertyDescriptor(TN.prototype,"leave"),TN.prototype),n(TN.prototype,"publish",[WD],Object.getOwnPropertyDescriptor(TN.prototype,"publish"),TN.prototype),n(TN.prototype,"publishImpl",[GD],Object.getOwnPropertyDescriptor(TN.prototype,"publishImpl"),TN.prototype),n(TN.prototype,"unpublish",[JD],Object.getOwnPropertyDescriptor(TN.prototype,"unpublish"),TN.prototype),n(TN.prototype,"subscribeAudio",[qD],Object.getOwnPropertyDescriptor(TN.prototype,"subscribeAudio"),TN.prototype),n(TN.prototype,"unSubscribeAudio",[XD],Object.getOwnPropertyDescriptor(TN.prototype,"unSubscribeAudio"),TN.prototype),n(TN.prototype,"subscribe",[QD],Object.getOwnPropertyDescriptor(TN.prototype,"subscribe"),TN.prototype),n(TN.prototype,"batchSubscribe",[$D],Object.getOwnPropertyDescriptor(TN.prototype,"batchSubscribe"),TN.prototype),n(TN.prototype,"unsubscribe",[ZD],Object.getOwnPropertyDescriptor(TN.prototype,"unsubscribe"),TN.prototype),n(TN.prototype,"switchRole",[eN],Object.getOwnPropertyDescriptor(TN.prototype,"switchRole"),TN.prototype),n(TN.prototype,"refreshRemoteStreamList",[tN],Object.getOwnPropertyDescriptor(TN.prototype,"refreshRemoteStreamList"),TN.prototype),n(TN.prototype,"updateRemoteStream",[rN],Object.getOwnPropertyDescriptor(TN.prototype,"updateRemoteStream"),TN.prototype),n(TN.prototype,"removeRemoteStream",[iN],Object.getOwnPropertyDescriptor(TN.prototype,"removeRemoteStream"),TN.prototype),n(TN.prototype,"handleWatchMsg",[nN],Object.getOwnPropertyDescriptor(TN.prototype,"handleWatchMsg"),TN.prototype),n(TN.prototype,"refreshRoomUserInfos",[oN],Object.getOwnPropertyDescriptor(TN.prototype,"refreshRoomUserInfos"),TN.prototype),n(TN.prototype,"setVolume4TopThree",[sN],Object.getOwnPropertyDescriptor(TN.prototype,"setVolume4TopThree"),TN.prototype),n(TN.prototype,"muteAudio4TopThree",[aN],Object.getOwnPropertyDescriptor(TN.prototype,"muteAudio4TopThree"),TN.prototype),n(TN.prototype,"setAudioOutput4TopThree",[cN],Object.getOwnPropertyDescriptor(TN.prototype,"setAudioOutput4TopThree"),TN.prototype),n(TN.prototype,"isTopNAudioMuted",[uN],Object.getOwnPropertyDescriptor(TN.prototype,"isTopNAudioMuted"),TN.prototype),n(TN.prototype,"changeUserName",[dN],Object.getOwnPropertyDescriptor(TN.prototype,"changeUserName"),TN.prototype),n(TN.prototype,"startLiveStreaming",[lN],Object.getOwnPropertyDescriptor(TN.prototype,"startLiveStreaming"),TN.prototype),n(TN.prototype,"updateLiveStreaming",[hN],Object.getOwnPropertyDescriptor(TN.prototype,"updateLiveStreaming"),TN.prototype),n(TN.prototype,"stopLiveStreaming",[fN],Object.getOwnPropertyDescriptor(TN.prototype,"stopLiveStreaming"),TN.prototype),n(TN.prototype,"setProxyServer",[pN],Object.getOwnPropertyDescriptor(TN.prototype,"setProxyServer"),TN.prototype),n(TN.prototype,"setTurnServer",[mN],Object.getOwnPropertyDescriptor(TN.prototype,"setTurnServer"),TN.prototype),n(TN.prototype,"addMultiRoomMediaRelay",[gN],Object.getOwnPropertyDescriptor(TN.prototype,"addMultiRoomMediaRelay"),TN.prototype),n(TN.prototype,"stopMultiRoomMediaRelay",[_N],Object.getOwnPropertyDescriptor(TN.prototype,"stopMultiRoomMediaRelay"),TN.prototype),n(TN.prototype,"addRelayClient",[SN],Object.getOwnPropertyDescriptor(TN.prototype,"addRelayClient"),TN.prototype),n(TN.prototype,"stopRelayClient",[vN],Object.getOwnPropertyDescriptor(TN.prototype,"stopRelayClient"),TN.prototype),n(TN.prototype,"enableCommandMsg",[yN],Object.getOwnPropertyDescriptor(TN.prototype,"enableCommandMsg"),TN.prototype),n(TN.prototype,"renewSignature",[IN],Object.getOwnPropertyDescriptor(TN.prototype,"renewSignature"),TN.prototype),TN);var wN,kN,ON,PN,MN,DN,NN,UN,xN,LN,BN;const VN=new(wN=fP("default$setLogLevel#void#LogLevel"),kN=hP("default$checkSystemRequirements#Promise#boolean"),ON=fP("default$isScreenShareSupported#boolean"),PN=hP("default$getDevices#Promise"),MN=hP("default$getCameras#Promise"),DN=hP("default$getMicrophones#Promise"),NN=hP("default$getSpeakers#Promise"),UN=fP("default$setParameter#boolean#string#string"),xN=fP("default$createClient#Client#ClientConfig"),LN=fP("default$createStream#LocalStream#StreamConfig"),n((BN=class extends $P{constructor(){super({logger:!0,stat:!0}),i(this,"VERSION",uA),this.stat.setDeviceStatusInfo(),this.stat.setDeviceUserAgent()}setLogLevel(e){iE.setAllLogLevel(e)}async checkSystemRequirements(e){return await Cw.checkSystemRequirements(e)}isScreenShareSupported(){return Cw.isRTCScreenShareSupported()}async getDevices(){return await AC()}async getCameras(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"videoinput"===e.kind));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_VIDEO_INPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}async getMicrophones(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"audioinput"===e.kind&&"communications"!==e.deviceId&&"default"!==e.deviceId));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_INPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}async getSpeakers(){return await async function(){return new Promise(((e,t)=>{AC().then((r=>{const i=r.filter((e=>"audiooutput"===e.kind));i&&0!==i.length?e(i):t(new qc(Gc.RTC_ERR_CODE_NO_AVAILABLE_AUDIO_OUTPUT_DEVICES))})).catch((e=>{t(e)}))}))}()}setParameter(e,t){return pO.setParameter(e,t)}createClient(e){return Zk.checkAppid(e.appId),Zk.checkCountryCode(e.countryCode),e.domain&&Zk.checkDomain(e.domain),new AN(e)}createStream(e){if(e.screen){if(e.videoSource||e.audioSource){if(!0===e.video||!0===e.audio)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION)}else if(!this.isScreenShareSupported())throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION,"screen share is not supported")}else{if(!0!==e.video&&!0!==e.audio&&!e.videoSource&&!e.audioSource)throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION);if((!0===e.video||!0===e.audio)&&(e.videoSource||e.audioSource))throw new qc(Gc.RTC_ERR_CODE_INVALID_OPERATION)}return new tM(e)}getInfo(){return{moduleName:"default"}}}).prototype,"setLogLevel",[wN],Object.getOwnPropertyDescriptor(BN.prototype,"setLogLevel"),BN.prototype),n(BN.prototype,"checkSystemRequirements",[kN],Object.getOwnPropertyDescriptor(BN.prototype,"checkSystemRequirements"),BN.prototype),n(BN.prototype,"isScreenShareSupported",[ON],Object.getOwnPropertyDescriptor(BN.prototype,"isScreenShareSupported"),BN.prototype),n(BN.prototype,"getDevices",[PN],Object.getOwnPropertyDescriptor(BN.prototype,"getDevices"),BN.prototype),n(BN.prototype,"getCameras",[MN],Object.getOwnPropertyDescriptor(BN.prototype,"getCameras"),BN.prototype),n(BN.prototype,"getMicrophones",[DN],Object.getOwnPropertyDescriptor(BN.prototype,"getMicrophones"),BN.prototype),n(BN.prototype,"getSpeakers",[NN],Object.getOwnPropertyDescriptor(BN.prototype,"getSpeakers"),BN.prototype),n(BN.prototype,"setParameter",[UN],Object.getOwnPropertyDescriptor(BN.prototype,"setParameter"),BN.prototype),n(BN.prototype,"createClient",[xN],Object.getOwnPropertyDescriptor(BN.prototype,"createClient"),BN.prototype),n(BN.prototype,"createStream",[LN],Object.getOwnPropertyDescriptor(BN.prototype,"createStream"),BN.prototype),BN),YN={};return YN.VERSION=VN.VERSION,YN.setLogLevel=VN.setLogLevel,YN.checkSystemRequirements=VN.checkSystemRequirements,YN.isScreenShareSupported=VN.isScreenShareSupported,YN.getDevices=VN.getDevices,YN.getCameras=VN.getCameras,YN.getMicrophones=VN.getMicrophones,YN.getSpeakers=VN.getSpeakers,YN.setParameter=VN.setParameter,YN.createClient=VN.createClient,YN.createStream=VN.createStream,YN}));