dingrtc 3.8.11 → 3.8.12-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
14
14
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
15
15
|
* @license MIT
|
|
16
|
-
*/!function(e){!function(){function t(e){if(e)g[0]=g[16]=g[1]=g[2]=g[3]=g[4]=g[5]=g[6]=g[7]=g[8]=g[9]=g[10]=g[11]=g[12]=g[13]=g[14]=g[15]=0,this.blocks=g,this.buffer8=c;else if(l){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function r(e,r){var n,i=S(e);if(e=i[0],i[1]){var o,a=[],s=e.length,c=0;for(n=0;n<s;++n)(o=e.charCodeAt(n))<128?a[c++]=o:o<2048?(a[c++]=192|o>>>6,a[c++]=128|63&o):o<55296||o>=57344?(a[c++]=224|o>>>12,a[c++]=128|o>>>6&63,a[c++]=128|63&o):(o=65536+((1023&o)<<10|1023&e.charCodeAt(++n)),a[c++]=240|o>>>18,a[c++]=128|o>>>12&63,a[c++]=128|o>>>6&63,a[c++]=128|63&o);e=a}e.length>64&&(e=new t(!0).update(e).array());var u=[],l=[];for(n=0;n<64;++n){var d=e[n]||0;u[n]=92^d,l[n]=54^d}t.call(this,r),this.update(l),this.oKeyPad=u,this.inner=!0,this.sharedMemory=r}var n="input is invalid type",i="object"==typeof window,o=i?window:{};o.JS_MD5_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self,s=!o.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;s?o=commonjsGlobal:a&&(o=self);var c,u=!o.JS_MD5_NO_COMMON_JS&&e.exports,l=!o.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),p=[128,32768,8388608,-2147483648],f=[0,8,16,24],h=["hex","array","digest","buffer","arrayBuffer","base64"],m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),g=[];if(l){var v=new ArrayBuffer(68);c=new Uint8Array(v),g=new Uint32Array(v)}var y=Array.isArray;!o.JS_MD5_NO_NODE_JS&&y||(y=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var b=ArrayBuffer.isView;!l||!o.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&b||(b=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var S=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(n);if(l&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!y(e)&&!b(e))throw new Error(n);return[e,!1]},_=function(e){return function(r){return new t(!0).update(r)[e]()}},E=function(e){var t,r=require$$0,i=require$$1.Buffer;return t=i.from&&!o.JS_MD5_NO_BUFFER_FROM?i.from:function(e){return new i(e)},function(o){if("string"==typeof o)return r.createHash("md5").update(o,"utf8").digest("hex");if(null==o)throw new Error(n);return o.constructor===ArrayBuffer&&(o=new Uint8Array(o)),y(o)||b(o)||o.constructor===i?r.createHash("md5").update(t(o)).digest("hex"):e(o)}},T=function(e){return function(t,n){return new r(t,!0).update(n)[e]()}};t.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=S(e);e=t[0];for(var r,n,i=t[1],o=0,a=e.length,s=this.blocks,c=this.buffer8;o<a;){if(this.hashed&&(this.hashed=!1,s[0]=s[16],s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),i)if(l)for(n=this.start;o<a&&n<64;++o)(r=e.charCodeAt(o))<128?c[n++]=r:r<2048?(c[n++]=192|r>>>6,c[n++]=128|63&r):r<55296||r>=57344?(c[n++]=224|r>>>12,c[n++]=128|r>>>6&63,c[n++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++o)),c[n++]=240|r>>>18,c[n++]=128|r>>>12&63,c[n++]=128|r>>>6&63,c[n++]=128|63&r);else for(n=this.start;o<a&&n<64;++o)(r=e.charCodeAt(o))<128?s[n>>>2]|=r<<f[3&n++]:r<2048?(s[n>>>2]|=(192|r>>>6)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]):r<55296||r>=57344?(s[n>>>2]|=(224|r>>>12)<<f[3&n++],s[n>>>2]|=(128|r>>>6&63)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++o)),s[n>>>2]|=(240|r>>>18)<<f[3&n++],s[n>>>2]|=(128|r>>>12&63)<<f[3&n++],s[n>>>2]|=(128|r>>>6&63)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]);else if(l)for(n=this.start;o<a&&n<64;++o)c[n++]=e[o];else for(n=this.start;o<a&&n<64;++o)s[n>>>2]|=e[o]<<f[3&n++];this.lastByteIndex=n,this.bytes+=n-this.start,n>=64?(this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},t.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=p[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},t.prototype.hash=function(){var e,t,r,n,i,o,a=this.blocks;this.first?t=((t=((e=((e=a[0]-680876937)<<7|e>>>25)-271733879|0)^(r=((r=(-271733879^(n=((n=(-1732584194^2004318071&e)+a[1]-117830708)<<12|n>>>20)+e|0)&(-271733879^e))+a[2]-1126478375)<<17|r>>>15)+n|0)&(n^e))+a[3]-1316259209)<<22|t>>>10)+r|0:(e=this.h0,t=this.h1,r=this.h2,t=((t+=((e=((e+=((n=this.h3)^t&(r^n))+a[0]-680876936)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[1]-389564586)<<12|n>>>20)+e|0)&(e^t))+a[2]+606105819)<<17|r>>>15)+n|0)&(n^e))+a[3]-1044525330)<<22|t>>>10)+r|0),t=((t+=((e=((e+=(n^t&(r^n))+a[4]-176418897)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[5]+1200080426)<<12|n>>>20)+e|0)&(e^t))+a[6]-1473231341)<<17|r>>>15)+n|0)&(n^e))+a[7]-45705983)<<22|t>>>10)+r|0,t=((t+=((e=((e+=(n^t&(r^n))+a[8]+1770035416)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[9]-1958414417)<<12|n>>>20)+e|0)&(e^t))+a[10]-42063)<<17|r>>>15)+n|0)&(n^e))+a[11]-1990404162)<<22|t>>>10)+r|0,t=((t+=((e=((e+=(n^t&(r^n))+a[12]+1804603682)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[13]-40341101)<<12|n>>>20)+e|0)&(e^t))+a[14]-1502002290)<<17|r>>>15)+n|0)&(n^e))+a[15]+1236535329)<<22|t>>>10)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[1]-165796510)<<5|e>>>27)+t|0)^t))+a[6]-1069501632)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[11]+643717713)<<14|r>>>18)+n|0)^n))+a[0]-373897302)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[5]-701558691)<<5|e>>>27)+t|0)^t))+a[10]+38016083)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[15]-660478335)<<14|r>>>18)+n|0)^n))+a[4]-405537848)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[9]+568446438)<<5|e>>>27)+t|0)^t))+a[14]-1019803690)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[3]-187363961)<<14|r>>>18)+n|0)^n))+a[8]+1163531501)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[13]-1444681467)<<5|e>>>27)+t|0)^t))+a[2]-51403784)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[7]+1735328473)<<14|r>>>18)+n|0)^n))+a[12]-1926607734)<<20|t>>>12)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[5]-378558)<<4|e>>>28)+t|0))+a[8]-2022574463)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[11]+1839030562)<<16|r>>>16)+n|0))+a[14]-35309556)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[1]-1530992060)<<4|e>>>28)+t|0))+a[4]+1272893353)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[7]-155497632)<<16|r>>>16)+n|0))+a[10]-1094730640)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[13]+681279174)<<4|e>>>28)+t|0))+a[0]-358537222)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[3]-722521979)<<16|r>>>16)+n|0))+a[6]+76029189)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[9]-640364487)<<4|e>>>28)+t|0))+a[12]-421815835)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[15]+530742520)<<16|r>>>16)+n|0))+a[2]-995338651)<<23|t>>>9)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[0]-198630844)<<6|e>>>26)+t|0)|~r))+a[7]+1126891415)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[14]-1416354905)<<15|r>>>17)+n|0)|~e))+a[5]-57434055)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[12]+1700485571)<<6|e>>>26)+t|0)|~r))+a[3]-1894986606)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[10]-1051523)<<15|r>>>17)+n|0)|~e))+a[1]-2054922799)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[8]+1873313359)<<6|e>>>26)+t|0)|~r))+a[15]-30611744)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[6]-1560198380)<<15|r>>>17)+n|0)|~e))+a[13]+1309151649)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[4]-145523070)<<6|e>>>26)+t|0)|~r))+a[11]-1120210379)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[2]+718787259)<<15|r>>>17)+n|0)|~e))+a[9]-343485551)<<21|t>>>11)+r|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=r-1732584194|0,this.h3=n+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+r|0,this.h3=this.h3+n|0)},t.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[r>>>4&15]+d[15&r]+d[r>>>12&15]+d[r>>>8&15]+d[r>>>20&15]+d[r>>>16&15]+d[r>>>28&15]+d[r>>>24&15]+d[n>>>4&15]+d[15&n]+d[n>>>12&15]+d[n>>>8&15]+d[n>>>20&15]+d[n>>>16&15]+d[n>>>28&15]+d[n>>>24&15]},t.prototype.toString=t.prototype.hex,t.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&r,r>>>8&255,r>>>16&255,r>>>24&255,255&n,n>>>8&255,n>>>16&255,n>>>24&255]},t.prototype.array=t.prototype.digest,t.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},t.prototype.buffer=t.prototype.arrayBuffer,t.prototype.base64=function(){for(var e,t,r,n="",i=this.array(),o=0;o<15;)e=i[o++],t=i[o++],r=i[o++],n+=m[e>>>2]+m[63&(e<<4|t>>>4)]+m[63&(t<<2|r>>>6)]+m[63&r];return e=i[o],n+(m[e>>>2]+m[e<<4&63]+"==")},(r.prototype=new t).finalize=function(){if(t.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();t.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),t.prototype.finalize.call(this)}};var R=function(){var e=_("hex");s&&(e=E(e)),e.create=function(){return new t},e.update=function(t){return e.create().update(t)};for(var r=0;r<h.length;++r){var n=h[r];e[n]=_(n)}return e}();R.md5=R,R.md5.hmac=function(){var e=T("hex");e.create=function(e){return new r(e)},e.update=function(t,r){return e.create(t).update(r)};for(var t=0;t<h.length;++t){var n=h[t];e[n]=T(n)}return e}(),u?e.exports=R:o.md5=R}()}(md5);var md5Exports=md5.exports,builder=getProtobufRoot(SLS_PROTO),LogContentProto=builder.lookupType("sls.Log.Content"),LogGroupProto=builder.lookupType("sls.LogGroup"),encoder=new TextEncoder,getCanonicalizedHeaders=function(e){for(var t=Object.keys(e),r=[],n=0;n<t.length;n++){var i=t[n];(i.startsWith("x-log-")||i.startsWith("x-acs-"))&&r.push(i)}r.sort();for(var o="",a=0;a<r.length;a++){var s=r[a];o+="".concat(s,":").concat(String(e[s]).trim(),"\n")}return o},getCanonicalizedResource=function(e,t){for(var r="".concat(e),n=Object.keys(t),i=new Array(n.length),o=0;o<n.length;o++){var a=n[o];i[o]="".concat(a,"=").concat(t[a]||"")}i.sort();var s=i.join("&");return s&&(r+="?".concat(s)),r},sign=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r,n,i){var o,a,s,c,u,l,d,p,f;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=n["Content-MD5"]||"",a=n["Content-Type"]||"",s=n.Date,c=getCanonicalizedHeaders(n),u=getCanonicalizedResource(t,r),l=encoder.encode(["POST",o,a,s,"".concat(c).concat(u)].join("\n")),e.next=8,window.crypto.subtle.importKey("raw",encoder.encode(i.credentials.accessKeySecret),{name:"HMAC",hash:"SHA-1"},!1,["sign"]);case 8:return d=e.sent,e.t0=Uint8Array,e.next=12,window.crypto.subtle.sign("HMAC",d,l);case 12:return e.t1=e.sent,p=new e.t0(e.t1),f=window.btoa(String.fromCharCode.apply(String,_toConsumableArray$1(p))),e.abrupt("return","LOG ".concat(i.credentials.accessKeyId,":").concat(f));case 16:case"end":return e.stop()}}),e)})));return function(t,r,n,i){return e.apply(this,arguments)}}(),postLog=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,m;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.logstore,a=t.project,s=t.endpoint,c=t.credentials,u="/logstores/".concat(o,"/shards/lb"),l=a?a+".":"",d=(r?"?".concat(new URLSearchParams(r)):"").replace(/\?$/,""),p=window.location.href.indexOf("file://")>-1?"http://":"//",f="".concat(p).concat(l).concat(s.replace(/https?:\/\//,"")).concat(u).concat(d),h=new Date(getTime()).toUTCString(),m={"Content-Type":"application/x-protobuf","x-log-compresstype":"deflate","x-log-bodyrawsize":i,Date:h,Host:"".concat(l).concat(s),"x-log-apiversion":"0.6.0","x-log-signaturemethod":"hmac-sha1",Authorization:"","x-acs-security-token":c.securityToken},n&&(m["Content-MD5"]=md5Exports.md5(n).toUpperCase(),m["Content-Length"]=n.length),e.next=11,sign(u,r,m,t);case 11:return m.Authorization=e.sent,m["x-log-date"]=h,e.abrupt("return",{url:f,param:{method:"POST",body:n,headers:m}});case 14:case"end":return e.stop()}}),e)})));return function(t,r,n,i){return e.apply(this,arguments)}}(),getUploadParam=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r){var n,i,o,a,s,c,u;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=parseInt(String(getTime()).substr(0,10)),o={Logs:[],Topic:"Event Track"},t.forEach((function(e){o.Logs.push({Time:i,Contents:Object.keys(e).map((function(t){var r={Key:t,Value:String(e[t])},n=LogContentProto.verify(r);if(n)throw n;return r}))})})),!(n=LogGroupProto.verify(o))){e.next=7;break}throw new Error(n);case 7:return a=LogGroupProto.create(o),s=LogGroupProto.encode(a).finish(),c=pako.deflate(s),u=s.byteLength,e.next=13,postLog(r,{},c,u);case 13:return e.abrupt("return",e.sent);case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),_excute=function(e,t,r){return new Promise((function(n,i){fetch(e,t).then(n).catch((function(n){++r<=3?setTimeout((function(){_excute(e,t,r)}),500*(r+1)):i(n)}))}))},post=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r){var n,i,o;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,getUploadParam(t,r);case 4:return n=e.sent,i=n.url,o=n.param,e.abrupt("return",_excute(i,o,0));case 8:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),UPLOADTIMER=5e3,UPLOADITEMMAX=10,SlsClient=_createClass((function e(t,r){var n=this;_classCallCheck(this,e),Object.defineProperty(this,"logService",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=t.securityToken,o=t.logService,a=t.cycleStatsConfig;this.logService=o,this.cache=[],this.statsCache=[],this.cycleStatsInterval=a.uploadIntervalMs||UPLOAD_LOG_INTERVAL,this.eventTriggedInterval=UPLOADTIMER,this.tokenManager=new STSTokenManager(i,r,this.logService.credentials),this.tokenManager.on("update",(function(e){n.logService=e})),this.upload(!1,"eventTrigged"),this.cycleStatsTimer=addTimer((function(){n.upload(!0,"cycleStats")}),this.cycleStatsInterval,"interval"),this.eventTriggedTimer=addTimer((function(){n.upload(!1,"eventTrigged")}),this.eventTriggedInterval,"interval")}),[{key:"securityToken",get:function(){var e;return null===(e=this.tokenManager)||void 0===e||null===(e=e.securityToken)||void 0===e?void 0:e.securityToken}},{key:"stopUpdateToken",value:function(){this.tokenManager.stopUpdateToken()}},{key:"send",value:function(e){var t=e.cycleStats;delete e.serverDiffTime,t?(delete e.cycleStats,this.sendStats(e)):this.cache.push(e)}},{key:"sendStats",value:function(e){this.statsCache.push(e)}},{key:"flush",value:function(){this.upload(!0,"eventTrigged"),this.upload(!0,"cycleStats")}},{key:"upload",value:function(){var e;return e="eventTrigged"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"eventTrigged")?arguments.length>0&&void 0!==arguments[0]&&arguments[0]?this.cache.splice(0):this.cache.splice(0,UPLOADITEMMAX):this.statsCache.splice(0),post(e,this.logService)}},{key:"clear",value:function(){this.eventTriggedTimer&&(removeTimer(this.eventTriggedTimer,"interval"),this.eventTriggedTimer=null),this.cycleStatsTimer&&(removeTimer(this.cycleStatsTimer,"interval"),this.cycleStatsTimer=null)}}]),Logging=_createClass((function e(){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slsClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.buffer=[],this.slsClient=null,this.commonInfo={udid:Environment.deviceId,tabId:Environment.browserTabId}}),[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"start",value:function(e){this.slsClient=new SlsClient(e,this.commonInfo),this.flushLogBuffer()}},{key:"stop",value:function(){var e,t;this.flushLogBuffer(),null===(e=this.slsClient)||void 0===e||e.stopUpdateToken(),null===(t=this.slsClient)||void 0===t||t.clear()}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds()),e.acs=Environment.networkType||"unknown",this.commonInfo.apid?(this.realSend(e),this.buffer.length&&this.flushLogBuffer()):this.buffer.push(e)}},{key:"flushLogBuffer",value:function(){var e=this;this.buffer.length&&this.slsClient&&this.buffer.splice(0).forEach((function(t){e.realSend(t)})),this.slsClient&&this.slsClient.flush()}},{key:"realSend",value:function(e){var t=Object.assign({},this.commonInfo,e);this.slsClient&&this.slsClient.send(t)}}]);function ownKeys$1$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$1$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1$1(Object(r),!0).forEach((function(t){_defineProperty$1(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1$1(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var WebTrackingClient=_createClass((function e(t){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.commonInfo=Object.assign({},this.commonInfo,t)}),[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"gslbAccess",value:function(e,t){this.send({event:"gslbAccess",success:e,message:t})}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds());var r=_objectSpread$1$1(_objectSpread$1$1({},this.commonInfo),{},{tm:e.date},e);(new Image).src="".concat(BaseWebTrackingURL,"&").concat(new URLSearchParams(r))}}]);function ownKeys$b(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$b(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$b(Object(r),!0).forEach((function(t){_defineProperty$1(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$b(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var SLSSender=_createClass((function e(){_classCallCheck(this,e),Object.defineProperty(this,"logging",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"started",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logging=new Logging}),[{key:"start",value:function(e){var t=e.cycleStatsConfig;this.logging.start(e),this.statsConfig=t,this.started=!0}},{key:"stop",value:function(){this.logging.stop(),this.started=!1}},{key:"securityToken",get:function(){var e;return null===(e=this.logging)||void 0===e||null===(e=e.slsClient)||void 0===e?void 0:e.securityToken}},{key:"updateSecurityToken",value:function(e){var t;return null===(t=this.logging)||void 0===t?void 0:t.slsClient.tokenManager.updateSecurityToken(e)}},{key:"sendMetric",value:function(e){return this.logging.send(_objectSpread$b(_objectSpread$b({},e),{},{cycleStats:!0}))}},{key:"sendEvent",value:function(e){return this.logging.send(_objectSpread$b({},e))}},{key:"exception",value:function(e){this.logging.send(_objectSpread$b(_objectSpread$b({},TraceEvent$1.EXCEPTION),{},{code:e.code,message:e.message,name:e.name}))}}]),MAX_LOG_COUNT=5e3,ONE_FLUSH_LIMIT=500,ONE_FLUSH_CHAR_COUNT_LIMIT=5e5,LOG_LEVEL_NUM={debug:1,info:10,warn:20,error:30,none:99},Logger=function(){function e(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"logBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metricBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"envInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFlushing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logSendFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"afterPrinter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerPrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"flushLog",{enumerable:!0,configurable:!0,writable:!0,value:(t=_asyncToGenerator(_regeneratorRuntime.mark((function e(){var t,n,i,o,a;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.logBuffer.length||r.isFlushing){e.next=17;break}if(r.isFlushing=!0,t=r.logBuffer.length,r.logBuffer.length>ONE_FLUSH_LIMIT&&(t=ONE_FLUSH_LIMIT),r.logSendFunction){e.next=8;break}return r.isFlushing=!1,e.abrupt("return",Promise.reject("no log sender"));case 8:for(n=r.logBuffer.slice(0,t),i=n.map((function(e){return JSON.stringify(e)})),o=i.length?i.reduce((function(e,t){return e+t.length}),0):0;o>ONE_FLUSH_CHAR_COUNT_LIMIT&&n.length>=2;)n=n.slice(0,n.length/2),i=n.map((function(e){return JSON.stringify(e)})),o=i.length?i.reduce((function(e,t){return e+t.length}),0):0;return o>ONE_FLUSH_CHAR_COUNT_LIMIT&&(console.error("error: truncated logs for flushing log size is too large",n),i=["error: truncated logs for flushing log size is too large"]),a=r.logSendFunction,e.abrupt("return",a(i).then((function(e){e&&e.success&&r.logBuffer.splice(0,t)})).catch((function(e){console.warn("caught flushLogs error",e)})).finally((function(){r.isFlushing=!1})));case 17:return e.abrupt("return",Promise.resolve());case 18:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})}),this.loggerPrefix=n}return _createClass(e,[{key:"getLogger",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(){return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),i={debug:n,info:n,warn:n,error:n};return["debug","info","warn","error"].forEach((function(n){return i[n]=t.log(n,"".concat(e,":"),r)})),i}},{key:"pushToMetricBuffer",value:function(e){this.metricBuffer.length>=MAX_LOG_COUNT?console.error("drop metric for log buffer is full: ",e):this.metricBuffer.push(e)}},{key:"pushToLogBuffer",value:function(e){this.logBuffer.length>=MAX_LOG_COUNT?console.error("drop log for log buffer is full: ",e):this.logBuffer.push(e)}},{key:"log",value:function(t){for(var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.loggerPrefix,i=arguments.length,o=new Array(i>2?i-2:0),a=2;a<i;a++)o[a-2]=arguments[a];var s=[formatToBeijingTime(new Date(getTime())),t.toLocaleUpperCase(),n].concat(o);"none"!==t&&LOG_LEVEL_NUM[t]>=e.levelThreshold&&Function.apply.call(console[t],console,s);var c=this.stringifyArgs(s);null===(r=this.afterPrinter)||void 0===r||r.call(this,c),this.logSendFunction&&this.pushToLogBuffer(c)}},{key:"stringifyArgs",value:function(e){var t=_toConsumableArray$1(e).map((function(e){var t=e;return"string"!=typeof e&&(t=tryJsonStringify(e)),t})).join(" ");return"".concat(t)}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["debug",void 0,""].concat(t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["info",void 0,""].concat(t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["warn",void 0,""].concat(t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["error",void 0,""].concat(t))}},{key:"injectLogSender",value:function(e){this.logSendFunction=e}},{key:"injectLogPrint",value:function(e){this.afterPrinter=e}}],[{key:"setLogLevel",value:function(t){e.levelThreshold=LOG_LEVEL_NUM[t]}}])}();Object.defineProperty(Logger,"levelThreshold",{enumerable:!0,configurable:!0,writable:!0,value:LOG_LEVEL_NUM.warn});var Reporter=_createClass((function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metric",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webtracking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"getLoggerWithPrefix",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var r={debug:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).debug.apply(r,[e].concat(i))},info:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).info.apply(r,[e].concat(i))},warn:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).warn.apply(r,[e].concat(i))},error:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).error.apply(r,[e].concat(i))}};return r}}),this.commonInfo={bt:Environment.browserType,bv:Environment.browserVersion,osn:Environment.system,osv:Environment.systemVersion,udid:Environment.deviceId,tabId:Environment.browserTabId},this.sender=new SLSSender,this.webtracking=new WebTrackingClient(this.commonInfo),this.trace=new Trace(this.webtracking,this.sender),this.metric=new Metric(this.sender),this.log=new Logger,this.setId(r),this.log.injectLogPrint((function(e){t.trace.simpleLogger(e)}))}),[{key:"setId",value:function(e){this.id=e,this.log.loggerPrefix="clientId ".concat(this.id)}},{key:"securityToken",get:function(){return this.sender.securityToken}},{key:"statsConfig",get:function(){return this.sender.statsConfig}},{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e),this.webtracking.updateCommonInfo(this.commonInfo),this.sender.logging.updateCommonInfo(this.commonInfo),e.serverDiffTime&&setDiffTime(e.serverDiffTime)}},{key:"updateSecurityToken",value:function(e){this.sender.updateSecurityToken(e)}},{key:"start",value:function(e){this.sender.start(e)}},{key:"stop",value:function(){this.sender.stop()}}]),clientIdToReportMap=new Map,defaultReport,registerReporter=function(e){var t;return defaultReport?defaultReport&&!defaultReport.id?(defaultReport.setId(e),t=defaultReport):t=new Reporter(e):t=defaultReport=new Reporter(e),clientIdToReportMap.set(e,t),t},getReporter=function(e){return defaultReport||(defaultReport=new Reporter),defaultReport},setLogLevel=function(e){Logger.setLogLevel(e)},_ErrorCodeAndMsgMap,DeviceErrorDescription={MESSAGE_DEVICENOTFOUND:"Requested device not found",MESSAGE_DEVICENOTALLOWED:"Permission denied",MESSAGE_MACCHROMEDEVICENOTREADABLE:"Permission denied by system",MESSAGE_MACSAFARIDEVICENOTALLOWED:"The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",MESSAGE_MOBILEDEVICE_NOTALLOWED:"video device not allowed",MESSAGE_AUDIODEVICENOTREADABLE:"Could not start audio source",MESSAGE_VIDEODEVICENOTREADABLE:"Could not start video source",NAME_ABORTEERROR:"AbortError",NAME_INVALIDSTATEERROR:"InvalidStateError",NAME_DEVICENOTALLOWED:"NotAllowedError",NAME_DEVICENOTFOUND:"NotFoundError",NAME_DEVICENOTREADABLE:"NotReadableError",NAME_DEVICEOVERCONSTRAINED:"OverconstrainedError",NAME_INVALID_ACCESS:"InvalidAccessError",NAME_TYPEERROR:"TypeError"},GSLBErrorCode,ErrorCode;!function(e){e.CLIENT_ERROR_INVALID_AUTHORIZATION="invalid authorization",e.CLIENT_ERROR_NOT_FOUND_APP="app not found",e.CLIENT_ERROR_INVALID_APP_STATUS="invalid app status",e.CLIENT_ERROR_MISSING_CHANNEL_NAME="channel missing",e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP="invalid token timestamp",e.CLIENT_ERROR_INVALID_APP_ID="invalid appId",e.CLIENT_ERROR_MISSING_REQUEST="request missing",e.CLIENT_ERROR_MISSING_DEVICE_ID="deviceId missing",e.CLIENT_ERROR_MISSING_UA="ua missing",e.CLIENT_ERROR_MISSING_CLIENT_IP="clientIp missing",e.CLIENT_ERROR_INVALID_USER_ID="invalid userId",e.CLIENT_ERROR_MISSING_SERVIC="service missing",e.CLIENT_ERROR_MISSING_TASK_ID="taskId missing",e.CLIENT_ERROR_MISSING_APP_ID="appId missing",e.CLIENT_ERROR_MISSING_USER_ID="userId missing",e.CLIENT_ERROR_MISSING_USER="user missing",e.CLIENT_ERROR_MISSING_CHANNEL_ID="channel missing",e.CLIENT_ERROR_MISSING_PARTICIPANT_ID="participantId missing",e.CLIENT_ERROR_INVALID_REQUEST="invalid request",e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL="gslb channel not found",e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR="gslb not found channelId error",e.SERVER_ERROR_INTERNAL_ERROR="internal error",e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR="media-engine access error",e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR="media-engine scheduleAndCreate error",e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR="security token not found error",e.SERVER_ERROR_GSLB_ACCESS_ERROR="gslb access error",e.SERVER_ERROR_GSLB_DISPATCH_ERROR="gslb dispatch error",e.SERVER_ERROR_GSLB_MAPI_ERROR="gslb mapi error"}(GSLBErrorCode||(GSLBErrorCode={})),function(e){e[e.JoinTimeout=16908804]="JoinTimeout",e[e.JoinChannelFailed=16974338]="JoinChannelFailed",e[e.CLIENT_ERROR_INVALID_AUTHORIZATION=33620485]="CLIENT_ERROR_INVALID_AUTHORIZATION",e[e.CLIENT_ERROR_NOT_FOUND_APP=33620481]="CLIENT_ERROR_NOT_FOUND_APP",e[e.CLIENT_ERROR_INVALID_APP_STATUS=33620486]="CLIENT_ERROR_INVALID_APP_STATUS",e[e.JoinBadParam=16974081]="JoinBadParam",e[e.CLIENT_ERROR_MISSING_CHANNEL_NAME=16974081]="CLIENT_ERROR_MISSING_CHANNEL_NAME",e[e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP=33620483]="CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP",e[e.CLIENT_ERROR_INVALID_APP_ID=33620482]="CLIENT_ERROR_INVALID_APP_ID",e[e.CLIENT_ERROR_MISSING_REQUEST=16974081]="CLIENT_ERROR_MISSING_REQUEST",e[e.CLIENT_ERROR_MISSING_CLIENT_IP=16974081]="CLIENT_ERROR_MISSING_CLIENT_IP",e[e.CLIENT_ERROR_INVALID_USER_ID=33622278]="CLIENT_ERROR_INVALID_USER_ID",e[e.CLIENT_ERROR_MISSING_SERVIC=16974081]="CLIENT_ERROR_MISSING_SERVIC",e[e.CLIENT_ERROR_MISSING_TASK_ID=16974081]="CLIENT_ERROR_MISSING_TASK_ID",e[e.CLIENT_ERROR_MISSING_APP_ID=16974081]="CLIENT_ERROR_MISSING_APP_ID",e[e.CLIENT_ERROR_MISSING_USER_ID=16974081]="CLIENT_ERROR_MISSING_USER_ID",e[e.CLIENT_ERROR_MISSING_USER=16974081]="CLIENT_ERROR_MISSING_USER",e[e.CLIENT_ERROR_MISSING_CHANNEL_ID=16974081]="CLIENT_ERROR_MISSING_CHANNEL_ID",e[e.CLIENT_ERROR_MISSING_PARTICIPANT_ID=16974081]="CLIENT_ERROR_MISSING_PARTICIPANT_ID",e[e.CLIENT_ERROR_INVALID_REQUEST=16974082]="CLIENT_ERROR_INVALID_REQUEST",e[e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL=33620484]="CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL",e[e.ServerResponseInvalid=16974354]="ServerResponseInvalid",e[e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR=33620496]="SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR",e[e.SERVER_ERROR_INTERNAL_ERROR=33620497]="SERVER_ERROR_INTERNAL_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR=33620498]="SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR=33620499]="SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR",e[e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR=33620500]="SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR",e[e.SERVER_ERROR_GSLB_ACCESS_ERROR=33622281]="SERVER_ERROR_GSLB_ACCESS_ERROR",e[e.SERVER_ERROR_GSLB_DISPATCH_ERROR=33620501]="SERVER_ERROR_GSLB_DISPATCH_ERROR",e[e.SERVER_ERROR_GSLB_MAPI_ERROR=33620502]="SERVER_ERROR_GSLB_MAPI_ERROR",e[e.MicOpenFail=17040388]="MicOpenFail",e[e.SpeakerOpenFail=17040389]="SpeakerOpenFail",e[e.MicInterrupt=17040390]="MicInterrupt",e[e.SpeakerSetNotSupported=17040416]="SpeakerSetNotSupported",e[e.SpeakerInterrupt=17040391]="SpeakerInterrupt",e[e.MicAuthFail=17040392]="MicAuthFail",e[e.MicNotAvailable=17040393]="MicNotAvailable",e[e.SpeakerNotAvailable=17040400]="SpeakerNotAvailable",e[e.SpecifiedAudioDeviceNotFound=17040401]="SpecifiedAudioDeviceNotFound",e[e.AudioMixingUnknownError=17040896]="AudioMixingUnknownError",e[e.LoadAudioFailed=17040897]="LoadAudioFailed",e[e.AudioMixingStateInvalid=17040898]="AudioMixingStateInvalid",e[e.AudioContextNotSupported=17040899]="AudioContextNotSupported",e[e.NotArrayBuffer=17040900]="NotArrayBuffer",e[e.AudioMixingMissingParam=17040901]="AudioMixingMissingParam",e[e.AudioMixingStartFailed=17040902]="AudioMixingStartFailed",e[e.AudioMixingResumeFailed=17040903]="AudioMixingResumeFailed",e[e.AudioPlayTimeError=17040912]="AudioPlayTimeError",e[e.AutoPlayFailed=17040928]="AutoPlayFailed",e[e.CameraOpenFail=17039620]="CameraOpenFail",e[e.CameraInterrupt=17039622]="CameraInterrupt",e[e.SpecifiedCameraDeviceNotFound=17039623]="SpecifiedCameraDeviceNotFound",e[e.CameraNotAvailable=17039673]="CameraNotAvailable",e[e.CameraAuthFail=17039680]="CameraAuthFail",e[e.ScreenShareOpenFail=17039624]="ScreenShareOpenFail",e[e.VideoDisplayOpenFail=17039873]="VideoDisplayOpenFail",e[e.VideoDisplayInterrupt=17039874]="VideoDisplayInterrupt",e[e.DeviceUnknownError=17040537]="DeviceUnknownError",e[e.OverConstrainedError=17040536]="OverConstrainedError",e[e.ScreenShareUnknownError=17040640]="ScreenShareUnknownError",e[e.ScreenShareNotAllowed=17040641]="ScreenShareNotAllowed",e[e.ScreenShareEnded=17040642]="ScreenShareEnded",e[e.ScreenShareNotAuthed=17040643]="ScreenShareNotAuthed",e[e.ScreenShareInvalidAccess=17040644]="ScreenShareInvalidAccess",e[e.ScreenShareAbortError=17040645]="ScreenShareAbortError",e[e.ScreenShareStateError=17040646]="ScreenShareStateError",e[e.ScreenShareTypeError=17040647]="ScreenShareTypeError",e[e.IceConnectionConnectFail=17105409]="IceConnectionConnectFail",e[e.IceConnectionReconnectFail=17105410]="IceConnectionReconnectFail",e[e.IceConnectionAnswerFail=17105426]="IceConnectionAnswerFail",e[e.IceConnectionNoCandidate=17105427]="IceConnectionNoCandidate",e[e.IceConnectionDisconnected=17105428]="IceConnectionDisconnected",e[e.IceConnectionSetLocalDescFail=17105429]="IceConnectionSetLocalDescFail",e[e.ConnectionHeartbeatTimeout=17105411]="ConnectionHeartbeatTimeout",e[e.ConnectionConnectFail=17105665]="ConnectionConnectFail",e[e.APICallTimeOut=17105681]="APICallTimeOut",e[e.PublishNoStream=16974596]="PublishNoStream",e[e.PublishInvaild=16974597]="PublishInvaild",e[e.PublishNotJoinChannel=16843782]="PublishNotJoinChannel",e[e.PublishAudioStreamFailed=16843856]="PublishAudioStreamFailed",e[e.PublishVideoStreamFailed=16843857]="PublishVideoStreamFailed",e[e.PublishScreenShareFailed=16843859]="PublishScreenShareFailed",e[e.PublishScreenShareConfigError=16843860]="PublishScreenShareConfigError",e[e.SubscribeStreamNotExisted=16974851]="SubscribeStreamNotExisted",e[e.SubscribeInvaild=16974852]="SubscribeInvaild",e[e.SubscribeNotJoinChannel=16844112]="SubscribeNotJoinChannel",e[e.SubscribeAudioStreamFailed=16844113]="SubscribeAudioStreamFailed",e[e.SubscribeVideoStreamFailed=16844114]="SubscribeVideoStreamFailed",e[e.SubscribeScreenShareFailed=16844116]="SubscribeScreenShareFailed",e[e.LogAlreadyInit=16974085]="LogAlreadyInit",e[e.LogRootPathError=16974086]="LogRootPathError",e[e.QuotaLimitExceed=16974096]="QuotaLimitExceed",e[e.BrowserNotSupported=16974101]="BrowserNotSupported",e[e.InvaildState=16974340]="InvaildState",e[e.InvaildArgument=16974083]="InvaildArgument",e[e.SessionRemoved=33620229]="SessionRemoved",e[e.AudioBufferFull=17236225]="AudioBufferFull",e[e.VideoBufferFull=17236226]="VideoBufferFull",e[e.AudioStreamError=17301761]="AudioStreamError",e[e.AudioFileOpenFail=17301762]="AudioFileOpenFail",e[e.AudioFormatNotSupported=17301763]="AudioFormatNotSupported",e[e.UpdateRoleChannel=16908801]="UpdateRoleChannel",e[e.Inner=-1]="Inner"}(ErrorCode||(ErrorCode={}));var ErrorCodeAndMsgMap=(_ErrorCodeAndMsgMap={},_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.SERVER_ERROR_GSLB_ACCESS_ERROR,"GSLB access error"),ErrorCode.CLIENT_ERROR_NOT_FOUND_APP,"AppId is not exist"),ErrorCode.CLIENT_ERROR_INVALID_APP_ID,"AppId is invalid"),ErrorCode.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL,"channel is not exist"),ErrorCode.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP,"channel is invalid"),ErrorCode.CLIENT_ERROR_INVALID_AUTHORIZATION,"token is invalid"),ErrorCode.JoinTimeout,"join timeout"),ErrorCode.JoinBadParam,"join with invalid parameter"),ErrorCode.JoinChannelFailed,"join channel failed"),ErrorCode.CLIENT_ERROR_INVALID_APP_STATUS,"invalid app status"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CLIENT_ERROR_INVALID_USER_ID,"invalid userId"),ErrorCode.CLIENT_ERROR_INVALID_REQUEST,"invalid request"),ErrorCode.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR,"gslb not found channelId error"),ErrorCode.SERVER_ERROR_INTERNAL_ERROR,"internal error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR,"media-engine access error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR,"media-engine scheduleAndCreate error"),ErrorCode.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR,"security token not found error"),ErrorCode.SERVER_ERROR_GSLB_DISPATCH_ERROR,"gslb dispatch error"),ErrorCode.SERVER_ERROR_GSLB_MAPI_ERROR,"gslb mapi error"),ErrorCode.ScreenShareUnknownError,"unknown screenShare error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.ScreenShareNotAllowed,"screenShare not allowned"),ErrorCode.ScreenShareEnded,"screenShare ended"),ErrorCode.ScreenShareNotAuthed,"screenShare no permission"),ErrorCode.ScreenShareInvalidAccess,"screenShare invalid access"),ErrorCode.ScreenShareAbortError,"screenShare abort access"),ErrorCode.ScreenShareStateError,"screenShare state error"),ErrorCode.ScreenShareTypeError,"screenShare type error"),ErrorCode.AutoPlayFailed,"auto play failed"),ErrorCode.OverConstrainedError,"Overconstrained error"),ErrorCode.DeviceUnknownError,"unknown device error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.MicOpenFail,"failed to open audio record device or audio device occupied"),ErrorCode.MicInterrupt,"audio recording error or audio device occupied"),ErrorCode.SpeakerInterrupt,"audio playing error or audio device occupied"),ErrorCode.SpeakerOpenFail,"failed to open playback device"),ErrorCode.SpeakerSetNotSupported,"not support set output device"),ErrorCode.MicAuthFail,"no audio recording permission or audio device occupied"),ErrorCode.MicNotAvailable,"no audio record device found"),ErrorCode.SpeakerNotAvailable,"no audio play device found"),ErrorCode.SpecifiedAudioDeviceNotFound,"specified audio device not found"),ErrorCode.CameraOpenFail,"failed to open camera due to no permission or camera device occupied"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CameraInterrupt,"camera capturing happens error"),ErrorCode.SpecifiedCameraDeviceNotFound,"specified camera device not found"),ErrorCode.VideoDisplayOpenFail,"failed to open render device"),ErrorCode.VideoDisplayInterrupt,"render happens error"),ErrorCode.ScreenShareOpenFail,"failed to start shareScreen"),ErrorCode.CameraNotAvailable,"no camera device found"),ErrorCode.CameraAuthFail,"no camera permission"),ErrorCode.IceConnectionConnectFail,"ICE connection failed"),ErrorCode.IceConnectionAnswerFail,"failed to answer ICE connection"),ErrorCode.IceConnectionDisconnected,"ICE connection disconnected"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.IceConnectionNoCandidate,"ICE connection has no candidates"),ErrorCode.IceConnectionSetLocalDescFail,"failed to set local SDP"),ErrorCode.ConnectionHeartbeatTimeout,"signal heartbeat timeout"),ErrorCode.ConnectionConnectFail,"signal connection failed"),ErrorCode.APICallTimeOut,"api call is timeout"),ErrorCode.IceConnectionReconnectFail,"failed to reconnect ICE connection"),ErrorCode.PublishVideoStreamFailed,"failed to publish video"),ErrorCode.PublishNoStream,"publish stream is not exist\t"),ErrorCode.PublishInvaild,"already unpublish or not publish for now"),ErrorCode.PublishNotJoinChannel,"can not publish before join channel"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.PublishAudioStreamFailed,"failed to publish audio"),ErrorCode.PublishScreenShareFailed,"failed to publish ScreenShare"),ErrorCode.PublishScreenShareConfigError,"failed to publish ScreenShare due to config error"),ErrorCode.SubscribeStreamNotExisted,"subscribe stream is not exist"),ErrorCode.SubscribeInvaild,"already unsubscribe or not subscribe for now"),ErrorCode.SubscribeNotJoinChannel,"can not subscribe before join channel"),ErrorCode.SubscribeAudioStreamFailed,"failed to subscribe audio"),ErrorCode.SubscribeScreenShareFailed,"failed to subscribe ScreenShare"),ErrorCode.SubscribeVideoStreamFailed,"failed to subscribe video"),ErrorCode.AudioMixingUnknownError,"audio mixing unknown error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LoadAudioFailed,"load audio source failed"),ErrorCode.AudioMixingStateInvalid,"invalid audio mixing state"),ErrorCode.AudioContextNotSupported,"audio context is not supported"),ErrorCode.NotArrayBuffer,"source type is not array buffer"),ErrorCode.AudioMixingMissingParam,"audio mixing is missing param"),ErrorCode.AudioMixingStartFailed,"audio mixing start failed"),ErrorCode.AudioMixingResumeFailed,"audio mixing resume failed"),ErrorCode.AudioPlayTimeError,"time out of range"),ErrorCode.QuotaLimitExceed,"task exceed limit"),ErrorCode.InvaildState,"the operation is rejected in current state"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.InvaildArgument,"invalid argument"),ErrorCode.AudioBufferFull,"external audio input buffer is full"),ErrorCode.VideoBufferFull,"external video input buffer is full"),ErrorCode.AudioStreamError,"auido stream has error"),ErrorCode.AudioFileOpenFail,"failed to open audio file"),ErrorCode.AudioFormatNotSupported,"no support the audio format"),ErrorCode.UpdateRoleChannel,"failed to update role"),ErrorCode.BrowserNotSupported,"failed to update role"),ErrorCode.Inner,"sdk internel error occured"),ErrorCode.LogAlreadyInit,"log already init"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LogRootPathError,"log root path error"),ErrorCode.SessionRemoved,"session has been removed"),ErrorCode.ServerResponseInvalid,"Server response invalid")),converToRtcErrorFromGslbCode=function(e,t){return new DingRTCError(ErrorCode[e],ErrorCodeAndMsgMap[e]||GSLBErrorCode[e]||t)},NAME_TYPEERROR=DeviceErrorDescription.NAME_TYPEERROR,NAME_ABORTEERROR=DeviceErrorDescription.NAME_ABORTEERROR,NAME_INVALID_ACCESS=DeviceErrorDescription.NAME_INVALID_ACCESS,NAME_DEVICENOTFOUND=DeviceErrorDescription.NAME_DEVICENOTFOUND,NAME_DEVICENOTALLOWED=DeviceErrorDescription.NAME_DEVICENOTALLOWED,NAME_INVALIDSTATEERROR=DeviceErrorDescription.NAME_INVALIDSTATEERROR,MESSAGE_DEVICENOTFOUND=DeviceErrorDescription.MESSAGE_DEVICENOTFOUND,NAME_DEVICENOTREADABLE=DeviceErrorDescription.NAME_DEVICENOTREADABLE,MESSAGE_DEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_DEVICENOTALLOWED,NAME_DEVICEOVERCONSTRAINED=DeviceErrorDescription.NAME_DEVICEOVERCONSTRAINED,MESSAGE_VIDEODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_VIDEODEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_AUDIODEVICENOTREADABLE,MESSAGE_MOBILEDEVICE_NOTALLOWED=DeviceErrorDescription.MESSAGE_MOBILEDEVICE_NOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_MACSAFARIDEVICENOTALLOWED,MESSAGE_MACCHROMEDEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_MACCHROMEDEVICENOTREADABLE,parseAudioDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.MicNotAvailable);if([MESSAGE_DEVICENOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED].includes(t))return new DingRTCError(ErrorCode.MicAuthFail);if([MESSAGE_MACCHROMEDEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE].includes(t)||r===NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.MicOpenFail);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseVideoDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.CameraNotAvailable);if(t==MESSAGE_DEVICENOTALLOWED||t==MESSAGE_MOBILEDEVICE_NOTALLOWED||t==MESSAGE_MACSAFARIDEVICENOTALLOWED)return new DingRTCError(ErrorCode.CameraAuthFail);if(t==MESSAGE_MACCHROMEDEVICENOTREADABLE||t==MESSAGE_VIDEODEVICENOTREADABLE||r==NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.CameraOpenFail);if(r==NAME_DEVICEOVERCONSTRAINED)return new DingRTCError(ErrorCode.OverConstrainedError);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseScreenShareError=function(e){if(e){var t=e.name,r=e.message;if("ended"==e.type)return new DingRTCError(ErrorCode.ScreenShareEnded);if(NAME_DEVICENOTALLOWED===t)return new DingRTCError(r==MESSAGE_DEVICENOTALLOWED?ErrorCode.ScreenShareNotAllowed:ErrorCode.ScreenShareNotAuthed,r);if(NAME_INVALID_ACCESS===t)return new DingRTCError(ErrorCode.ScreenShareInvalidAccess,r);if(NAME_ABORTEERROR===t)return new DingRTCError(ErrorCode.ScreenShareAbortError,r);if(NAME_INVALIDSTATEERROR===t)return new DingRTCError(ErrorCode.ScreenShareStateError,r);if(NAME_TYPEERROR===t)return new DingRTCError(ErrorCode.ScreenShareTypeError,r);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,r)}return new DingRTCError(ErrorCode.ScreenShareUnknownError,"name: ".concat(e.name," message: ").concat(e.message))};function _callSuper$m(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$m()?Reflect.construct(t,r,_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$m=function(){return!!e})()}var DingRTCError=function(e){function t(e,r){var n;return _classCallCheck(this,t),n=_callSuper$m(this,t,[r=r||ErrorCodeAndMsgMap[e]]),Object.defineProperty(n,"code",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.code=e,n.reason=r,getReporter().trace.exception(n),n}return _inherits(t,_wrapNativeSuper(Error)),_createClass(t)}(),AudioCodec,VideoCodec,AudioSourceInfo,TaskType,NetworkQualityType,SdkType,TerminalType,DropType,PubSubStates,PeerConnectionState,SubPubFailReason,ClientUserStats,VideoProfileType;function _defineProperty(e,t,r){return(t=toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _superPropBase(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf$1(e)););return e}function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=_superPropBase(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},_get.apply(null,arguments)}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(AudioCodec||(AudioCodec={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(VideoCodec||(VideoCodec={})),exports.AudioSourceInfo=void 0,AudioSourceInfo=exports.AudioSourceInfo||(exports.AudioSourceInfo={}),AudioSourceInfo.MIC="mic",AudioSourceInfo.SCREENCAST="screen-cast",AudioSourceInfo.MIXED="mixed",exports.VideoSourceInfo=void 0,function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(exports.VideoSourceInfo||(exports.VideoSourceInfo={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(TaskType||(TaskType={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(NetworkQualityType||(NetworkQualityType={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType||(SdkType={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType||(TerminalType={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(DropType||(DropType={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(PubSubStates||(PubSubStates={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(PeerConnectionState||(PeerConnectionState={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(SubPubFailReason||(SubPubFailReason={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(ClientUserStats||(ClientUserStats={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(VideoProfileType||(VideoProfileType={}));var name="dingrtc",version="3.8.11",description="dingRTC web端 sdk",files=["dist"],main="./dist/index.js",browser="./dist/index.esm.js",types="./dist/index.d.ts",sideEffects=["dist/*"],scripts={doc:"sh ../../scripts/doc.sh",unittest:"node ./node_modules/karma/bin/karma start test/unit/config/karma.config.js",genproto:"pbjs -t static-module -w es6 -o ./src/services/protos/index.js ./src/services/protos/*.proto",proto2ts:"pbts -o ./src/services/protos/index.d.ts ./src/services/protos/index.js","update-proto":"npm run genproto && npm run proto2ts","genproto-json":"pbjs -t json -o ./src/services/protos/index.json ./src/services/protos/*.proto",e2etest:"npx playwright test --ui",e2ecodegen:"npx playwright codegen http://localhost:5174/","build:dev":"env=development app=dingrtc bash ../../scripts/build.sh",build:"env=production app=dingrtc bash ../../scripts/build.sh ","publish:npm":"npm run build && clean-package -c ../../clean-package.prod.js && pnpm publish && clean-package restore && cross-env APP=dingrtc node ../../scripts/uploadSDK.js","publish:tnpm":"npm run build:dev && clean-package -c ../../clean-package.dev.js&& pnpm publish && clean-package restore"},keywords=["web","library"],dependencies={"@dingrtc/shared":"1.1.0","@dingrtc/channel":"1.1.0","sdp-transform":"^2.14.2","webrtc-adapter":"^8.2.3"},overrides={"grunt-jsdoc":{jsdoc:"^4.0.0"},"ink-docstrap":{"sanitize-html":"^2.3.2"}},license="MIT",gitHead="e980464185949aa7edc75803f17e61ede8918021",publishConfig={registry:"https://registry.anpm.alibaba-inc.com"},repository="git@gitlab.alibaba-inc.com:oneRTC/oneRTC.git",pkg={name:name,version:version,description:description,files:files,main:main,browser:browser,types:types,sideEffects:sideEffects,scripts:scripts,keywords:keywords,dependencies:dependencies,overrides:overrides,license:license,gitHead:gitHead,publishConfig:publishConfig,repository:repository},VideoDimensions={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(exports.AudioSourceState||(exports.AudioSourceState={}));var SDK_VERSION=pkg.version,DEFAULT_GSLB_DOMAIN="https://gslb.dingrtc.com",IGNOGRED_VERSION=-999,SIGNAL_CALL_TIMEOUT=1e3,SUB_PUB_TIMEOUT=15e3,NETWORK_QUALITY_TIMEOUT=2e3,METRIC_STATS_INTERVAL=2e3,CREATE_PC_TIMEOUT=4e3,MEDIA_ELEMENT_LABEL_ATTR="rtc-label",STUCK_JUDGE_RECV_BYTES=5e3;JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),Environment.browserType,Environment.browserVersion,Environment.system,Environment.systemVersion;var USER_STATS_SYNC="onertc_state_sync",TRACK_EVENT_NAME="onertc_internal_track_event",_getReporter$b=getReporter(),logger$8=_getReporter$b.log,Support=function(){return _createClass$1((function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=Environment.system,this.browser=Environment.browserType,this.browserVersion=Environment.browserVersion}),[{key:"getSupportedCodec",value:(e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=7,r.createOffer();case 7:if(n=e.sent.sdp){e.next=10;break}return e.abrupt("return",t);case 10:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 24:throw e.prev=24,e.t0=e.catch(1),logger$8.error("get supportedCodecs failed"),new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 28:case"end":return e.stop()}}),e,null,[[1,24]])}))),function(){return e.apply(this,arguments)})},{key:"checkSupported",value:function(){var e=!1;try{var t=window.RTCPeerConnection,r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;e=!!(t&&r&&n)}catch(e){return!1}var i=!1;i=Environment.isChrome()||Environment.isFirefox()?parseInt(Environment.browserVersion,10)>=69:Environment.isOpera()?parseInt(Environment.browserVersion,10)>=45:Environment.isSafari()?parseInt(Environment.browserVersion,10)>=11:(Environment.isWeixin()||Environment.isQQBrowser(),!0);var o=e&&i;return logger$8.debug("checkSystemRequirements, api:",e,"browser",i),o}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(OSType.ANDROID)&&this.system!==OSType.IOS&&(!(this.browser===BrowserType.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===BrowserType.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var e}(),support=new Support,isSupportSimulcast=function(){var e,t=(null===(e=window.RTCRtpSender)||void 0===e?void 0:e.prototype)||{},r=t.setParameters,n=t.getParameters;return!(!r||!n)&&(!Environment.isFirefox()&&(Environment.isSafari()?parseInt(Environment.browserVersion)>=14:Environment.isChrome()?parseInt(Environment.browserVersion)>=81:!Environment.isAndroid()))};function _arrayLikeToArray$d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$d(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$d(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$d(e,t);var r={}.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)?_arrayLikeToArray$d(e,t):void 0}}function _nonIterableSpread(){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 _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$d(e)||_nonIterableSpread()}function _callSuper$l(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$l()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$l=function(){return!!e})()}var _getReporter$a=getReporter(),logger$7=_getReporter$a.log,ClientConfig=function(e){function t(){var e;return _classCallCheck$1(this,t),e=_callSuper$l(this,t),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:isSupportSimulcast()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e.setClientConfig({gslb:[DEFAULT_GSLB_DOMAIN]}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"setClientConfig",value:function(e){logger$7.info("setClientConfig",e);var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU,o=t.republish,a=t.disableTransportCC;"string"==typeof r&&(this.gslb=[r],setGslb(r)),Array.isArray(r)&&isString(r[0])&&(this.gslb=r,setGslb(r[0])),null!=n&&isSupportSimulcast()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i)),null!=a&&(this.disableTransportCC=Boolean(a)),null!=o&&(this.republish=Boolean(o))}}])}(EventEmitter),clientConfig=new ClientConfig,sortResolutions=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},getResolutions=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,_toConsumableArray(i.parameters.resolution)),n.sort(sortResolutions),n},parseSubscribeError=function(e,t){var r,n=e.media,i=n.audio,o=n.video;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if(i)r=new DingRTCError(ErrorCode.SubscribeAudioStreamFailed,t);else if(o){var a=o.source;a===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.SubscribeVideoStreamFailed,t):a===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.SubscribeScreenShareFailed,t))}return r},parsePublishError=function(e,t){var r,n=e.trackMediaType;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if("audio"===n)r=new DingRTCError(ErrorCode.PublishAudioStreamFailed,t);else{var i=e.source;i===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.PublishVideoStreamFailed,t):i===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.PublishScreenShareFailed,t))}return r},updateRemoteTrack=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?clientConfig.audioSFU?n?n.replaceStream(e):i=new RemoteAudioTrack(null,r,e):n?n.replaceTrack(a[0]):i=new RemoteAudioTrack(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new RemoteVideoTrack(o[0],r)),i},isScreenCast=function(e){return"object"===_typeof$3(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function ownKeys$a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$a(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$a(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$c(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$c(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$c(e,t);var r={}.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)?_arrayLikeToArray$c(e,t):void 0}}function _arrayLikeToArray$c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$k(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$k()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$k(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$k=function(){return!!e})()}var _getReporter$9=getReporter(),logger$6=_getReporter$9.log,DeviceManager=function(e){function t(){var e,r;return _classCallCheck$1(this,t),e=_callSuper$k(this,t),Object.defineProperty(e,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function r(){var n;return _regeneratorRuntime$1.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=2;break}return r.abrupt("return");case 2:return e.checking=!0,r.next=5,t.getDevices();case 5:n=r.sent,e.compareDevices(n,"audiooutput"),e.compareDevices(n,"videoinput"),e.compareDevices(n,"audioinput"),e.deviceList=n,e.checking=!1;case 11:case"end":return r.stop()}}),r)}))),function(){return r.apply(this,arguments)})}),Object.defineProperty(e,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(t,r){var n,i=t.filter((function(e){return e.kind===r})),o=e.deviceList.filter((function(e){return e.kind===r})),a=i.map((function(e){return e.deviceId})),s=o.map((function(e){return e.deviceId})),c=i.filter((function(e){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),l={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},d=_createForOfIteratorHelper$c(c);try{for(d.s();!(n=d.n()).done;){var p=n.value;e.emit(l[r],{device:p,state:"active"})}}catch(e){d.e(e)}finally{d.f()}var f,h=_createForOfIteratorHelper$c(u);try{for(h.s();!(f=h.n()).done;){var m=f.value;e.emit(l[r],{device:m,state:"inactive"})}}catch(e){h.e(e)}finally{h.f()}}}),t._instance?_possibleConstructorReturn$1(e,t._instance):(e.deviceList=[],support.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).then((function(t){e.deviceList=t,e.addEventListeners()})),e):_possibleConstructorReturn$1(e))}return _inherits$1(t,e),_createClass$1(t,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):addTimer(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return t._instance}},{key:"getMedias",value:function(e,t){var r,n,i=this;return isScreenCast(e)?(logger$6.info("getDisplayMedia with",t),null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t)):(logger$6.info("getUserMedia with",t),null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t})))}},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(n,i){var o;if(null!==(o=navigator.mediaDevices)&&void 0!==o&&o.enumerateDevices){var a=!1;t.audio&&t.video?a=e.audioPermitted&&e.videoPermitted:t.audio?a=e.audioPermitted:t.video&&(a=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(o){var s=o.filter((function(e){return e.deviceId})),c=s.filter((function(e){return"videoinput"===e.kind})),u=s.filter((function(e){return"audioinput"===e.kind})),l=s.filter((function(e){return"audiooutput"===e.kind})),d=[];t.audio&&(d=d.concat(u,l)),t.video&&(d=d.concat(c)),0!==d.length||a||r?d.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(d)):n(d):(logger$6.info("getUserMedia with",t),navigator.mediaDevices.getUserMedia(t).then((function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){n(e)}),i)}),i)),n(s)}))}else i(new DingRTCError(ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}(EventEmitter);Object.defineProperty(DeviceManager,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new DeviceManager}),Object.defineProperty(DeviceManager,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(e){throw parseAudioDeviceError(e)}))}}),Object.defineProperty(DeviceManager,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({video:!0}).then((function(e){return logger$6.info("getCameras",e),e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return _objectSpread$a(_objectSpread$a({},r),{},{toJSON:function(){return r}})}))})).catch((function(e){throw logger$6.error("getCameras error",e),parseVideoDeviceError(e)}))}}),Object.defineProperty(DeviceManager,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then((function(e){return logger$6.info("getMicrophones",e),e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(e){throw logger$6.error("getMicrophones error",e),parseAudioDeviceError(e)}))}});var parseVideoDimension=function(e){return{width:VideoDimensions[e][0],height:VideoDimensions[e][1]}},addAudioTrackAttribute=function(e){var t,r=Object.create({}),n={};null!==(t=navigator)&&void 0!==t&&null!==(t=t.mediaDevices)&&void 0!==t&&t.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var i=e.AEC,o=e.AGC,a=e.ANS;return e.deviceId&&(Environment.isSafari()?r.deviceId=e.deviceId:r.deviceId={exact:e.deviceId}),n.autoGainControl&&(r.autoGainControl={ideal:null==o||o}),n.echoCancellation&&(r.echoCancellation={ideal:null==i||i}),n.noiseSuppression&&(r.noiseSuppression={ideal:null==a||a}),r},createMediaStream=function(e){if(!isObject(e)||!e.audio&&!e.video)return Promise.reject(new TypeError("Invalid constrains"));var t=e.audio,r=e.video;if(!isScreenCast(e)&&"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(isScreenCast(e)&&"object"===_typeof$3(t)&&t.source!==exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!t&&!r)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n=Object.create({});if("object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.MIC||"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST?n.audio=addAudioTrackAttribute(t):n.audio=e.audio,"object"===_typeof$3(r)){var i,o=r.frameRate,a=r.deviceId,s=r.source,c=r.facingMode,u=r.displaySurface,l=r.dimension;n.video=Object.create({}),isNumber(o)&&(n.video.frameRate=Math.min(r.frameRate,30)),l&&(i=parseVideoDimension(l)),i&&i.width&&i.height&&(s===exports.VideoSourceInfo.SCREENCAST||Environment.isFirefox()?(n.video.width=i.width,n.video.height=i.height):(n.video.width={ideal:i.width,max:i.width},n.video.height={ideal:i.height,max:i.height})),isString(a)&&a&&(n.video.deviceId={exact:a}),s===exports.VideoSourceInfo.SCREENCAST&&(Environment.isFirefox()&&(n.video.mediaSource="screen"),u&&["browser","window","monitor"].includes(u)&&(n.video.displaySurface=u)),c&&["user","environment"].includes(c)&&(n.video.facingMode=c)}else n.video=r;return DeviceManager.getMedias(e,n)},_this=void 0,getPlainMediaTrackInfo=function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t},getPlainMediaStreamInfo=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map((function(e){return getPlainMediaTrackInfo(e)}));return t.trackInfos=r,t},isVideoStreamPlayable=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},getDeltaDurationInSeconds=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},transNativeAndWebNetworkRank=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},getDelta=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},tryTimes=function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.resolve,a=e.reject;if(!(r>0))throw new Error("invalid params times");var s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var n,s;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=0;case 1:if(!(s<r)){e.next=22;break}return e.prev=2,e.next=5,t();case 5:return n=e.sent,null==o||o(n),e.abrupt("break",22);case 10:if(e.prev=10,e.t0=e.catch(2),s!==r-1){e.next=17;break}return null==a||a(e.t0),e.abrupt("return",e.t0);case 17:return e.next=19,asyncDelayMs(i);case 19:s++,e.next=1;break;case 22:return e.abrupt("return",n);case 23:case"end":return e.stop()}}),e,null,[[2,10]])})));return function(){return e.apply(this,arguments)}}();return s()},asyncDelayMs=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=3;break}return e.next=3,new Promise((function(e){setTimeout(e,t)}));case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),taskQueue=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime=function(e){return new Promise((function(t){addTimer(t,1e3*e)}))},debounce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=null,i=0;return function(){for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];var c=Date.now();c-i>=t&&r?(e.apply(_this,a),i=c):(n&&clearTimeout(n),n=setTimeout((function(){e.apply(_this,a),i=c}),t))}},_getReporter$8=getReporter(),logger$5=_getReporter$8.log,MEDIA_ELEMENT_INTERSECTING_ATTR="rtc-intersecting",MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES={visible:"visible",invisible:"invisible"},MEDIA_ELEMENT_EVENT_NAMES=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],MEDIA_PLAYBACK_CHECK_PERIOD_MS=4e3,getLabel=function(e){return"".concat(null==e?void 0:e.getAttribute(MEDIA_ELEMENT_LABEL_ATTR),"-").concat(null==e?void 0:e.rtcPurpose)},isVideoTagIntersectingVisible=function(e){return e&&e.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR)===MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible},MediaElementPool=function(){return _createClass$1((function e(t,r){var n=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new Debouncer}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse)).forEach((function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject;if(t.error){var i="".concat(e,": ").concat(getLabel(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=getPlainMediaStreamInfo(r);logger$5.debug(i,o),"visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load()}if(t.paused){var a=!1;if(n.hasActivated&&"video"===n.mediaKind?isVideoTagIntersectingVisible(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(getLabel(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR),", mediaStream="),c=getPlainMediaStreamInfo(r);logger$5.error(s,c),isVideoStreamPlayable(r)&&t.load(),t.paused&&t.play().catch((function(e){console.error("inPoll",e)}))}}}})),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&!0!==(null==i?void 0:i.muted)){var o="".concat(e,": ").concat(getLabel(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=getPlainMediaStreamInfo(r);return logger$5.error(o,a),void("visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load())}n.currentTimeOfLastCheckMap.set(t,t.currentTime)}}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$5.error(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$5.debug(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject);logger$5.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse));if(!n.hasActivated&&(n.hasActivated=!0,e.forEach((function(e){e.load()})),n._activatedListener))try{n._activatedListener()}catch(e){logger$5.error("error occurred when exec activatedListener",tryJsonStringify(e))}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver((function(e){e.forEach((function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible):null===(r=e.target)||void 0===r||r.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.invisible)}))})));for(var i=0;i<r;i++){var o,a=this._createElement();null===(o=this.observer)||void 0===o||o.observe(a),this.addAtttribute(a),a.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"".concat(t,"-").concat(i)),this.mediaElementPool.push(a),this.allElements.add(a)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=addTimer((function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")}),MEDIA_PLAYBACK_CHECK_PERIOD_MS,"interval")}),[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?(this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||""):(t=document.createElement(this.mediaKind),this.addAtttribute(t)),t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter((function(t){return t!==e})),t.length!==this.mediaElementsInUse.length&&(this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(){var e,t=document.createElement(this.mediaKind);return null===(e=this.observer)||void 0===e||e.observe(t),t}},{key:"_resetMediaElement",value:function(e){MEDIA_ELEMENT_EVENT_NAMES.forEach((function(t){e["on".concat(t)]=null})),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),audioElementMgr,videoElementMgr,getAudioElementPool=function(){return audioElementMgr||initMediaElementPool(),audioElementMgr},getVideoElementPool=function(){return videoElementMgr||initMediaElementPool(),videoElementMgr},INIT_AUDIO_TAG_COUNT=2,INIT_VIDEO_TAG_COUNT=Environment.isIOS()||Environment.isAndroid()?9:25,initMediaElementPool=function(){audioElementMgr||(audioElementMgr=new MediaElementPool("audio",INIT_AUDIO_TAG_COUNT)),videoElementMgr||(videoElementMgr=new MediaElementPool("video",INIT_VIDEO_TAG_COUNT))},audioContext=new AudioContext,getAudioContext=function(){return audioContext},mergeAudioTracks=function(e){var t=e.getAudioTracks(),r=audioContext.createMediaStreamDestination();return t.forEach((function(e){audioContext.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},playVideo=function(e,t,r){var n=getVideoElementPool().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n},playAudio=function(e){var t=getAudioElementPool().popElement();return t.srcObject=e,t},getAudioVolumeLevel=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},getCurrentFrame=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},audioElementPool=getAudioElementPool(),videoElementPool=getVideoElementPool(),_getReporter$7=getReporter(),log=_getReporter$7.log,PlayerManager=function(){return _createClass$1((function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(e,t,r){var n,i=this,o=e.getTrackId(),a=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var s,c=this.findDom(t);if(!c)throw new DingRTCError(ErrorCode.InvaildArgument,"wrapper dom not found");var u=r||{},l=u.mirror,d=u.fit;if((n=this.players.find((function(e){return e.container===t})))&&(null===(s=n.track)||void 0===s?void 0:s.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stop(n.track,t),void this.play(e,t,r);n?(n.element.pause(),!e.sourceMirror!=!l?n.element.style.transform="scaleX(-1)":n.element.style.transform="",d&&(n.element.style.objectFit=d),n.element.srcObject=a,n.element.load()):((n={container:t,track:e,playerConfig:r}).element=playVideo(c,a,{mirror:!e.sourceMirror!=!l,fit:d}),this.players.push(n))}else(n=this.players.find((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})))?(n.element.pause(),n.element.srcObject=a,n.element.load()):((n={track:e}).element=playAudio(a),this.players.push(n));n.element.paused&&n.element.play().then((function(){n.isPlaying=!0})).catch((function(e){"NotAllowedError"===e.name?(log.error("autoplay failed",tryJsonStringify(e)),EventBus.emit("autoplay-failed",i)):log.warn("".concat(o," play has exception"),tryJsonStringify(e))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?audioElementPool.pushElement(t.element):videoElementPool.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),player$3=new PlayerManager,getPlayer=function(){return player$3};function _callSuper$j(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$j()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$j(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$j=function(){return!!e})()}function _superPropGet$4(e,t,r,n){var i=_get(_getPrototypeOf$1(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var _getReporter$6=getReporter(),simpleLogger$2=_getReporter$6.log,trace=_getReporter$6.trace,logger$4=simpleLogger$2,player$2=getPlayer(),Track=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$j(this,t),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:trace}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e?(n.trackMediaType=e.kind,n.trackSettings=e.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.audioContext=getAudioContext(),n.analyser=n.audioContext.createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(createUuid(6)),n.setMediaStreamTrack(e,r),n}return _inherits$1(t,e),_createClass$1(t,[{key:"isPlaying",get:function(){return player$2.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return logger$4.info("track emit event",e,null==n?void 0:n[0]),_superPropGet$4(t,"emit",this,3)([e].concat(n))}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var i;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(i=this.audioContext)||void 0===i?void 0:i.createMediaStreamSource(new MediaStream([e]));else if(t){var o,a=mergeAudioTracks(t);this.sourceNode=null===(o=this.audioContext)||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([a]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===exports.VideoSourceInfo.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===exports.AudioSourceInfo.MIC?new DingRTCError(ErrorCode.MicInterrupt):r.source===exports.VideoSourceInfo.CAMERA&&new DingRTCError(ErrorCode.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){simpleLogger$2.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(TRACK_EVENT_NAME,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===exports.VideoSourceInfo.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===exports.AudioSourceInfo.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){simpleLogger$2.info("stop paly track ".concat(this.getTrackId())),player$2.stop(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.element,n=e.config;e.updated?player$2.getPlayInfos(this).forEach((function(e){e.container?player$2.findDom(e.container)?player$2.play(t,e.container,e.playerConfig):player$2.stop(t,e.container):player$2.play(t,e.container,e.playerConfig)})):player$2.play(this,r,n);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(e){simpleLogger$2.debug("resume audioContext failed: ".concat(tryJsonStringify(e)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}(EventEmitter),ResolutionProfile;function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$d(e,t)||_nonIterableRest()}function ownKeys$9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$9(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$9(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$9(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(ResolutionProfile||(ResolutionProfile={}));var ResolutionProfileMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},ResolutionProfile.LLD,"lld"),ResolutionProfile.LD,"ld"),ResolutionProfile.SD,"sd"),ResolutionProfile.HD,"hd"),ResolutionProfile.FHD,"fhd"),ResolutionProfile.QHD,"qhd"),ResolutionRange={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},getResolutionLevel=function(e,t){var r={high:VideoProfileType.QHD,low:VideoProfileType.LD,QHD:VideoProfileType.QHD,FHD:VideoProfileType.FHD,HD:VideoProfileType.HD,SD:VideoProfileType.SD,LD:VideoProfileType.LD},n=r[e]||VideoProfileType.None,i=ResolutionRange[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(ResolutionRange).find((function(e){var t=_slicedToArray(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[_slicedToArray(a,1)[0]]}return n},is2K=function(e){return 2560===e.width&&1440===e.height},getResolutionInfo=function(e,t){return{resolution:getResolution(e,t),resolutionLevel:getResolutionLevel(e,t)}},getStreamTypeByResolutionLevel=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},getResolution=function(e,t){var r=ResolutionRange[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&is2K(i))return i;if(t[0].width*t[0].height>ResolutionRange.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},DefaultVideoMaxPixelCount=[49152,76800,307200,1228800,2764800,4915200],DefaultMaxBitrateKbps=[200,350,1e3,1800,2828,5600],DefaultResolution_16_9=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],DefaultResolution_4_3=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],getVideoProfile=function(e,t){var r=ResolutionProfile.FHD,n=e*t;return n<=DefaultVideoMaxPixelCount[ResolutionProfile.LLD]?r=ResolutionProfile.LLD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.LD]?r=ResolutionProfile.LD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.SD]?r=ResolutionProfile.SD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.HD]?r=ResolutionProfile.HD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.FHD]?r=ResolutionProfile.FHD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.QHD]&&(r=ResolutionProfile.QHD),r},getTargetResolution=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=DefaultResolution_16_9[r][0],o=DefaultResolution_16_9[r][1];else if(4*t==3*e)i=DefaultResolution_4_3[r][0],o=DefaultResolution_4_3[r][1];else{var s=Math.sqrt(1*DefaultResolution_16_9[r][0]*DefaultResolution_16_9[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},getVideoMaxbitrate=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=DefaultMaxBitrateKbps[getVideoProfile(e,t)];n=Math.round(Math.max(i*o,50))}return n},getDownByScales=function(e,t){var r=getVideoProfile(e,t),n=function(n){var i=_slicedToArray(getTargetResolution(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(ResolutionProfile.LD),sd:n(ResolutionProfile.SD),fhd:n(r)}},getVideoSenderEncodings=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=getVideoProfile(t,r),s=[],c=a>=ResolutionProfile.HD?3:2,u=function(e){var o=_slicedToArray(getTargetResolution(t,r,e,a),2),s=o[0],c=o[1],u=DefaultMaxBitrateKbps[e]/DefaultMaxBitrateKbps[a],l=1/(c/r);return{targetWidth:s,rid:ResolutionProfileMap[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:l}};a>ResolutionProfile.LLD&&s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,ResolutionProfile.LLD)===o},u(ResolutionProfile.LLD))),a>ResolutionProfile.LD&&s.push(_objectSpread$9({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,ResolutionProfile.LD)===o},u(ResolutionProfile.LD))),a>ResolutionProfile.SD&&s.push(_objectSpread$9({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,ResolutionProfile.SD)===o},u(ResolutionProfile.SD))),a===ResolutionProfile.FHD?(s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:!1},u(ResolutionProfile.HD))),s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:clientConfig.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(ResolutionProfile.FHD)))):s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var l=0,d=0;d<s.length;++d)0!=d&&(s[d].minBitrate=l),l=Math.round(Math.max((s[d].maxBitrate+s[d].minBitrate)/2,s[d].maxBitrate-400));return s.shift(),s},getHighestResolutionLevel=function(e,t){var r=getVideoProfile(e,t),n=Math.pow(2,r);return console.log(n,r),n},getVideoBitrateMap=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!clientConfig.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST||is2K({width:i,height:o}),c={resolutionLevel:getHighestResolutionLevel(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:clientConfig.republish?c.encodings=getVideoSenderEncodings({width:1920,height:1080,frameRate:30,maxBitrate:getVideoMaxbitrate(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=getVideoSenderEncodings({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function ownKeys$8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$8(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$8(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$8(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$i(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$i()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$i=function(){return!!e})()}function _superPropGet$3(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var player$1=getPlayer(),_getReporter$5=getReporter(),logger$3=_getReporter$5.log,LocalTrack=function(e){function t(e,r){var n;if(_classCallCheck$1(this,t),n=_callSuper$i(this,t,[e]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var i,o=e.muted;if(n.muted=o,!r)r=null===(i=e.getSettings())||void 0===i?void 0:i.deviceId}return n.enabled=!0,n.deviceId=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;_superPropGet$3(t,"setMediaStreamTrack",this)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(e){return logger$3.info("setEnabled",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.enabled=e,this.emit(TRACK_EVENT_NAME,e?"unmute":"mute"),e?this.updateNewTrack():(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),Promise.resolve()));var t}},{key:"close",value:function(){var e;logger$3.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(TRACK_EVENT_NAME,"stop"),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.audioContext&&(this.sourceNode=null,this.analyser=null,this.audioContext=null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return logger$3.info("setMuted",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(TRACK_EVENT_NAME,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return logger$3.debug("gengrate new audioTrack"),new Promise((function(t,r){var n;createMediaStream({audio:_objectSpread$8(_objectSpread$8({source:e.source},e.config),{},{deviceId:e.deviceId})}).then((function(e){n=e.getAudioTracks()[0]})).catch((function(t){try{var i=e.audioContext.createOscillator(),o=e.audioContext.createMediaStreamDestination();i.connect(o),n=o.stream.getAudioTracks()[0]}catch(e){logger$3.error("gengrate new audioTrack error",parseAudioDeviceError(t)),r(parseAudioDeviceError(t))}})).finally((function(){n&&t(n)}))}))}},{key:"getVideoTrack",value:function(){var e=this;return logger$3.info("gengrate new videoTrack"),new Promise((function(t,r){var n,i=_objectSpread$8({source:e.source},e.config);e.config.deviceId&&(i.deviceId=e.config.deviceId),e.config.facingMode&&e.config.deviceId&&(logger$3.info("ignore did param to create videoTrack because facingMode is",e.config.facingMode),delete i.deviceId),createMediaStream({video:i,audio:!1}).then((function(e){n=e.getVideoTracks()[0],t(n)})).catch((function(e){logger$3.error("gengrate new videoTrack error",parseVideoDeviceError(e)),r(parseVideoDeviceError(e))}))}))}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,logger$3.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof CameraVideoTrack)||"user"!==t&&"environment"!==t){e.next=7;break}this.config.facingMode=t,e.next=10;break;case 7:if(this.deviceId!==t){e.next=9;break}return e.abrupt("return");case 9:this.deviceId=t;case 10:return e.abrupt("return",this.updateNewTrack());case 11:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(logger$3.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(Track),LocalVideoTrack=function(e){function t(e,r,n){var i;if(_classCallCheck$1(this,t),(i=_callSuper$i(this,t,[e,r])).config=n,e){var o=e.getSettings(),a=o.width,s=o.height;i.maxBitrate=getVideoMaxbitrate(a,s,n.frameRate,n.maxBitrate)}return i}return _inherits$1(t,e),_createClass$1(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(e){var t=this;logger$3.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),e);var r=e.dimension,n=e.frameRate,i=e.maxBitrate,o=e.optimizationMode,a=e.mirror;if(n&&Number.isNaN(n))return Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid frameRate"));if(r&&!VideoDimensions[r])return Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid dimension"));!a!=!this.config.mirror&&(this.emit(TRACK_EVENT_NAME,"mirror",a),this.config.mirror=a),o&&o!==this.optimizationMode&&(this.config.optimizationMode=o,this.emit(TRACK_EVENT_NAME,"optimizationMode"));var s=!1;if(r&&this.config.dimension!==r&&(this.config.dimension=r,s=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),s=!0),i&&this.maxBitrate!==i&&(s=!0),!s)return Promise.resolve();var c=_objectSpread$8({frameRate:this.config.frameRate},parseVideoDimension(this.config.dimension)),u=this.getMediaStreamTrack();return null==u?void 0:u.applyConstraints(c).then((function(){var e,r=null===(e=t.getMediaStreamTrack())||void 0===e?void 0:e.getSettings(),n=r.width,o=r.height;t.maxBitrate=getVideoMaxbitrate(n,o,t.config.frameRate,i),console.log(n,o,c,t.maxBitrate),t.emit(TRACK_EVENT_NAME,"republish",t)})).catch((function(e){var r=parseVideoDeviceError(e);throw logger$3.error("videoTrack ".concat(t.getTrackId()," setEncoderConfiguration error"),r),r}))}},{key:"getCurrentFrameData",value:function(){return logger$3.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:getCurrentFrame(player$1.getElement(this)[0])}},{key:"play",value:function(e,r){return logger$3.info("local video play"),_superPropGet$3(t,"play",this)([e,r])}}])}(LocalTrack),LocalAudioTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$i(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||player$1.getElement(this)[0]&&(player$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return player$1.getElement(this)[0]?player$1.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:getAudioVolumeLevel(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return logger$3.info("local audio play"),_superPropGet$3(t,"play",this)([])}}])}(LocalTrack),CameraVideoTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$i(this,t,[e,r.deviceId,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return _inherits$1(t,e),_createClass$1(t)}(LocalVideoTrack),MicrophoneAudioTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$i(this,t,[e,(r||{}).deviceId])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=n.audioContext.createAnalyser(),n}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||player$1.getElement(this)[0]&&(player$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return player$1.getElement(this)[0]?player$1.getElement(this)[0].volume:void 0}}])}(LocalAudioTrack),createMicrophoneAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l,d;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAudioTrack",t),r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,u=void 0===c||c,e.prev=3,e.next=6,createMediaStream({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:exports.AudioSourceInfo.MIC,AEC:o,AGC:s,ANS:u}});case 6:return l=e.sent,d=l.getAudioTracks()[0],logger$3.info("MicrophoneAudioTrack created"),e.abrupt("return",new MicrophoneAudioTrack(d,Object.assign({},t,{AEC:o,AGC:s,ANS:u})));case 12:throw e.prev=12,e.t0=e.catch(3),parseAudioDeviceError(e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,12]])})));return function(t){return e.apply(this,arguments)}}(),createCameraVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createCameraVideoTrack",t),r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=3,e.next=6,createMediaStream({video:{deviceId:r,source:exports.VideoSourceInfo.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 6:return u=e.sent,l=u.getVideoTracks()[0],logger$3.info("CameraVideoTrack created"),e.abrupt("return",new CameraVideoTrack(l,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 12:throw e.prev=12,e.t0=e.catch(3),parseVideoDeviceError(e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,12]])})));return function(t){return e.apply(this,arguments)}}(),createScreenVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoTrack",t),r=t.displaySurface,n=void 0===r?"monitor":r,i=t.dimension,o=void 0===i?"VD_1920x1080":i,a=t.optimizationMode,s=void 0===a?"detail":a,c=Math.min(t.frameRate||5,30),e.prev=3,e.next=6,createMediaStream({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:n,frameRate:c,dimension:o},audio:!1});case 6:return u=e.sent,(l=new LocalVideoTrack(u.getVideoTracks()[0],null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(exports.VideoSourceInfo.SCREENCAST),logger$3.info("ScreenVideoTrack created"),e.abrupt("return",[l]);case 13:throw e.prev=13,e.t0=e.catch(3),parseScreenShareError(e.t0);case 16:case"end":return e.stop()}}),e,null,[[3,13]])})));return function(t){return e.apply(this,arguments)}}(),createMicrophoneAndCameraTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAndCameraTracks",t,r),n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,l={AEC:!0,AGC:!0,ANS:!0},p=(d=r||l).AEC,f=void 0===p||p,h=d.AGC,m=void 0===h||h,g=d.ANS,v=void 0===g||g,e.prev=5,e.next=8,createMediaStream({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:f,AGC:m,ANS:v}});case 8:return y=e.sent,b=y.getVideoTracks()[0],S=y.getAudioTracks()[0],logger$3.info("CameraVideoTrack and MicrophoneTrack created"),_=new CameraVideoTrack(b,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),E=new MicrophoneAudioTrack(S,Object.assign({},Object.assign({},r,{AEC:f,AGC:m,ANS:v}))),e.abrupt("return",[_,E]);case 17:throw e.prev=17,e.t0=e.catch(5),parseVideoDeviceError(e.t0);case 20:case"end":return e.stop()}}),e,null,[[5,17]])})));return function(t,r){return e.apply(this,arguments)}}(),createCustomVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("createCustomVideoTrack",t),n=(r=t||{}).mediaStreamTrack,i=r.dimension,o=void 0===i?"VD_640x480":i,a=r.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(t.frameRate||15,30),n instanceof MediaStreamTrack&&"video"===n.kind){e.next=5;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 5:return(u=new LocalVideoTrack(n,null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(exports.VideoSourceInfo.CAMERA),e.abrupt("return",u);case 8:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),createCustomAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("createCustomAudioTrack",t),(r=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===r.kind){e.next=4;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 4:return(n=new LocalAudioTrack(r)).setSource(exports.AudioSourceInfo.MIC),e.abrupt("return",n);case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function _superPropGet$2(e,t,r,n){var i=_get(_getPrototypeOf$1(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function _callSuper$h(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$h()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$h=function(){return!!e})()}var _getReporter$4=getReporter(),simpleLogger$1=_getReporter$4.log,player=getPlayer(),RemoteTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$h(this,t,[e,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return _inherits$1(t,e),_createClass$1(t,[{key:"getUserId",value:function(){return simpleLogger$1.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(Track),RemoteAudioTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$h(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return _inherits$1(t,e),_createClass$1(t,[{key:"getMediaStreamTrack",value:function(){return clientConfig.audioSFU?mergeAudioTracks(this.sfuStream):_superPropGet$2(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){simpleLogger$1.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){simpleLogger$1.info("setVolume",e),player.getElement(this)[0]&&(player.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(simpleLogger$1.info("getVolume"),player.getElement(this)[0])return player.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return simpleLogger$1.info("setSpeaker",e),new Promise((function(r,n){var i,o=player.getElement(t)[0];o||n(new DingRTCError(ErrorCode.InvaildState,"please playout audio first")),o.setSinkId||n(new DingRTCError(ErrorCode.SpeakerSetNotSupported)),null===(i=o.setSinkId)||void 0===i||i.call(o,e).then((function(){t.deviceId=e,r()})).catch((function(e){n(parseAudioDeviceError(e))}))}))}},{key:"getVolumeLevel",value:function(){return getAudioVolumeLevel(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return simpleLogger$1.info("remote audio play"),_superPropGet$2(t,"innnerPlay",this,3)([{}])}}])}(RemoteTrack),RemoteVideoTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$h(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"play",value:function(e,r){return simpleLogger$1.info("remote video play"),_superPropGet$2(t,"innnerPlay",this,3)([{element:e,config:r}])}},{key:"setSourceMirror",value:function(e){e!==this.sourceMirror&&(simpleLogger$1.info("remote video track set Mirror",e),this.sourceMirror=e,this.isPlaying&&_superPropGet$2(t,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return simpleLogger$1.info("getCurrentFrameData"),this.isPlaying?getCurrentFrame(player.getElement(this)[0]):null}}])}(RemoteTrack),signal_msg;!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(signal_msg||(signal_msg={}));var nested={signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"uint32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}},SIGNAL_PROTO={nested:nested},root=getProtobufRoot(SIGNAL_PROTO),Response=root.lookupType("signal_msg.Response"),BatchNotification=root.lookupType("signal_msg.BatchNotification"),MediaMessage=root.lookupType("signal_msg.MediaMessage"),StreamNotification=root.lookupType("signal_msg.StreamNotification");root.lookupType("signal_msg.ProgressNotification");var ServerFailoverNotification=root.lookupType("signal_msg.ServerFailoverNotification"),PublishRequest=root.lookupType("signal_msg.PublishRequest"),SoacRequest=root.lookupType("signal_msg.SoacRequest"),UnpublishRequest=root.lookupType("signal_msg.UnpublishRequest"),StreamControlRequest=root.lookupType("signal_msg.StreamControlRequest"),SubscribeRequest=root.lookupType("signal_msg.SubscribeRequest"),SetStreamPropertiesRequest=root.lookupType("signal_msg.SetStreamPropertiesRequest"),UnsubscribeRequest=root.lookupType("signal_msg.UnsubscribeRequest"),SubscriptionControlRequest=root.lookupType("signal_msg.SubscriptionControlRequest"),CreatePeerConnectionRequest=root.lookupType("signal_msg.CreatePeerConnectionRequest"),ClosePeerConnectionRequest=root.lookupType("signal_msg.ClosePeerConnectionRequest"),BatchPublishRequest=root.lookupType("signal_msg.BatchPublishRequest"),BatchUnpublishRequest=root.lookupType("signal_msg.BatchUnpublishRequest"),BatchSubscribeRequest=root.lookupType("signal_msg.BatchSubscribeRequest"),BatchUnsubscribeRequest=root.lookupType("signal_msg.BatchUnsubscribeRequest"),JoinGroupRequest=root.lookupType("signal_msg.JoinGroupRequest"),SetGroupPropertiesRequest=root.lookupType("signal_msg.SetGroupPropertiesRequest"),DismissGroupRequest=root.lookupType("signal_msg.DismissGroupRequest"),LeaveGroupRequest=root.lookupType("signal_msg.LeaveGroupRequest"),SyncDataRequest=root.lookupType("signal_msg.SyncDataRequest"),SyncDataByIdsRequest=root.lookupType("signal_msg.SyncDataByIdsRequest"),GroupChangeLog=root.lookupType("signal_msg.GroupChangeLog"),GroupListChangeLog=root.lookupType("signal_msg.GroupListChangeLog"),SetParticipantPropertiesRequest=root.lookupType("signal_msg.SetParticipantPropertiesRequest"),QueryStreamsVerRequest=root.lookupType("signal_msg.QueryStreamsVerRequest"),QueryStreamsRequest=root.lookupType("signal_msg.QueryStreamsRequest");function _callSuper$g(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$g()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$g(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$g=function(){return!!e})()}var RtcSignaling=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$g(this,t),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return _inherits$1(t,e),_createClass$1(t,[{key:"join",value:function(e,t){return this.channel.join(e,t).then((function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}}))}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",StreamNotification.decode(t)):"serverFailover"===e?this.emit("serverFailover",ServerFailoverNotification.decode(t)):"media-message"===e?this.emit("media-message",MediaMessage.decode(t)):"group"===e?this.emit("group",GroupChangeLog.decode(t)):"group-list"===e&&this.emit("group-list",GroupListChangeLog.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;BatchNotification.decode(e).notificationItem.forEach((function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)}))}},{key:"createPeerConnection",value:function(e){var t=CreatePeerConnectionRequest.encode(e).finish();return this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=ClosePeerConnectionRequest.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=BatchSubscribeRequest.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=SetGroupPropertiesRequest.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=BatchUnsubscribeRequest.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=BatchPublishRequest.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=BatchUnpublishRequest.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=PublishRequest.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){var t=SetParticipantPropertiesRequest.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=SoacRequest.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=UnpublishRequest.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=StreamControlRequest.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=SetStreamPropertiesRequest.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=SubscribeRequest.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=UnsubscribeRequest.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=SubscriptionControlRequest.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=QueryStreamsVerRequest.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=QueryStreamsRequest.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=JoinGroupRequest.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=LeaveGroupRequest.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=DismissGroupRequest.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=SyncDataRequest.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=SyncDataByIdsRequest.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then((function(e){return e.syncDataByIdsResponse}))}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then((function(e){return e.observeAllGroupsResponse}))}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then((function(e){return e.unobserveAllGroupsResponse}))}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(i,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),n),r.channel.signaling.rpc(e,t,n).then((function(t){var n=Response.decode(t);n.code===signal_msg.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),n),i(n)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),n),o(n))})).catch((function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)}))}))}}])}(EventEmitter);function _callSuper$f(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$f()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$f(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$f=function(){return!!e})()}var Monitor=function(e){function t(){var e;_classCallCheck$1(this,t),e=_callSuper$f(this,t),Object.defineProperty(e,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var r=getReporter().statsConfig;return e.interval=(null==r?void 0:r.statsIntervalMs)||METRIC_STATS_INTERVAL,e.start(),e}return _inherits$1(t,e),_createClass$1(t,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=addTimer((function(){e.makeReport()}),this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null)}}])}(EventEmitter);function ownKeys$7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$7(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$7(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$b(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$b(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$b(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$b(e,t);var r={}.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)?_arrayLikeToArray$b(e,t):void 0}}function _arrayLikeToArray$b(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$e(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$e()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$e=function(){return!!e})()}var initAudioSendInfo={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},initVideoSendInfo={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},PublishMonitor=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$e(this,t),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var n=e.tracks.filter((function(e){return"video"===e.trackMediaType}))[0];return r.source=null==n?void 0:n.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},initVideoSendInfo),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},initAudioSendInfo),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source,trackStats:[]},initVideoSendInfo,this.connection.peerConnectionStats);if(r.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=n.frameRate;r.captureFramesPerSecond=a===1/0?0:a||0,r.captureFrameWidth=i||0,r.captureFrameHeight=o||0}var s=new Map,c=getDeltaDurationInSeconds(r,this.lastVideoSendInfo);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)){var n=s.get(e.ssrc)||{},i=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};if(n.sendFrameWidth=e.frameWidth||0,n.sendFrameHeight=e.frameHeight||0,n.framesSent=e.framesSent||0,n.framesEncoded=e.framesEncoded||0,n.targetBitrate=e.targetBitrate||0,n.qpSum=e.qpSum||0,n.bytesSent=e.bytesSent||0,n.packetsSent=e.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=e.timestamp||0,n.totalEncodeTime=e.totalEncodeTime||0,n.keyFramesEncoded=e.keyFramesEncoded||0,n.firCount=e.firCount||0,n.pliCount=e.pliCount||0,n.retransmittedBytesSent=e.retransmittedBytesSent||0,n.retransmittedPacketsSent=e.retransmittedPacketsSent||0,n.qualityLimitationReason=e.qualityLimitationReason||"",n.sendFramesPerSecond=e.framesPerSecond||0,n.sendFrameWidth>r.maxSendFrameWidth){if(r.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&i){var o=getDelta(n.framesSent||n.framesEncoded,i.framesSent||i.framesEncoded);n.sendFramesPerSecond=Math.round(o/c)}if(n.framesEncoded){var a=getDelta(n.framesEncoded,null==i?void 0:i.framesEncoded);r.encodeFramesPerSecond=Math.round(a/c)}r.sendFramesPerSecond=n.sendFramesPerSecond}s.set(e.ssrc,n),r.targetBitrate=n.targetBitrate,r.totalBytesSent+=n.bytesSent,r.totalPacketsSent+=n.packetsSent,r.totalEncodedTime+=n.totalEncodeTime,r.totalFramesEncoded+=n.framesEncoded,r.totalFramesSent+=n.framesSent,r.totalQpSum+=n.qpSum,r.maxSendFrameHeight=Math.max(n.sendFrameHeight,r.maxSendFrameHeight),s.set(e.ssrc,n)}else if(/track/i.test(e.type)&&!1===e.remoteSource){if(Environment.isSafari()){var u=s.get(e.ssrc)||{};u.sendFrameHeight>0||(u.sendFrameWidth=e.frameWidth||0,u.sendFrameHeight=e.frameHeight||0),u.framesSent=e.framesSent||0,u.totalEncodeTime=e.totalEncodeTime||0,s.set(e.ssrc,u),r.totalFramesEncoded+=u.framesEncoded,r.totalEncodedTime+=u.totalEncodeTime,r.totalFramesSent+=u.framesSent,s.set(e.ssrc,u)}}else if(/remote-inbound-rtp/i.test(e.type)){var l=s.get(e.ssrc)||{},d=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};l.packetsLost=e.packetsLost||0,l.lostTimestamp=e.timestamp,r.totalPacketsLost+=l.packetsLost,l.packetsLost===(d.packetsLost||0)&&(l.packetsSentForLost=d.packetsSentForLost||0,l.lostTimestamp=d.lostTimestamp||0),s.set(e.ssrc,l)}})),r.trackStats=s,r}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=_createForOfIteratorHelper$b(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=_slicedToArray(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=getDelta(a.framesSent,s.framesSent),u=getDelta(a.framesEncoded,s.framesEncoded),l=getDelta(a.keyFramesEncoded,s.keyFramesEncoded),d=getDelta(a.retransmittedBytesSent,s.retransmittedBytesSent),p=getDelta(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=getDelta(a.firCount,s.firCount),h=getDelta(a.pliCount,s.pliCount),m=getDelta(a.packetsSent,s.packetsSent),g=getDelta(a.packetsSentForLost,s.packetsSentForLost),v=getDelta(a.lostTimestamp,s.lostTimestamp),y=getDelta(a.sentTimestamp,s.sentTimestamp),b=getDelta(a.packetsLost,s.packetsLost),S=getDelta(a.totalEncodeTime,s.totalEncodeTime),_=getDelta(a.qpSum,s.qpSum),E=a.qualityLimitationReason,T=a.sendFrameWidth,R=_objectSpread$7(_objectSpread$7({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:E},a),{},{deltaQbSum:_,deltaPacketsSent:m,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:v,deltaFramesEncoded:u,deltaKeyFramesEncoded:l,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:h,deltaTimestampForSent:y,deltaPacketsSentForLost:g,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:p});r.push(R)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,l=getDelta(e.timestamp,this.lastVideoSendInfo.timestamp),d=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var h=f.deltaFramesEncoded||f.deltaFramesSent;d&&(d=0===h),s.attr_encoded_framerate_sim.push(_defineProperty({},p,Math.round(1e3*h/l))),s.attr_encode_qp_sim.push(_defineProperty({},p,Math.round((f.deltaQbSum||0)/(h||Number.EPSILON))));var m=f.deltaTimestampForLost,g=f.deltaTimestampForSent,v=f.deltaPacketsLost,y=f.deltaPacketsSentForLost;if(v&&y&&m&&g){var b=v/m/(y/g);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,_=Object.entries(s);S<_.length;S++){var E=_slicedToArray(_[S],2),T=E[0],R=E[1];t[T]=R.length?JSON.stringify(R):""}var C=0,w=getDelta(o,this.lastVideoSendInfo.totalFramesEncoded),O=getDelta(a,this.lastVideoSendInfo.totalEncodedTime);w&&O&&(C=Math.round(1e3*O/w));var P=getDelta(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=l,t.attr_bitrate=l>0?Math.min(Math.round(8*P*1e3/l),2e7):0,t.attr_enc_average_elapsed_ms=C,this.videoSendReport=t,d&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:l,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},initAudioSendInfo,this.connection.peerConnectionStats);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(getDelta(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*getDelta(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/getDelta(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,i=this.pc;if(!i||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then((function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e)}}))}}])}(Monitor);function _createForOfIteratorHelper$a(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$a(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$a(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$a(e,t);var r={}.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)?_arrayLikeToArray$a(e,t):void 0}}function _arrayLikeToArray$a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$d(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$d()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$d=function(){return!!e})()}function _superPropGet$1(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var initAudioReceiveInfo={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},initVideoReciveInfo={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},SubscribeMonitor=function(e){function t(e){var r,n;_classCallCheck$1(this,t),n=_callSuper$d(this,t),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.connection,o=e.transceiver,a=e.uid,s=e.stream,c=e.transceivers;return n.connection=i,n.pc=i.pc,n.tranceiver=o,n.tranceivers=c,n.firstReportTimer=addTimer((function(){n.getStats().then((function(e){n.makeFirstReport(e)}))}),400,"interval"),n.source="mcu"!==a&&(null===(r=s.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},initVideoReciveInfo),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},initAudioReceiveInfo),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return _inherits$1(t,e),_createClass$1(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=_createForOfIteratorHelper$a(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},initVideoReciveInfo,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(getDelta(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=getDelta(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=getDelta(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=getDelta(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,l=t.packetsReceivedForLost,d=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=getDelta(e.timestamp,i);if(e.bytesReceived-u>=0){var h=getDelta(e.packetsLost,a),m=getDelta(e.packetsReceivedForLost,l),g=0;try{g=Math.round(h/m*255)}catch(e){g=0}isNaN(g)&&(g=0);var v=getDelta(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*v/f),attr_dec_frames:v,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:getDelta(e.framesDropped,c),attr_fir_count:getDelta(e.firCount,r),attr_freeze_count:getDelta(e.freezeCount,o),attr_pli_count:getDelta(e.pliCount,n),attr_retx_bytes:getDelta(e.retransmittedBytesReceived,d),attr_retx_packets:getDelta(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*getDelta(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(g,255)),attr_resolution:JSON.stringify([{count:v,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,i=this.pc;if(!(i&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var o=n.map((function(e){return e.receiver.track})).filter((function(e){return!!e}));return Promise.all(o.map((function(e){return i.getStats(e)}))).then((function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}}))}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?i.getStats(r.receiver.track).then((function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}})):void 0}},{key:"stop",value:function(){_superPropGet$1(t,"stop",this)([]),this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}(Monitor),lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.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(grammar$2).forEach((function(e){grammar$2[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(r[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var s=0;s<(n[t]||[]).length;s+=1){var c=n[t][s];if(c.reg.test(i))return r(c,a,i)}})),t.media=o,t};var o=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var o=t.names[i];t.name?n.push(r[t.name][o]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach((function(t){grammar$1[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))})),e.media.forEach((function(e){i.push(makeLine("m",grammar$1.m[0],e)),n.forEach((function(t){grammar$1[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;function _createForOfIteratorHelper$9(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$9(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$9(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$9(e,t);var r={}.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)?_arrayLikeToArray$9(e,t):void 0}}function _arrayLikeToArray$9(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$6(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$6(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$6(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$6(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$c(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$c()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$c=function(){return!!e})()}lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;var _getReporter$3=getReporter(),logger$2=_getReporter$3.log,Subscription=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$c(this,t),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.stream,o=e.uid,a=e.resolutionInfo,s=e.userConfigResolution;return r.connection=n,r.resolutionInfo=a,r.userConfigResolution=s,r.rtcSignaling=n.rtcSignaling,r.stream=i,r.uid=o,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[subscription]"),r.connection.once("ended",(function(){r.clear()})),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=PubSubStates.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return _inherits$1(t,e),_createClass$1(t,[{key:"handleStreamAdd",value:function(e,t){var r,n=this,i=function(){n.reporter.trace.subscribe({init:!1,capabilities:n.stream.media,remoteStreamId:n.stream.id,remoteUserId:n.uid,sessionId:n.id,elapse:Date.now()-n.startTime,resolutionInfo:n.resolutionInfo}),n.startTime=Date.now()};if(clientConfig.audioSFU&&"audio"===e.kind){var o,a=null===(o=this.transceivers)||void 0===o?void 0:o.map((function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id}));null!=a&&a.includes(e.id)&&!this._stream&&(this._stream=t,i())}else e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)&&(this._stream=new MediaStream([e]),i())}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===PubSubStates.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch((function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))}))}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=getActualResolution(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==PubSubStates.End&&(this.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:-1,remoteUserId:this.uid})}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=getDeltaDurationInSeconds(n,d),f=getDelta(n.bytesReceived,d.bytesReceived),h={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(getDelta(null==n?void 0:n.framesDecoded,d.framesDecoded)/p),receiveFrameRate:Math.round(getDelta(null==n?void 0:n.framesReceived,d.framesReceived)/p),receiveFramesDropped:getDelta(null==n?void 0:n.framesDropped,d.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},m=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),g=(null===(l=this.stream.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.source)===exports.VideoSourceInfo.CAMERA&&f>STUCK_JUDGE_RECV_BYTES&&0===h.decodeFrameRate;"network"===t&&(this.stucked&&g?m&&h.receiveFramesDropped>0&&!clientConfig.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=g),this.videoStatsMap.set(t,h)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-first-packet",(function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("audio-first-frame",(function(){e.emit("audio-first-frame")}))):(this.monitor.on("video-first-packet",(function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("video-recv-stream",(function(t){e.reporter.metric.videoRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(EventEmitter),getActualResolution=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=getStreamTypeByResolutionLevel(n);return getResolutionInfo(i,getResolutions(e))}return t},prepareForBatchSubscribe=function(e){var t,r={audio:[],video:[]},n=_createForOfIteratorHelper$9(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo;if(a)logger$2.error("skip subscribe",o,a);else{var c=getSingleMediaOption(o,s),u=c.audio,l=c.video;if(u){var d=_objectSpread$6(_objectSpread$6({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:generateSubSsrc()}]});clientConfig.audioSFU&&(d.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:generateSubSsrc()}}))),r.audio.push(d)}else if(l){var p,f;r.video.push(_objectSpread$6(_objectSpread$6({},l),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:generateSubSsrc(),rtxSsrc:generateSubSsrc()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},getSingleMediaOption=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:getActualResolution(e,t)}}return a},batchSubscribeStart=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=[],o={},t.forEach((function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var u=new Subscription(_objectSpread$6(_objectSpread$6({},r),{},{uid:s,userConfigResolution:c,resolutionInfo:c&&getActualResolution(n,c),stream:n}));o[n.id]=u}})),s=new Promise((function(e,r){a=function(){var a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function a(){var s;return _regeneratorRuntime$1.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=prepareForBatchSubscribe(t),a.next=3,adjustDownlinkSDPWhenSubscribe(n,s,o);case 3:n.rtcSignaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:clientConfig.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function r(n){var a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=4;break}return i.forEach((function(e){e.error=e.error||parseSubscribeError(e.stream,s)})),r.abrupt("return",e(i));case 4:c=_createForOfIteratorHelper$9(a),r.prev=5,l=_regeneratorRuntime$1.mark((function e(){var r,n,a,s,c,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],l=t.findIndex((function(e){return e.stream.id===s.id})),"ok"===a&&c?(c.id=n,i[l].id=n,i[l].subscription=c):"ok"!==a&&(i[l].error=parseSubscribeError(c.stream,a));case 4:case"end":return e.stop()}}),e)})),c.s();case 8:if((u=c.n()).done){r.next=12;break}return r.delegateYield(l(),"t0",10);case 10:r.next=8;break;case 12:r.next=17;break;case 14:r.prev=14,r.t1=r.catch(5),c.e(r.t1);case 17:return r.prev=17,c.f(),r.finish(17);case 20:e(i);case 21:case"end":return r.stop()}}),r,null,[[5,14,17,20]])})));return function(e){return r.apply(this,arguments)}}()).catch(r);case 4:case"end":return a.stop()}}),a)})));return function(){return a.apply(this,arguments)}}()})),n.addTask(a),e.abrupt("return",s);case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),batchSubscribeStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,o=new Promise((function(e,r){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function n(){var o,a;return _regeneratorRuntime$1.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)})).map((function(e){return e.id})),n.next=4,adjustDownlinkSDPWhenUnsubscribe(i,t);case 4:i.rtcSignaling.batchUnSubscribe({connectionId:i.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",o);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function ownKeys$5(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$5(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$5(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$5(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$8(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$8(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$8(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$8(e,t);var r={}.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)?_arrayLikeToArray$8(e,t):void 0}}function _arrayLikeToArray$8(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var _getReporter$2=getReporter(),logger$1=_getReporter$2.log,optionzationMap={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},ssrcPrefix=0,ssrcMask=0,ssrcSeed=0,inUseSsrcSet=new Set,parseSubSsrcInfo=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(ssrcMask=e,ssrcPrefix=(t<<r|2147483648)>>>0)},generateSubSsrc=function(){if(0==ssrcPrefix||0==ssrcMask)return 0;var e=Math.min(ssrcMask+1,1e4);do{var t=ssrcPrefix+(ssrcMask&ssrcSeed++);if(0!=t&&!inUseSsrcSet.has(t))return t}while(--e>0);return 0},useSubSsrcGroup=function(e){e.ssrc&&inUseSsrcSet.add(e.ssrc),e.rtxSsrc&&inUseSsrcSet.add(e.rtxSsrc)},addRidsToMline=function(e,t){var r,n;if((null===(r=e.rids)||void 0===r?void 0:r.length)>1)return Environment.isFirefox()&&(t=addRidExtForFirefox(t)),t.rids=null===(n=e.rids)||void 0===n?void 0:n.map((function(e){return{direction:"recv",id:e.id}})),t.simulcast={dir1:"recv",list1:e.simulcast.list1},t},adjustUplinkSDPWhenApplyOptions=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=4,o.createOffer();case 4:return a=e.sent,e.next=7,o.setLocalDescription(a);case 7:return r.localSDP=lib.parse(a.sdp),s=r.localSDP.media.find((function(e){return e.mid==n.mid})),c=i.media.find((function(e){return e.mid==n.mid})),addRidsToMline(s,c),e.next=13,o.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 13:r.remoteSDP=i;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenPublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.idToTransceiverMap,o=t.remoteSDP,a=new MediaStream(r.map((function(e){return e.getMediaStreamTrack()}))),s=r.map((function(e){var r={direction:"sendonly"};if(e instanceof LocalVideoTrack){var n=getVideoBitrateMap(e).encodings;r.sendEncodings=n.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var o=t.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,r);if(e instanceof LocalVideoTrack&&o.sender.setParameters){var a=e.optimizationMode,s=o.sender.getParameters();s.degradationPreference=optionzationMap[a]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(logger$1.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach((function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,logger$1.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}}))),logger$1.info("adjustUplinkSDPWhenPublish setParameters",s),o.sender.setParameters(s)}return i.set(e.getTrackId(),o),o})),e.next=5,n.createOffer();case 5:return c=e.sent,u=lib.parse(c.sdp),e.next=9,n.setLocalDescription(c);case 9:t.localSDP=u,o.groups[0].mids=t.localSDP.groups[0].mids,l=_createForOfIteratorHelper$8(s),e.prev=12,p=_regeneratorRuntime$1.mark((function e(){var t,r,n,i,a,s,c;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=d.value,r=o.media.find((function(e){return e.type===t.sender.track.kind})),Environment.isFirefox()&&"video"===r.type&&(delete r.rids,delete r.simulcast),n=_objectSpread$5(_objectSpread$5({},r),{},{ext:_toConsumableArray(r.ext),mid:t.mid}),i=u.media.find((function(e){return e.mid==t.mid})),a=new URLSearchParams(location.search).get("startkbs"),s=new URLSearchParams(location.search).get("minkbs"),c=new URLSearchParams(location.search).get("maxkbs"),logger$1.info("startkbs, minkbs",a,s),n.fmtp.map((function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter((function(e){return!/x-google-start-bitrate/i.test(e)}));a&&t.push("x-google-start-bitrate=".concat(a)),s&&t.push("x-google-min-bitrate=".concat(s)),c&&t.push("x-google-max-bitrate=".concat(c)),e.config=t.join(";")}})),addRidsToMline(i,n),o.media.push(n);case 12:case"end":return e.stop()}}),e)})),l.s();case 15:if((d=l.n()).done){e.next=19;break}return e.delegateYield(p(),"t0",17);case 17:e.next=15;break;case 19:e.next=24;break;case 21:e.prev=21,e.t1=e.catch(12),l.e(e.t1);case 24:return e.prev=24,l.f(),e.finish(24);case 27:return window.remoteSDP=o,e.next=30,n.setRemoteDescription({type:"answer",sdp:lib.write(o)});case 30:return t.remoteSDP=o,e.abrupt("return",{localSDP:t.localSDP,stream:a});case 32:case"end":return e.stop()}}),e,null,[[12,21,24,27]])})));return function(t,r){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenUnpublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map((function(e){return e.transceiver})).forEach((function(e){if(e){n.removeTrack(e.sender);var t=i.media.find((function(t){return t.mid==(null==e?void 0:e.mid)}));e.direction="inactive",t.direction="inactive"}})),e.next=5,n.createOffer();case 5:return o=e.sent,a=lib.parse(o.sdp),e.next=9,n.setLocalDescription(o);case 9:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=14,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),addSSRC=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;useSubSsrcGroup(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter((function(e){return void 0!==e})).forEach((function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:createUuid(),id:e})}))},addRidExtForFirefox=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some((function(e){return e.uri.includes("rtp-stream-id")}))||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},adjustDownlinkSDPWhenSubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E,T,R,C,w,O,P,k,I,A;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=t.pc,s=t.idToTransceiverMap,c=t.remoteSDP,u=t.idToTransceiversMap,l=c.media.find((function(e){return"video"===e.type})),d=c.media.find((function(e){return"audio"===e.type})),p=null===(i=l.ssrcs)||void 0===i?void 0:i.find((function(e){return"msid"===e.attribute})).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(h=null===(f=r.audio)||void 0===f?void 0:f[0],m=h.from,clientConfig.audioSFU){if(u.get(m)){g=_createForOfIteratorHelper$8(u.get(m));try{for(g.s();!(v=g.n()).done;)v.value.direction="recvonly"}catch(e){g.e(e)}finally{g.f()}y=c.media.filter((function(e){return"audio"===e.type})),b=_createForOfIteratorHelper$8(y);try{for(b.s();!(S=b.n()).done;)S.value.direction="sendonly"}catch(e){b.e(e)}finally{b.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})})),u.set(m,t.mcuAudioTranceivers);n[m].addTransceivers(u.get(m))}else s.get(m)||s.set(m,t.mcuAudioTranceiver),s.get(m).direction="recvonly",d.direction="sendonly",n[m].addTransceiver(s.get(m));_=_createForOfIteratorHelper$8(r.video),e.prev=6,T=_regeneratorRuntime$1.mark((function e(){var t,r,i,o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=E.value,r=t.from,i=s.get(r)){e.next=7;break}s.set(r,a.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===i.direction){e.next=18;break}return i.direction="inactive",e.next=11,a.createOffer();case 11:return o=e.sent,e.next=14,a.setLocalDescription(o);case 14:return c.media.find((function(e){return e.mid==i.mid})).direction="inactive",e.next=18,a.setRemoteDescription({type:"answer",sdp:lib.write(c)});case 18:s.get(r).direction="recvonly";case 19:n[r].addTransceiver(s.get(r));case 20:case"end":return e.stop()}}),e)})),_.s();case 9:if((E=_.n()).done){e.next=13;break}return e.delegateYield(T(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),_.e(e.t1);case 18:return e.prev=18,_.f(),e.finish(18);case 21:return e.next=23,a.createOffer();case 23:return R=e.sent,C=lib.parse(R.sdp),c.groups[0].mids=C.groups[0].mids,e.next=28,a.setLocalDescription(R);case 28:t.localSDP=C,clientConfig.audioSFU&&r.audio[0]&&(w=r.audio[0],O=w.ssrcGroup,P=w.from,u.get(P).forEach((function(e,t){var r,n=null===(r=O[t])||void 0===r?void 0:r.ssrc,i=c.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=_objectSpread$5(_objectSpread$5({},d),{},{mid:e.mid}),c.media.push(i)),i.ssrcs=getSsrcInfo(n,p),i.direction="sendonly"}))),k=_createForOfIteratorHelper$8(r.video),e.prev=31,A=_regeneratorRuntime$1.mark((function e(){var t,r,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=I.value,r=t.from,i=t.subSsrcGroup,o=s.get(r),a=c.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})),a||((a=_objectSpread$5({},l)).mid=o.mid,c.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,addSSRC(i,a,p);case 8:case"end":return e.stop()}}),e)})),k.s();case 34:if((I=k.n()).done){e.next=38;break}return e.delegateYield(A(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),k.e(e.t3);case 43:return e.prev=43,k.f(),e.finish(43);case 46:return t.remoteSDP=c,e.next=49,a.setRemoteDescription({type:"answer",sdp:lib.write(c)});case 49:case"end":return e.stop()}}),e,null,[[6,15,18,21],[31,40,43,46]])})));return function(t,r,n){return e.apply(this,arguments)}}(),adjustDownlinkSDPWhenUnsubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=_createForOfIteratorHelper$8(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,l=c.transceivers,u?o.push(u):l&&o.push.apply(o,_toConsumableArray(l))}catch(e){a.e(e)}finally{a.f()}return o.forEach((function(e){e.direction="inactive"})),e.next=7,n.createOffer();case 7:return d=e.sent,e.next=10,n.setLocalDescription(d);case 10:t.localSDP=lib.parse(d.sdp),p=_regeneratorRuntime$1.mark((function e(){var t;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=h[f],i.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),f=0,h=o;case 13:if(!(f<h.length)){e.next=18;break}return e.delegateYield(p(),"t0",15);case 15:f++,e.next=13;break;case 18:return t.remoteSDP=i,e.next=21,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 21:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),adjustRemoteSDPWhenFailover=function(e,t){var r=t.media.find((function(e){return"audio"===e.type})),n=t.media.find((function(e){return"video"===e.type}));return e.media.forEach((function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,l=t.rids,d=void 0===l?[]:l;"audio"===t.type?e.media[i]=_objectSpread$5(_objectSpread$5({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=_objectSpread$5(_objectSpread$5({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),d.length&&(e.media[i].rids=d,e.media[i].simulcast={dir1:"recv",list1:d.map((function(e){return"~".concat(e.id)})).join(";")}))})),e},adjustLocalSDPWhenFailover=function(e,t){var r=t.media;return e.media.forEach((function(e){var t=e.mid,n=e.ssrcGroups,i=void 0===n?[]:n,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex((function(e){return e.mid==t&&e.type===s}));c>-1&&(r[c]=_objectSpread$5(_objectSpread$5({},r[c]),{},{ssrcGroups:i,ssrcs:a}))})),t},getSsrcInfo=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:createUuid(),id:e}]},remoteSDPAdaptor=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"all",i=t.direction,o=t.remoteSDP,a=lib.parse(e);"relay"===n&&a.media.forEach((function(e){e.candidates=e.candidates.filter((function(e){return isPrivateIP(e.ip)}))})),r&&(a=adjustRemoteSDPWhenFailover(o,a));var s=a.media.find((function(e){return"video"===e.type}));if("uplink"===i&&Environment.isFirefox()&&clientConfig.simulcast&&(s.ext=s.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!s.ssrcs&&"downlink"===i){var c=generateSubSsrc(),u=a.msidSemantic.token;s.ssrcs=getSsrcInfo(c,u)}return t.remoteSDP=a,a},removeTransportCC=function(e){e.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!e.uri.includes("transport-wide-cc")})),e.rtcpFb=e.rtcpFb.filter((function(e){return"transport-cc"!==e.type}))}))},localSDPAdaptor=function(e,t){var r=t.direction,n=["uplink"===r,clientConfig.downlinkForbidHighProfile],i=lib.parse(e);if(n.some((function(e){return e}))&&(i=removeProfileByPrefix(i,"64")),clientConfig.disableTransportCC&&"uplink"===r&&removeTransportCC(i),"downlink"===r&&!clientConfig.downlinkForbidHighProfile){var o=[];i.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&o.push(t)})),t.subSdpFmtpLines=o}if(Environment.isFirefox()&&(i=removeProfileOfUnsetPacketzationMode(i)),"uplink"===r&&Environment.isFirefox()&&clientConfig.simulcast){var a=i.media.find((function(e){return"video"===e.type}));addRidExtForFirefox(a)}return t.localSDP=i,i},adjustOfferWhenFailover=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),l=_toConsumableArray(n.sessions.values());if("downlink"===c){var d=r.media.slice(2),p=l.filter((function(e){return e instanceof Subscription})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!clientConfig.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var h=[];u.forEach((function(e){var t={direction:e.direction},r=d.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&h.push(i))})),h.length&&f&&(e.mcuAudioTranceivers=h,s.set(f.id,h),f.addTransceivers(h))}else{var m=l.filter((function(e){return e instanceof Publication}));u.forEach((function(e){var t={direction:e.direction},r=m.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof LocalVideoTrack){var s=getVideoBitrateMap(n).encodings;t.sendEncodings=s.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}},removePayloadTypes=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=_createForOfIteratorHelper$8(n);try{for(u.s();!(r=u.n()).done;){var l=r.value,d=l.config,p=l.payload,f=d.split(";");c[p]={};var h,m=_createForOfIteratorHelper$8(f);try{for(m.s();!(h=m.n()).done;){var g=_slicedToArray(h.value.split("="),2),v=g[0],y=g[1];c[p][v]=y}}catch(e){m.e(e)}finally{m.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var _=n.length-1;_>=0;_--){var E=n[_].payload;s.includes(E)&&n.splice(_,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var R=a.length-1;R>=0;R--)s.includes(a[R].payload)&&a.splice(R,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},removeProfileByPrefix=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return removePayloadTypes(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},removeProfileOfUnsetPacketzationMode=function(e){var t=e.media.find((function(e){return"video"===e.type}));return removePayloadTypes(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function ownKeys$4(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$4(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$4(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$4(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$7(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$7(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$7(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$7(e,t);var r={}.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)?_arrayLikeToArray$7(e,t):void 0}}function _arrayLikeToArray$7(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$b(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$b()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$b=function(){return!!e})()}var _getReporter$1=getReporter(),logger=_getReporter$1.log,Publication=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$b(this,t),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.uid,o=e.tracks,a=void 0===o?[]:o;return r.tracks=a,r.connection=n,r.rtcSignaling=n.rtcSignaling,r.uid=i,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[publication]"),r.state=PubSubStates.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),r.applyOptions=r.applyOptions.bind(r),r.applyOptions=debounce(r.applyOptions,1e3,!1),a.forEach((function(e){e.on(TRACK_EVENT_NAME,r.handleTracEvent)})),r.encodings=getVideoBitrateMap(a[0]).encodings,r.state=PubSubStates.Processing,r.connection.once("ended",(function(){r.clear()})),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stop",value:function(){var e=this;return this.state!==PubSubStates.Processing?Promise.resolve():batchPublishStop([this],{connection:this.connection}).catch((function(t){e.clear(),e.logger.warn("negative ack for unpublish, ".concat(tryJsonStringify(t)))}))}},{key:"mute",value:function(){if(this.tracks.length&&this.state===PubSubStates.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!0,this.id),this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:e})}}},{key:"unmute",value:function(){if(this.tracks.length&&this.state===PubSubStates.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!1,this.id),this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:e})}}},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0];this.addTransceiver(this.connection.idToTransceiverMap.get(t.getTrackId())),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this.connection,r=this.transceiver,n=e.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=getHighestResolutionLevel(i,o);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:a});var s=getDownByScales(i,o);t.addTask(_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger.info("scales",s),(t=r.sender.getParameters()).encodings.forEach((function(e){e.scaleResolutionDownBy=s[e.rid]})),logger.info("handleRepublish setParameters",t),e.abrupt("return",r.sender.setParameters(t).then((function(){console.log(r.sender.getParameters().encodings)})));case 5:case"end":return e.stop()}}),e)}))))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){clientConfig.republish?n.handleRepublish(t):n.stop().then((function(){n.connection.sessionManager.serviceManager.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==PubSubStates.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(TRACK_EVENT_NAME,e.handleTracEvent)})),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(this.logger.debug("applyOptions",e),!(n<this.feedbackIndex||this.state!==PubSubStates.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask((function(){return new Promise((function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map((function(e){return e.rid})),l=_createForOfIteratorHelper$7(c.encodings);try{for(l.s();!(n=l.n()).done;){var d,p=n.value,f=_createForOfIteratorHelper$7(e);try{for(f.s();!(d=f.n()).done;){d.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){l.e(e)}finally{l.f()}if(logger.info("encodings",c.encodings),s)return logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then((function(){return adjustUplinkSDPWhenApplyOptions(t).then(r)}));r()}))}))}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof LocalVideoTrack&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask((function(){var e=n.sender.getParameters();return e.degradationPreference=optionzationMap[o]||"balanced",logger.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),adjustUplinkSDPWhenApplyOptions(t)}))}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=PubSubStates.Processing,this.feedbackIndex=-1,this.monitor=new PublishMonitor(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;this.transceiver&&(null===(t=this.transceiver.sender.track)||void 0===t||t.stop(),this.transceiver.sender.replaceTrack(e))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===d?[]:d,f=(null===(l=this.metricsMap.get(t))||void 0===l?void 0:l.videoMetrics)||{},h=getDeltaDurationInSeconds(n,f),m=getDelta(n.totalBytesSent,f.totalBytesSent),g={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*m/h};this.videoStatsMap.set(t,g)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(_objectSpread$4({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(_objectSpread$4({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(_objectSpread$4({sessionId:e.id},t))}))}}])}(EventEmitter),prepareForPublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>2&&void 0!==c[2]?c[2]:["common"],i={},e.next=4,adjustUplinkSDPWhenPublish(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof LocalVideoTrack){var c;i.video=i.video||[];var u=o.ssrcGroups,l=void 0===u?[]:u,d=getVideoBitrateMap(e),p=d.encodings,f=d.resolutionLevel;p.length>1&&(l=p.map((function(){return{semantics:"FID",ssrcs:"".concat(generateSubSsrc()," ").concat(generateSubSsrc())}})));var h=l.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),m=p[p.length-1],g={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:h,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==h||null===(c=h[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(m.maxBitrate),resolution:{width:m.targetWidth,height:m.targetHeight},framerate:m.maxFramerate},ssrcParameters:h.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}}))};i.video.push(g)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),batchPublishStart=function(e){var t,r=e.tracks,n=e.connection,i=e.labels,o=r.map((function(t){return{publication:new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[t]})),track:t}})),a=new Promise((function(e,a){t=function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function t(){var s,c;return _regeneratorRuntime$1.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,prepareForPublish(r,n,i);case 2:return s=t.sent,c={connectionId:n.id,media:s,simulcast:clientConfig.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.rtcSignaling.batchPublish(c).then(function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function t(r){var n,i,a,s,c;return _regeneratorRuntime$1.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=4;break}return o.forEach((function(e){e.error=parsePublishError(e.track,i)})),t.abrupt("return",e(o));case 4:a=_createForOfIteratorHelper$7(n),t.prev=5,c=_regeneratorRuntime$1.mark((function e(){var t,r,n,i,a,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,a=o.findIndex((function(e){return e.track.getTrackId()===n.id})),c=o[a]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(o[a].error=parsePublishError(o[a].track,i));case 4:case"end":return e.stop()}}),e)})),a.s();case 8:if((s=a.n()).done){t.next=12;break}return t.delegateYield(c(),"t0",10);case 10:t.next=8;break;case 12:t.next=17;break;case 14:t.prev=14,t.t1=t.catch(5),a.e(t.t1);case 17:return t.prev=17,a.f(),t.finish(17);case 20:e(o);case 21:case"end":return t.stop()}}),t,null,[[5,14,17,20]])})));return function(e){return t.apply(this,arguments)}}()).catch((function(e){logger.info("batchPublishStart error",e),a(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),a},batchPublishStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise((function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function n(){var o,a;return _regeneratorRuntime$1.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),n.next=4,adjustUplinkSDPWhenUnpublish(r.connection,t);case 4:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(i);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function _callSuper$a(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$a()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$a=function(){return!!e})()}var initPeerConnectionMetrics={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},PeerConnectionMonitor=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$a(this,t),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},initPeerConnectionMetrics)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractMetrics",value:function(e){var t=Object.assign({},this.connectionMetrics),r="";return e.forEach((function(e){var n;if(!e.isRemote)if(/local-candidate/i.test(e.type)&&e.id===r)Environment.networkType=(null!==(n=e.networkType)&&void 0!==n?n:Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(e.type)&&"succeeded"===e.state)r=e.localCandidateId,Environment.isFirefox()||(t.roundTripTime=1e3*(e.currentRoundTripTime||e.totalRoundTripTime/e.responsesReceived)),void 0!==e.availableOutgoingBitrate&&(t.availableOutgoingBitrate=e.availableOutgoingBitrate);else if(/codec/i.test(e.type)){var i,o;null!==(i=e.mimeType)&&void 0!==i&&i.includes("audio")?t.audioCodec=e.mimeType.replace("audio/",""):null!==(o=e.mimeType)&&void 0!==o&&o.includes("video")&&(t.videoCodec=e.mimeType.replace("video/",""),t.sdpFmtpLine=e.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},t),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then((function(t){return e.extractMetrics(t)}))}}])}(Monitor);function _createForOfIteratorHelper$6(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$6(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$6(e,t);var r={}.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)?_arrayLikeToArray$6(e,t):void 0}}function _arrayLikeToArray$6(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$9(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$9()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$9(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$9=function(){return!!e})()}var icePolicyMap={uplink:"",downlink:""},PeerConnection=function(e){function t(e){var r,n;_classCallCheck$1(this,t),r=_callSuper$9(this,t),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pendingTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:PeerConnectionState.New}),Object.defineProperty(r,"exchangeSdpTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,n=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&void 0!==n[0]&&n[0],"uplink"===r.direction?(r.pc.addTransceiver("audio",{direction:"sendonly"}),r.pc.addTransceiver("video",{direction:"sendonly"})):(r.mcuAudioStream=null,r.mcuAudioTranceiver=r.pc.addTransceiver("audio",{direction:"recvonly"}),r.pc.addTransceiver("video",{direction:"recvonly"})),t&&adjustOfferWhenFailover(r),e.next=5,r.exchangeSDP(t);case 5:r.state=PeerConnectionState.Idle,r.enquenTask.start();case 7:case"end":return e.stop()}}),e)}))),function(){return n.apply(this,arguments)})}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.logger.info("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),r.pc=null;var i=e.direction,o=e.sessionManager;return r.rtcSignaling=o.serviceManager.rtcSignaling,r.sessionManager=o,r.reporter=o.reporter,r.logger=r.reporter.getLoggerWithPrefix("[peerconn]"),r.enquenTask=taskQueue(),r.subSdpFmtpLines=[],r.direction=i,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(createUuid()),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"reset",value:function(){this.pendingTask&&(this.pendingTask=null)}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?clientConfig.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==PeerConnectionState.Ended&&(this.state=PeerConnectionState.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"clearPcForReoffer",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==PeerConnectionState.New){e.next=2;break}return e.abrupt("return",Promise.reject());case 2:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),e.prev=3,e.next=6,this.stopSinglePC(!0);case 6:this.removeAllListeners(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(3),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(tryJsonStringify(e.t0)));case 12:this.closePeerConnection();case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),this.logger.info("connectionId:".concat(this.id," connection state changed to ").concat(t)),"failed"===t||"closed"===t?(this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=addTimer((function(){e.state!==PeerConnectionState.New&&(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))}),SIGNAL_CALL_TIMEOUT)):"connected"===t&&(this.clientFailoverTimer&&(removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(removeTimer(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var e=this.sessionManager.serviceManager.iceConfig,t=e.username,r=e.password,n=e.port,i=e.iceServerList,o={bundlePolicy:"max-bundle",iceTransportPolicy:i.length?"relay":"all",sdpSemantics:"unified-plan"};if(i.length){var a,s=[],c=_createForOfIteratorHelper$6(i);try{for(c.s();!(a=c.n()).done;){var u=a.value;s.push("turn:".concat(u,":").concat(n,"?transport=udp"),"turn:".concat(u,":").concat(n,"?transport=tcp"))}}catch(e){c.e(e)}finally{c.f()}Environment.isFirefox()&&s.splice(4,2),"relay"===icePolicyMap[this.direction]&&(icePolicyMap[this.direction]="all",o.iceTransportPolicy="all"),o.iceServers=[{urls:s,username:t,credential:r}]}return icePolicyMap[this.direction]=o.iceTransportPolicy,this.logger.info("PeerConnectionConfig",o),o}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.logger.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=addTimer((function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.exchangeSdpTask||(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))}),CREATE_PC_TIMEOUT))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new PeerConnectionMonitor(this),this.monitor.on("metrics",(function(t){e.peerConnectionStats=t})))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then((function(e){r.peerConnectionStats=e})):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&removeTimer(this.createPeerConnectionTimer),this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"startTask",value:function(){var e=this;return new Promise((function(t,r){e.pendingTask={resolve:t,reject:r},e.exchangeSDP(),addTimer((function(){var t;e.pendingTask&&e.state===PeerConnectionState.Processing&&(null===(t=e.pendingTask)||void 0===t||t.reject(),e.fireEndedEvent())}),SUB_PUB_TIMEOUT)}))}},{key:"exchangeSDP",value:function(){var e,t=this,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return new Promise((function(n,i){t.exchangeSdpTask={resolve:n,reject:i},t.pc.createOffer().then((function(n){return e=n,r&&(e.sdp=lib.write(adjustLocalSDPWhenFailover(t.localSDP,lib.parse(e.sdp)))),t.pc.setLocalDescription(e).catch((function(e){throw t.logger.error("connectionId:".concat(t.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){t.logger.info("connectionId:".concat(t.id," set local sdp success"));var o=localSDPAdaptor(e.sdp,t);e.sdp=lib.write(o),t.offerSDP=o,e.sdp=lib.write(o);var a,s={direction:"downlink"!==t.direction?"in":"out",sdpOffer:e.sdp,connectionId:t.id,isFailover:r,optionsJsonStr:JSON.stringify({supportCVO:1})};if(r){var c=lib.parse(e.sdp);c.media=c.media.slice(0,2),c.groups=[{mids:"0 1",type:"BUNDLE"}],s.sdpOffer=lib.write(c)}tryTimes({key:"createPeerConnection_".concat(t.direction),fn:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===(null===(n=t.sessionManager)||void 0===n||null===(n=n.serviceManager)||void 0===n||null===(n=n.client)||void 0===n?void 0:n.connectionState)){e.next=2;break}return e.abrupt("return");case 2:if(s.isFailover||!t.prevId){e.next=7;break}return e.next=5,t.stopSinglePC(!0);case 5:t.id="".concat(t.direction,"_").concat(createUuid()),s.connectionId=t.id;case 7:return t.prevId=t.id,e.abrupt("return",t.rtcSignaling.createPeerConnection(s).then((function(e){var n=e.sdpAnswer,i=remoteSDPAdaptor(n,t,r,icePolicyMap[t.direction]);t.pc.setRemoteDescription({sdp:lib.write(i),type:"answer"}).then((function(){var e;t.logger.info("connectionId:".concat(t.id," receive answer success")),null===(e=t.exchangeSdpTask)||void 0===e||e.resolve(),t.exchangeSdpTask=void 0})).catch((function(e){var r,n;t.logger.error("connectionId:".concat(t.id," Set remote description failed: ").concat(e)),null===(r=t.exchangeSdpTask)||void 0===r||r.reject(e),t.exchangeSdpTask=void 0,null===(n=t.pendingTask)||void 0===n||n.reject(new DingRTCError(ErrorCode.IceConnectionAnswerFail)),t.fireEndedEvent()}))})));case 9:case"end":return e.stop()}}),e)}))),function(){return a.apply(this,arguments)}),times:3,interval:2e3,reject:i,resolve:n})})).catch((function(e){var r,n;t.logger.error("connectionId:".concat(t.id," Failed to create offer or set SDP. Message: ").concat(e.message)),null===(r=t.pendingTask)||void 0===r||r.reject(new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail)),t.fireEndedEvent(),null===(n=t.exchangeSdpTask)||void 0===n||n.reject(e),t.exchangeSdpTask=void 0}))}))}},{key:"reoffer",value:function(){return this.state===PeerConnectionState.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=PeerConnectionState.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){clientConfig.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}(EventEmitter);function ownKeys$3(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$3(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$3(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$3(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$5(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$5(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$5(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$5(e,t);var r={}.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)?_arrayLikeToArray$5(e,t):void 0}}function _arrayLikeToArray$5(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$8(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$8()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$8(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$8=function(){return!!e})()}var media_reconnect_duration_ms=45e3,media_reconnect_single_round_min_duration_ms=2e3,SessionManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$8(this,t),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.serviceManager=r,n.client=e,n.reporter=r.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),n.streamIdToSessionId=new Map,n.sessions=new Map,n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n.handleRepulish=n.handleRepulish.bind(n),n.handleResubscribe=n.handleResubscribe.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"getOrCreatePeerConnection",value:(m=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=10;break}if(this.uplink){e.next=7;break}return this.uplink=new PeerConnection({direction:t,sessionManager:this}),e.next=5,this.uplink.startSinglePC();case 5:this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){r.uplink=null}));case 7:return e.abrupt("return",this.uplink);case 10:if(this.downlink){e.next=16;break}return this.downlink=new PeerConnection({direction:t,sessionManager:this}),e.next=14,this.downlink.startSinglePC();case 14:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){r.downlink=null}));case 16:return e.abrupt("return",this.downlink);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"handleRepulish",value:(h=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.logger.info("handle repub"),r=_toConsumableArray(this.client.localTracks),n=_createForOfIteratorHelper$5(this.sessions.values());try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Publication&&o.state===PubSubStates.Processing&&(o.clear(),this.sessions.delete(o.id))}catch(e){n.e(e)}finally{n.f()}this.client.emit("media-reconnect-start",this.client.userId),a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+media_reconnect_duration_ms,u=!1,l=0;case 10:if(!(l<23&&Date.now()<=c)){e.next=42;break}if(!((d=Date.now())<s+l*media_reconnect_single_round_min_duration_ms)){e.next=15;break}return e.next=15,asyncDelayMs(s+l*media_reconnect_single_round_min_duration_ms-d);case 15:if(this.logger.debug("repub round=".concat(l,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=18;break}return e.abrupt("continue",39);case 18:return e.prev=18,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(l,", clearPcForReoffer start ").concat(r.map((function(e){return e.trackMediaType})).join())),e.next=23,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 23:if(this.uplink=null,this.logger.info("repub round=".concat(l,", batchPublish start ").concat(r.map((function(e){return e.trackMediaType})).join())),!r.length){e.next=29;break}return e.next=28,this.batchPublish(r);case 28:this.logger.info("".concat(this.client.userId," batchPublish finished for repub"));case 29:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),u=!0,e.abrupt("break",42);case 36:e.prev=36,e.t0=e.catch(18),this.logger.error("".concat(this.client.userId," republish failed for"),e.t0);case 39:l++,e.next=10;break;case 42:u||(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),this.client.emit("media-reconnect-end",this.client.userId),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error"));case 43:case"end":return e.stop()}}),e,this,[[18,36]])}))),function(){return h.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(f=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 3:r=[],n=_createForOfIteratorHelper$5(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Subscription&&o.state===PubSubStates.Processing&&(r.push({stream:o.stream,uid:o.uid,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=9,e.next=12,this.batchUnscribe(r);case 12:return e.next=14,this.batchSubscribe(r);case 14:s=e.sent,c=_createForOfIteratorHelper$5(s);try{for(c.s();!(u=c.n()).done;)l=u.value,d=l.subscription,p=l.error,d&&!p&&this.handleSubscribeReoffer(d)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=25;break;case 20:e.prev=20,e.t0=e.catch(9),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),e.t0),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 25:case"end":return e.stop()}}),e,this,[[9,20]])}))),function(e){return f.apply(this,arguments)})},{key:"handleResubscribe",value:(p=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=E.length>0&&void 0!==E[0]&&E[0],this.logger.info("handle resub fromServer=",r),n=r?"server":"client",i=[],o=_createForOfIteratorHelper$5(this.sessions.values());try{for(o.s();!(a=o.n()).done;)(s=a.value)instanceof Subscription&&s.state===PubSubStates.Processing&&(i.push({stream:s.stream,uid:s.uid}),this.removeSession(s.id))}catch(e){o.e(e)}finally{o.f()}c=i.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",c),this.logger.info("resubscribe start ".concat(c)),u=null===(t=this.downlink)||void 0===t?void 0:t.id,l=Date.now(),d=l+media_reconnect_duration_ms,p=!1,f=0;case 14:if(!(f<23&&Date.now()<=d)){e.next=46;break}if(!((h=Date.now())<l+f*media_reconnect_single_round_min_duration_ms)){e.next=19;break}return e.next=19,asyncDelayMs(l+f*media_reconnect_single_round_min_duration_ms-h);case 19:if(this.logger.debug("resub round=".concat(f,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=22;break}return e.abrupt("continue",43);case 22:return e.prev=22,this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferStart")),e.next=26,null===(m=this.downlink)||void 0===m?void 0:m.clearPcForReoffer();case 26:if(this.downlink=null,!i.length){e.next=33;break}return e.next=30,this.batchSubscribe(i);case 30:g=e.sent,v=_createForOfIteratorHelper$5(g);try{for(v.s();!(y=v.n()).done;)b=y.value,S=b.subscription,_=b.error,S&&!_&&this.handleSubscribeReoffer(S)}catch(e){v.e(e)}finally{v.f()}case 33:return this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferSuccess")),this.logger.debug("resub round=".concat(f," resubscribe ").concat(c," success")),this.client.emit("media-reconnect-end",c),p=!0,e.abrupt("break",46);case 40:e.prev=40,e.t0=e.catch(22),this.logger.debug("resub round=".concat(f," resubscribe failed for"),e.t0);case 43:f++,e.next=14;break;case 46:p||(this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferFailed")),this.client.emit("media-reconnect-end",c),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error"));case 47:case"end":return e.stop()}}),e,this,[[22,40]])}))),function(){return p.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return this.sessions.get(this.streamIdToSessionId.get(e))}},{key:"handleSubscribeReoffer",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(clientConfig.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var l=this.serviceManager.rtcUserManager.remoteUsers.find((function(e){return e.userId===r}));a&&null!=l&&l.auxiliaryTrack&&i?l.auxiliaryTrack.replaceTrack(a):a&&null!=l&&l.videoTrack&&!i&&l.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,n=e.actions,i=_createForOfIteratorHelper$5(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,l=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then((function(){t.logger.info("".concat(u," republish ").concat(l.map((function(e){return e.trackMediaType})).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)})).catch((function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")}))}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?NetworkQualityType.BAD:e>30||t>450?NetworkQualityType.POOR:e>20||t>300?NetworkQualityType.NORMAL:e>10||t>200?NetworkQualityType.GOOD:e>=0||t>=0?NetworkQualityType.GREAT:NetworkQualityType.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(d=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=_toConsumableArray(this.sessions.values())).length){e.next=4;break}return this.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN),e.abrupt("return");case 4:if(0!==t.filter((function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)})).length){e.next=8;break}return this.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED),e.abrupt("return");case 8:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then((function(e){var t=_slicedToArray(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,l=0,d=0,p=0;if(n){var f=n.camera,h=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,d=Math.max(d,f.rtt||0)),h&&(c+=h.sendPacketsLost,s+=h.sendPackets,d=Math.max(d,h.rtt||0))}for(var m in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,d=Math.max(d,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,l+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var g=a[m],v=g.camera,y=g.auxiliary;v&&(u+=v.receivePacketsLost,l+=v.receivePackets,p=Math.max(p,v.rtt||0)),y&&(u+=y.receivePacketsLost,l+=y.receivePackets,p=Math.max(p,y.rtt||0))}var b=-1,S=-1,_={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:l};if(s){var E,T,R=c-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsLost)||0);if(R<0&&(R=c),_.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==R){var C;_.totalUplinkPacketsSentForLost=s;var w=s-((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalUplinkPacketsSentForLost)||0);w<0&&(w=s),b=R/w}}if(l){var O,P,k,I,A=u-((null===(O=r.lastChannelNetworkQuality)||void 0===O?void 0:O.totalDownlinkPacketsLost)||0);A<0&&(A=u),_.totalDownlinkPacketsRecvForLost=(null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalDownlinkPacketsRecvForLost)||0,null===(k=r.lastChannelNetworkQuality)||void 0===k||k.totalDownlinkPacketsRecvForLost,A&&(u!==((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0)&&(_.totalDownlinkPacketsRecvForLost=l),S=A/l)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),d),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=_}));case 9:case"end":return e.stop()}}),e,this)}))),function(){return d.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e))}},{key:"batchPublish",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return i=e.sent,e.abrupt("return",batchPublishStart({uid:this.client.userId,tracks:t,connection:i,labels:r}).then((function(e){var t,r=_createForOfIteratorHelper$5(e);try{var i=function(){var e=t.value,r=e.error,i=e.publication,a=e.track;r?o.reporter.trace.publish(!1,a,"",Date.now()-n):(o.addSession(a.getTrackId(),i),o.reporter.trace.publish(!0,a,i.id,Date.now()-n),o.reporter.trace.publish(!1,a,i.id,Date.now()-n),i.on("ended",(function(){o.removeSession(i.id)})))};for(r.s();!(t=r.n()).done;)i()}catch(e){r.e(e)}finally{r.f()}})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return l.apply(this,arguments)})},{key:"batchUnPublish",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return",Promise.resolve());case 2:return e.next=4,this.getOrCreatePeerConnection("uplink");case 4:return r=e.sent,e.abrupt("return",batchPublishStop(t,{connection:r}).then((function(){var e,r=_createForOfIteratorHelper$5(t);try{for(r.s();!(e=r.n()).done;){var i,o,a,s=e.value;n.streamIdToSessionId.delete(null===(i=s.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=(a=i).getTrackId)||void 0===o?void 0:o.call(a)),n.removeSession(s.id)}}catch(e){r.e(e)}finally{r.f()}})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,i=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(r){var o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getOrCreatePeerConnection("downlink");case 2:return o=e.sent,e.abrupt("return",batchSubscribeStart(r,{connection:o}).then(function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(o){var a,s,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<o.length;c++)"RoomBusy"===(null===(u=o[c].error)||void 0===u?void 0:u.message)&&(s.push(r[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){e.next=12;break}return n++,e.next=7,awaitTime(1);case 7:if("connected"!==t.client.connectionState){e.next=12;break}return e.next=10,i(s);case 10:e.sent.forEach((function(e,t){var r=a.get(t);o[r]=e}));case 12:return e.abrupt("return",o);case 13:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();return i(e).then((function(e){var n,i=_createForOfIteratorHelper$5(e);try{var o=function(){var e=n.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;o&&(t.reporter.trace.subscribe({init:!0,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:a,resolutionInfo:u}),"mcu"===o.uid&&t.reporter.trace.subscribe({init:!1,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:o.id,resolutionInfo:u}),t.addSession(s.id,o),o.on("ended",(function(){t.logger.info("remove subscription for ended",a),t.removeSession(a)}))),i&&(t.logger.error("batchSubscribe error",s,i),t.reporter.trace.subscribe({init:!1,capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:"",resolutionInfo:u}))};for(i.s();!(n=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return t.logger.info("batchSubscribe result",null==e?void 0:e.map((function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}}))),e}))}},{key:"batchUnscribe",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))})),e.next=6,this.getOrCreatePeerConnection("downlink");case 6:return o=e.sent,e.abrupt("return",batchSubscribeStop(n,{connection:o}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r})));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach((function(e){r.removeSession(e.id)})),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(removeTimer(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return this.uplink=e.sent,e.next=6,this.getOrCreatePeerConnection("downlink");case 6:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 9:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=addTimer((function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",NetworkQualityType.BAD,NetworkQualityType.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN)}),NETWORK_QUALITY_TIMEOUT,"interval")}},{key:"getLocalAudioStats",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter((function(e){var t,r;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"getLocalVideoStats",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,m=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=m.length>0&&void 0!==m[0]?m[0]:"network",i=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType})),e.next=4,Promise.all(i.map((function(e){return e.getMetrics(n)})));case 4:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter((function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")})).map((function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex((function(e){return e.includes("profile-level-id")}));return r[n].split("=")[1]})))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find((function(e){return"video"===e.type})),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find((function(e){return"video"===e.type})),c={uplinkProfile:_toConsumableArray(new Set(o(a))),downlinkProfile:_toConsumableArray(new Set(o(s)))},u=_createForOfIteratorHelper$5(i),e.prev=9,u.s();case 11:if((l=u.n()).done){e.next=21;break}if(d=l.value,p=d.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=d.tracks,h=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[h?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return o.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video})),e.next=4,Promise.all(r.map((function(e){return e.getMetrics(t)})));case 4:n={},i=_createForOfIteratorHelper$5(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,l=s.stream,d=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=l.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=_objectSpread$3(_objectSpread$3({},n[u]||{}),{},_defineProperty({},p,d));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return i.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=4;break}return e.abrupt("return");case 4:n=_toConsumableArray(this.sessions.values()).filter((function(e){return e instanceof Publication&&e.state===PubSubStates.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA})),i=_createForOfIteratorHelper$5(n),e.prev=6,a=_regeneratorRuntime$1.mark((function e(){var t,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter((function(e){return e.mid==t.transceiver.mid}))).length&&t.applyOptions(n);case 3:case"end":return e.stop()}}),e)})),i.s();case 9:if((o=i.n()).done){e.next=13;break}return e.delegateYield(a(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),i.e(e.t1);case 18:return e.prev=18,i.f(),e.finish(18);case 21:case"end":return e.stop()}}),e,this,[[6,15,18,21]])}))),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c,u,l,d,p,f,h,m}(EventEmitter);function _createForOfIteratorHelper$4(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$4(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$4(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$4(e,t);var r={}.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)?_arrayLikeToArray$4(e,t):void 0}}function _arrayLikeToArray$4(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$7(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$7()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$7(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$7=function(){return!!e})()}var PropertyNameMap={name:"name"},GroupManager=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$7(this,t),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"joinedIds",get:function(){var e=this.serviceManager.rtcUserManager.currentPid,t=new Set;return this.groups.forEach((function(r){var n=r.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.serviceManager.rtcUserManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,i=e.userData;if(this.joinedIds.has(n))throw new DingRTCError(ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:i,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new DingRTCError(ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:t,reasonCode:signal_msg.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new DingRTCError(ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find((function(t){return t.pid===e.pid}))&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex((function(t){return t.pid===e.pid}));i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||n!==signal_msg.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.logger.info("on group event:",e);var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==signal_msg.OptType.OPT_TYPE_ADD||u){if(s===signal_msg.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===signal_msg.OptType.OPT_TYPE_UPDATE){var l=c.updateAction,d=c.participants;if(u&&(u.ver+1===o||r)){if(l===signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map((function(e){return e.pid})),h=_createForOfIteratorHelper$4(d);try{for(h.s();!(p=h.n()).done;){var m=p.value;f.includes(m.pid)||(u.participants.push(m),this.emit("group","user-join",i,{userId:m.uid,userData:m.userData}))}}catch(e){h.e(e)}finally{h.f()}}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=d.map((function(e){return e.pid})),v=_toConsumableArray(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),v.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(i," audioStream lost"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(i," audioStream recover"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach((function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach((function(t){t.key===e.key&&(t.value=e.value,r=!1)})),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(PropertyNameMap[e.key]),value:e.value})}));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var y,b=c.properties.map((function(e){return e.key}));u.properties=null===(y=u.properties)||void 0===y?void 0:y.filter((function(e){var t=e.key;return!b.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(PropertyNameMap[e.key])})}))}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],l=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),d=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==l[e.key]})),h=c.filter((function(e){return!l.has(e.key)})),m=a.filter((function(e){return!d.includes(e.pid)})),g=u.filter((function(e){return!p.includes(e.pid)}));m.length&&t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:m}},!0),g.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:g}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:h}},!0)}else t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:signal_msg.DataType.DATA_TYPE_GROUP,ids:e.map((function(e){return{id:e}}))}).then((function(e){e.fullSync.groupData.groupInfos.forEach((function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)}))}))}},{key:"syncGroupList",value:function(){var e=this;this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then((function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter((function(t){return!e.groupIds.has(t)})),s=_toConsumableArray(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}(EventEmitter);function _callSuper$6(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$6()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$6(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$6=function(){return!!e})()}var User=function(e){function t(e,r){var n;_classCallCheck$1(this,t),n=_callSuper$6(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.user;return n.userId=i,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.serviceManager=r,n.joinedTime=Date.now(),n.update(e),n}return _inherits$1(t,e),_createClass$1(t,[{key:"relatedStreams",get:function(){var e=this;return _toConsumableArray(this.serviceManager.streamManager.streams.values()).filter((function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id}))}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some((function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST}))}},{key:"hasVideo",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.CAMERA}))}},{key:"hasAudio",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===exports.AudioSourceInfo.MIC}))}},{key:"audioMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC}))}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST}))}},{key:"videoMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.CAMERA}))}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==SdkType$1.Web&&e){var r=e.split("");r[ClientUserStats.UPLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.UPLINK]),r[ClientUserStats.DOWNLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[USER_STATS_SYNC])&&(this.properties[USER_STATS_SYNC]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[USER_STATS_SYNC])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=updateRemoteTrack(e.mediaStream,"video",this.userId,r);return r||i.once("first-frame-decoded",(function(){e.handleVideoFirstFrame()})),t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}(EventEmitter);function _createForOfIteratorHelper$3(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$3(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$3(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$3(e,t);var r={}.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)?_arrayLikeToArray$3(e,t):void 0}}function _arrayLikeToArray$3(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$5(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$5()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$5(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$5=function(){return!!e})()}var RtcUserManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$5(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.serviceManager=e,n.reporter=e.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-userMgr]"),n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){var e=this;return uniqBy(_toConsumableArray(this.users.values()).sort((function(e,t){return e.joinedTime-t.joinedTime})),"userId").filter((function(t){return t.userId&&t.id!==e.currentPid}))}},{key:"init",value:function(e,t){var r,n=_createForOfIteratorHelper$3(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new User(i,this.serviceManager);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var n=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new User(t,this.serviceManager);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map((function(e){return e.id})));_toConsumableArray(this.streamManager.streams.values()).filter((function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)})).map((function(e){return e.id})).forEach((function(e){return n.streamManager.remove(e,!0)}));var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new User(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(_defineProperty({},USER_STATS_SYNC,e))})}}])}(EventEmitter);function _createForOfIteratorHelper$2(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$2(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$2(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$2(e,t);var r={}.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)?_arrayLikeToArray$2(e,t):void 0}}function _arrayLikeToArray$2(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$4(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$4()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$4(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$4=function(){return!!e})()}var StreamManager=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$4(this,t),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var n=e.rtcSignaling,i=e.reporter;return r.rtcSignaling=n,r.reporter=i,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.sync=r.sync.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find((function(e){return"admin"===e.info.owner&&"mixed"===e.type}));null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map((function(e){return[e.id,e]}))),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=_toConsumableArray(this.streams.values()).find((function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s}));c&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===VideoSourceInfo.SCREENCAST;((null==o?void 0:o.source)===VideoSourceInfo.CAMERA||u)&&this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u}),(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIC&&(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","add",{id:r,owner:n,mediaType:"audio"})}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===VideoSourceInfo.SCREENCAST;((null==i?void 0:i.source)===VideoSourceInfo.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIC&&(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return _toConsumableArray(this.streams.values()).find((function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e}))}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties","highestResolutionLevel"]}[i];c.length&&!c.includes(a.field)||this.logger.info("streamEvent",e);var u=this.totalVer;if(s===u+1||s==IGNOGRED_VERSION||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var l=a.field,d=a.streamStatus,p=a.activeStream,f=a.extraValue,h=a.streamVer,m=a.propertiesJsonStr,g=a.highestResolutionLevel,v=this.streams.get(n);if(v){h!==IGNOGRED_VERSION&&(v.version=h);var y=v.media,b=y.audio,S=y.video,_=v.info.owner;if("audio.status"===l||"video.status"===l){var E;"audio.status"===l?(E="audio",b.status=d):"video.status"===l&&(E="video",S.status=d),this.reporter.trace.streamsEvent(n,"".concat(E," ").concat(d));var T="active"===d?"unmute":"mute";this.emit("stream","update",{owner:_,id:n,updateStatus:"".concat(T,"-").concat(E)})}else if("activeInput"===l){var R=[p].concat(f||[]).map((function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner})).filter((function(e){return!!e}));this.reporter.trace.streamsEvent(JSON.stringify(R),l),this.emit("stream","volumeActive",{owners:R})}else if("properties"==l){var C,w=JSON.parse(m);v.info.attributesJsonStr=JSON.stringify(_objectSpread$2(_objectSpread$2({},JSON.parse(v.info.attributesJsonStr)),w));var O=(null===(C=v.media)||void 0===C||null===(C=C.video)||void 0===C?void 0:C.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,properties:w,auxiliary:O})}else"highestResolutionLevel"===l&&(v.media.video.highestResolutionLevel=g,this.emit("stream","update",{owner:_,id:n,highestResolutionLevel:g}))}}t||s<=this.totalVer&&s!==IGNOGRED_VERSION||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&this.sync())}},{key:"sync",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=4,this.rtcSignaling.getStreamsVer({});case 4:n=e.sent,i=n.streamVersions,o=n.totalVer,a=_toConsumableArray(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=_createForOfIteratorHelper$2(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,l=u.streamId,d=u.streamVer,!l.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(l))?p&&p.version!==d&&t.push(l):(r.push(l),t.push(l));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),a.filter((function(e){return!f.includes(e)})).forEach((function(e){h.handleEvent({status:"remove",streamId:e,stream:h.streams.get(e),totalVer:o},!0)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=34;break}return e.abrupt("return");case 34:this.rtcSignaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=_createForOfIteratorHelper$2(h.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,l=_createForOfIteratorHelper$2(o);try{for(l.s();!(u=l.n()).done;){var d=u.value;h.streams.has(d.id)?h.streams.set(d.id,d.stream):a.set(d.id,d.stream)}}catch(e){l.e(e)}finally{l.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var m=p[f];r.includes(m.id)&&h.handleEvent({status:"add",streamId:m.id,stream:m,totalVer:i},!0)}a.clear(),h.totalVer=i}));case 35:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}(EventEmitter),wasm=null;
|
|
16
|
+
*/!function(e){!function(){function t(e){if(e)g[0]=g[16]=g[1]=g[2]=g[3]=g[4]=g[5]=g[6]=g[7]=g[8]=g[9]=g[10]=g[11]=g[12]=g[13]=g[14]=g[15]=0,this.blocks=g,this.buffer8=c;else if(l){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function r(e,r){var n,i=S(e);if(e=i[0],i[1]){var o,a=[],s=e.length,c=0;for(n=0;n<s;++n)(o=e.charCodeAt(n))<128?a[c++]=o:o<2048?(a[c++]=192|o>>>6,a[c++]=128|63&o):o<55296||o>=57344?(a[c++]=224|o>>>12,a[c++]=128|o>>>6&63,a[c++]=128|63&o):(o=65536+((1023&o)<<10|1023&e.charCodeAt(++n)),a[c++]=240|o>>>18,a[c++]=128|o>>>12&63,a[c++]=128|o>>>6&63,a[c++]=128|63&o);e=a}e.length>64&&(e=new t(!0).update(e).array());var u=[],l=[];for(n=0;n<64;++n){var d=e[n]||0;u[n]=92^d,l[n]=54^d}t.call(this,r),this.update(l),this.oKeyPad=u,this.inner=!0,this.sharedMemory=r}var n="input is invalid type",i="object"==typeof window,o=i?window:{};o.JS_MD5_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self,s=!o.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;s?o=commonjsGlobal:a&&(o=self);var c,u=!o.JS_MD5_NO_COMMON_JS&&e.exports,l=!o.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),p=[128,32768,8388608,-2147483648],f=[0,8,16,24],h=["hex","array","digest","buffer","arrayBuffer","base64"],m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),g=[];if(l){var v=new ArrayBuffer(68);c=new Uint8Array(v),g=new Uint32Array(v)}var y=Array.isArray;!o.JS_MD5_NO_NODE_JS&&y||(y=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var b=ArrayBuffer.isView;!l||!o.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&b||(b=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var S=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(n);if(l&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!y(e)&&!b(e))throw new Error(n);return[e,!1]},_=function(e){return function(r){return new t(!0).update(r)[e]()}},E=function(e){var t,r=require$$0,i=require$$1.Buffer;return t=i.from&&!o.JS_MD5_NO_BUFFER_FROM?i.from:function(e){return new i(e)},function(o){if("string"==typeof o)return r.createHash("md5").update(o,"utf8").digest("hex");if(null==o)throw new Error(n);return o.constructor===ArrayBuffer&&(o=new Uint8Array(o)),y(o)||b(o)||o.constructor===i?r.createHash("md5").update(t(o)).digest("hex"):e(o)}},T=function(e){return function(t,n){return new r(t,!0).update(n)[e]()}};t.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=S(e);e=t[0];for(var r,n,i=t[1],o=0,a=e.length,s=this.blocks,c=this.buffer8;o<a;){if(this.hashed&&(this.hashed=!1,s[0]=s[16],s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),i)if(l)for(n=this.start;o<a&&n<64;++o)(r=e.charCodeAt(o))<128?c[n++]=r:r<2048?(c[n++]=192|r>>>6,c[n++]=128|63&r):r<55296||r>=57344?(c[n++]=224|r>>>12,c[n++]=128|r>>>6&63,c[n++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++o)),c[n++]=240|r>>>18,c[n++]=128|r>>>12&63,c[n++]=128|r>>>6&63,c[n++]=128|63&r);else for(n=this.start;o<a&&n<64;++o)(r=e.charCodeAt(o))<128?s[n>>>2]|=r<<f[3&n++]:r<2048?(s[n>>>2]|=(192|r>>>6)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]):r<55296||r>=57344?(s[n>>>2]|=(224|r>>>12)<<f[3&n++],s[n>>>2]|=(128|r>>>6&63)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++o)),s[n>>>2]|=(240|r>>>18)<<f[3&n++],s[n>>>2]|=(128|r>>>12&63)<<f[3&n++],s[n>>>2]|=(128|r>>>6&63)<<f[3&n++],s[n>>>2]|=(128|63&r)<<f[3&n++]);else if(l)for(n=this.start;o<a&&n<64;++o)c[n++]=e[o];else for(n=this.start;o<a&&n<64;++o)s[n>>>2]|=e[o]<<f[3&n++];this.lastByteIndex=n,this.bytes+=n-this.start,n>=64?(this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},t.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>>2]|=p[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},t.prototype.hash=function(){var e,t,r,n,i,o,a=this.blocks;this.first?t=((t=((e=((e=a[0]-680876937)<<7|e>>>25)-271733879|0)^(r=((r=(-271733879^(n=((n=(-1732584194^2004318071&e)+a[1]-117830708)<<12|n>>>20)+e|0)&(-271733879^e))+a[2]-1126478375)<<17|r>>>15)+n|0)&(n^e))+a[3]-1316259209)<<22|t>>>10)+r|0:(e=this.h0,t=this.h1,r=this.h2,t=((t+=((e=((e+=((n=this.h3)^t&(r^n))+a[0]-680876936)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[1]-389564586)<<12|n>>>20)+e|0)&(e^t))+a[2]+606105819)<<17|r>>>15)+n|0)&(n^e))+a[3]-1044525330)<<22|t>>>10)+r|0),t=((t+=((e=((e+=(n^t&(r^n))+a[4]-176418897)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[5]+1200080426)<<12|n>>>20)+e|0)&(e^t))+a[6]-1473231341)<<17|r>>>15)+n|0)&(n^e))+a[7]-45705983)<<22|t>>>10)+r|0,t=((t+=((e=((e+=(n^t&(r^n))+a[8]+1770035416)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[9]-1958414417)<<12|n>>>20)+e|0)&(e^t))+a[10]-42063)<<17|r>>>15)+n|0)&(n^e))+a[11]-1990404162)<<22|t>>>10)+r|0,t=((t+=((e=((e+=(n^t&(r^n))+a[12]+1804603682)<<7|e>>>25)+t|0)^(r=((r+=(t^(n=((n+=(r^e&(t^r))+a[13]-40341101)<<12|n>>>20)+e|0)&(e^t))+a[14]-1502002290)<<17|r>>>15)+n|0)&(n^e))+a[15]+1236535329)<<22|t>>>10)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[1]-165796510)<<5|e>>>27)+t|0)^t))+a[6]-1069501632)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[11]+643717713)<<14|r>>>18)+n|0)^n))+a[0]-373897302)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[5]-701558691)<<5|e>>>27)+t|0)^t))+a[10]+38016083)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[15]-660478335)<<14|r>>>18)+n|0)^n))+a[4]-405537848)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[9]+568446438)<<5|e>>>27)+t|0)^t))+a[14]-1019803690)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[3]-187363961)<<14|r>>>18)+n|0)^n))+a[8]+1163531501)<<20|t>>>12)+r|0,t=((t+=((n=((n+=(t^r&((e=((e+=(r^n&(t^r))+a[13]-1444681467)<<5|e>>>27)+t|0)^t))+a[2]-51403784)<<9|n>>>23)+e|0)^e&((r=((r+=(e^t&(n^e))+a[7]+1735328473)<<14|r>>>18)+n|0)^n))+a[12]-1926607734)<<20|t>>>12)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[5]-378558)<<4|e>>>28)+t|0))+a[8]-2022574463)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[11]+1839030562)<<16|r>>>16)+n|0))+a[14]-35309556)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[1]-1530992060)<<4|e>>>28)+t|0))+a[4]+1272893353)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[7]-155497632)<<16|r>>>16)+n|0))+a[10]-1094730640)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[13]+681279174)<<4|e>>>28)+t|0))+a[0]-358537222)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[3]-722521979)<<16|r>>>16)+n|0))+a[6]+76029189)<<23|t>>>9)+r|0,t=((t+=((o=(n=((n+=((i=t^r)^(e=((e+=(i^n)+a[9]-640364487)<<4|e>>>28)+t|0))+a[12]-421815835)<<11|n>>>21)+e|0)^e)^(r=((r+=(o^t)+a[15]+530742520)<<16|r>>>16)+n|0))+a[2]-995338651)<<23|t>>>9)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[0]-198630844)<<6|e>>>26)+t|0)|~r))+a[7]+1126891415)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[14]-1416354905)<<15|r>>>17)+n|0)|~e))+a[5]-57434055)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[12]+1700485571)<<6|e>>>26)+t|0)|~r))+a[3]-1894986606)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[10]-1051523)<<15|r>>>17)+n|0)|~e))+a[1]-2054922799)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[8]+1873313359)<<6|e>>>26)+t|0)|~r))+a[15]-30611744)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[6]-1560198380)<<15|r>>>17)+n|0)|~e))+a[13]+1309151649)<<21|t>>>11)+r|0,t=((t+=((n=((n+=(t^((e=((e+=(r^(t|~n))+a[4]-145523070)<<6|e>>>26)+t|0)|~r))+a[11]-1120210379)<<10|n>>>22)+e|0)^((r=((r+=(e^(n|~t))+a[2]+718787259)<<15|r>>>17)+n|0)|~e))+a[9]-343485551)<<21|t>>>11)+r|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=r-1732584194|0,this.h3=n+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+r|0,this.h3=this.h3+n|0)},t.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3;return d[e>>>4&15]+d[15&e]+d[e>>>12&15]+d[e>>>8&15]+d[e>>>20&15]+d[e>>>16&15]+d[e>>>28&15]+d[e>>>24&15]+d[t>>>4&15]+d[15&t]+d[t>>>12&15]+d[t>>>8&15]+d[t>>>20&15]+d[t>>>16&15]+d[t>>>28&15]+d[t>>>24&15]+d[r>>>4&15]+d[15&r]+d[r>>>12&15]+d[r>>>8&15]+d[r>>>20&15]+d[r>>>16&15]+d[r>>>28&15]+d[r>>>24&15]+d[n>>>4&15]+d[15&n]+d[n>>>12&15]+d[n>>>8&15]+d[n>>>20&15]+d[n>>>16&15]+d[n>>>28&15]+d[n>>>24&15]},t.prototype.toString=t.prototype.hex,t.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3;return[255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&r,r>>>8&255,r>>>16&255,r>>>24&255,255&n,n>>>8&255,n>>>16&255,n>>>24&255]},t.prototype.array=t.prototype.digest,t.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},t.prototype.buffer=t.prototype.arrayBuffer,t.prototype.base64=function(){for(var e,t,r,n="",i=this.array(),o=0;o<15;)e=i[o++],t=i[o++],r=i[o++],n+=m[e>>>2]+m[63&(e<<4|t>>>4)]+m[63&(t<<2|r>>>6)]+m[63&r];return e=i[o],n+(m[e>>>2]+m[e<<4&63]+"==")},(r.prototype=new t).finalize=function(){if(t.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();t.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),t.prototype.finalize.call(this)}};var R=function(){var e=_("hex");s&&(e=E(e)),e.create=function(){return new t},e.update=function(t){return e.create().update(t)};for(var r=0;r<h.length;++r){var n=h[r];e[n]=_(n)}return e}();R.md5=R,R.md5.hmac=function(){var e=T("hex");e.create=function(e){return new r(e)},e.update=function(t,r){return e.create(t).update(r)};for(var t=0;t<h.length;++t){var n=h[t];e[n]=T(n)}return e}(),u?e.exports=R:o.md5=R}()}(md5);var md5Exports=md5.exports,builder=getProtobufRoot(SLS_PROTO),LogContentProto=builder.lookupType("sls.Log.Content"),LogGroupProto=builder.lookupType("sls.LogGroup"),encoder=new TextEncoder,getCanonicalizedHeaders=function(e){for(var t=Object.keys(e),r=[],n=0;n<t.length;n++){var i=t[n];(i.startsWith("x-log-")||i.startsWith("x-acs-"))&&r.push(i)}r.sort();for(var o="",a=0;a<r.length;a++){var s=r[a];o+="".concat(s,":").concat(String(e[s]).trim(),"\n")}return o},getCanonicalizedResource=function(e,t){for(var r="".concat(e),n=Object.keys(t),i=new Array(n.length),o=0;o<n.length;o++){var a=n[o];i[o]="".concat(a,"=").concat(t[a]||"")}i.sort();var s=i.join("&");return s&&(r+="?".concat(s)),r},sign=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r,n,i){var o,a,s,c,u,l,d,p,f;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=n["Content-MD5"]||"",a=n["Content-Type"]||"",s=n.Date,c=getCanonicalizedHeaders(n),u=getCanonicalizedResource(t,r),l=encoder.encode(["POST",o,a,s,"".concat(c).concat(u)].join("\n")),e.next=8,window.crypto.subtle.importKey("raw",encoder.encode(i.credentials.accessKeySecret),{name:"HMAC",hash:"SHA-1"},!1,["sign"]);case 8:return d=e.sent,e.t0=Uint8Array,e.next=12,window.crypto.subtle.sign("HMAC",d,l);case 12:return e.t1=e.sent,p=new e.t0(e.t1),f=window.btoa(String.fromCharCode.apply(String,_toConsumableArray$1(p))),e.abrupt("return","LOG ".concat(i.credentials.accessKeyId,":").concat(f));case 16:case"end":return e.stop()}}),e)})));return function(t,r,n,i){return e.apply(this,arguments)}}(),postLog=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,m;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.logstore,a=t.project,s=t.endpoint,c=t.credentials,u="/logstores/".concat(o,"/shards/lb"),l=a?a+".":"",d=(r?"?".concat(new URLSearchParams(r)):"").replace(/\?$/,""),p=window.location.href.indexOf("file://")>-1?"http://":"//",f="".concat(p).concat(l).concat(s.replace(/https?:\/\//,"")).concat(u).concat(d),h=new Date(getTime()).toUTCString(),m={"Content-Type":"application/x-protobuf","x-log-compresstype":"deflate","x-log-bodyrawsize":i,Date:h,Host:"".concat(l).concat(s),"x-log-apiversion":"0.6.0","x-log-signaturemethod":"hmac-sha1",Authorization:"","x-acs-security-token":c.securityToken},n&&(m["Content-MD5"]=md5Exports.md5(n).toUpperCase(),m["Content-Length"]=n.length),e.next=11,sign(u,r,m,t);case 11:return m.Authorization=e.sent,m["x-log-date"]=h,e.abrupt("return",{url:f,param:{method:"POST",body:n,headers:m}});case 14:case"end":return e.stop()}}),e)})));return function(t,r,n,i){return e.apply(this,arguments)}}(),getUploadParam=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r){var n,i,o,a,s,c,u;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=parseInt(String(getTime()).substr(0,10)),o={Logs:[],Topic:"Event Track"},t.forEach((function(e){o.Logs.push({Time:i,Contents:Object.keys(e).map((function(t){var r={Key:t,Value:String(e[t])},n=LogContentProto.verify(r);if(n)throw n;return r}))})})),!(n=LogGroupProto.verify(o))){e.next=7;break}throw new Error(n);case 7:return a=LogGroupProto.create(o),s=LogGroupProto.encode(a).finish(),c=pako.deflate(s),u=s.byteLength,e.next=13,postLog(r,{},c,u);case 13:return e.abrupt("return",e.sent);case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),_excute=function(e,t,r){return new Promise((function(n,i){fetch(e,t).then(n).catch((function(n){++r<=3?setTimeout((function(){_excute(e,t,r)}),500*(r+1)):i(n)}))}))},post=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(t,r){var n,i,o;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,getUploadParam(t,r);case 4:return n=e.sent,i=n.url,o=n.param,e.abrupt("return",_excute(i,o,0));case 8:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),UPLOADTIMER=5e3,UPLOADITEMMAX=10,SlsClient=_createClass((function e(t,r){var n=this;_classCallCheck(this,e),Object.defineProperty(this,"logService",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=t.securityToken,o=t.logService,a=t.cycleStatsConfig;this.logService=o,this.cache=[],this.statsCache=[],this.cycleStatsInterval=a.uploadIntervalMs||UPLOAD_LOG_INTERVAL,this.eventTriggedInterval=UPLOADTIMER,this.tokenManager=new STSTokenManager(i,r,this.logService.credentials),this.tokenManager.on("update",(function(e){n.logService=e})),this.upload(!1,"eventTrigged"),this.cycleStatsTimer=addTimer((function(){n.upload(!0,"cycleStats")}),this.cycleStatsInterval,"interval"),this.eventTriggedTimer=addTimer((function(){n.upload(!1,"eventTrigged")}),this.eventTriggedInterval,"interval")}),[{key:"securityToken",get:function(){var e;return null===(e=this.tokenManager)||void 0===e||null===(e=e.securityToken)||void 0===e?void 0:e.securityToken}},{key:"stopUpdateToken",value:function(){this.tokenManager.stopUpdateToken()}},{key:"send",value:function(e){var t=e.cycleStats;delete e.serverDiffTime,t?(delete e.cycleStats,this.sendStats(e)):this.cache.push(e)}},{key:"sendStats",value:function(e){this.statsCache.push(e)}},{key:"flush",value:function(){this.upload(!0,"eventTrigged"),this.upload(!0,"cycleStats")}},{key:"upload",value:function(){var e;return e="eventTrigged"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"eventTrigged")?arguments.length>0&&void 0!==arguments[0]&&arguments[0]?this.cache.splice(0):this.cache.splice(0,UPLOADITEMMAX):this.statsCache.splice(0),post(e,this.logService)}},{key:"clear",value:function(){this.eventTriggedTimer&&(removeTimer(this.eventTriggedTimer,"interval"),this.eventTriggedTimer=null),this.cycleStatsTimer&&(removeTimer(this.cycleStatsTimer,"interval"),this.cycleStatsTimer=null)}}]),Logging=_createClass((function e(){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slsClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.buffer=[],this.slsClient=null,this.commonInfo={udid:Environment.deviceId,tabId:Environment.browserTabId}}),[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"start",value:function(e){this.slsClient=new SlsClient(e,this.commonInfo),this.flushLogBuffer()}},{key:"stop",value:function(){var e,t;this.flushLogBuffer(),null===(e=this.slsClient)||void 0===e||e.stopUpdateToken(),null===(t=this.slsClient)||void 0===t||t.clear()}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds()),e.acs=Environment.networkType||"unknown",this.commonInfo.apid?(this.realSend(e),this.buffer.length&&this.flushLogBuffer()):this.buffer.push(e)}},{key:"flushLogBuffer",value:function(){var e=this;this.buffer.length&&this.slsClient&&this.buffer.splice(0).forEach((function(t){e.realSend(t)})),this.slsClient&&this.slsClient.flush()}},{key:"realSend",value:function(e){var t=Object.assign({},this.commonInfo,e);this.slsClient&&this.slsClient.send(t)}}]);function ownKeys$1$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$1$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1$1(Object(r),!0).forEach((function(t){_defineProperty$1(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1$1(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var WebTrackingClient=_createClass((function e(t){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.commonInfo=Object.assign({},this.commonInfo,t)}),[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"gslbAccess",value:function(e,t){this.send({event:"gslbAccess",success:e,message:t})}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds());var r=_objectSpread$1$1(_objectSpread$1$1({},this.commonInfo),{},{tm:e.date},e);(new Image).src="".concat(BaseWebTrackingURL,"&").concat(new URLSearchParams(r))}}]);function ownKeys$b(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$b(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$b(Object(r),!0).forEach((function(t){_defineProperty$1(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$b(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var SLSSender=_createClass((function e(){_classCallCheck(this,e),Object.defineProperty(this,"logging",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"started",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logging=new Logging}),[{key:"start",value:function(e){var t=e.cycleStatsConfig;this.logging.start(e),this.statsConfig=t,this.started=!0}},{key:"stop",value:function(){this.logging.stop(),this.started=!1}},{key:"securityToken",get:function(){var e;return null===(e=this.logging)||void 0===e||null===(e=e.slsClient)||void 0===e?void 0:e.securityToken}},{key:"updateSecurityToken",value:function(e){var t;return null===(t=this.logging)||void 0===t?void 0:t.slsClient.tokenManager.updateSecurityToken(e)}},{key:"sendMetric",value:function(e){return this.logging.send(_objectSpread$b(_objectSpread$b({},e),{},{cycleStats:!0}))}},{key:"sendEvent",value:function(e){return this.logging.send(_objectSpread$b({},e))}},{key:"exception",value:function(e){this.logging.send(_objectSpread$b(_objectSpread$b({},TraceEvent$1.EXCEPTION),{},{code:e.code,message:e.message,name:e.name}))}}]),MAX_LOG_COUNT=5e3,ONE_FLUSH_LIMIT=500,ONE_FLUSH_CHAR_COUNT_LIMIT=5e5,LOG_LEVEL_NUM={debug:1,info:10,warn:20,error:30,none:99},Logger=function(){function e(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"logBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metricBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"envInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFlushing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logSendFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"afterPrinter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerPrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"flushLog",{enumerable:!0,configurable:!0,writable:!0,value:(t=_asyncToGenerator(_regeneratorRuntime.mark((function e(){var t,n,i,o,a;return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.logBuffer.length||r.isFlushing){e.next=17;break}if(r.isFlushing=!0,t=r.logBuffer.length,r.logBuffer.length>ONE_FLUSH_LIMIT&&(t=ONE_FLUSH_LIMIT),r.logSendFunction){e.next=8;break}return r.isFlushing=!1,e.abrupt("return",Promise.reject("no log sender"));case 8:for(n=r.logBuffer.slice(0,t),i=n.map((function(e){return JSON.stringify(e)})),o=i.length?i.reduce((function(e,t){return e+t.length}),0):0;o>ONE_FLUSH_CHAR_COUNT_LIMIT&&n.length>=2;)n=n.slice(0,n.length/2),i=n.map((function(e){return JSON.stringify(e)})),o=i.length?i.reduce((function(e,t){return e+t.length}),0):0;return o>ONE_FLUSH_CHAR_COUNT_LIMIT&&(console.error("error: truncated logs for flushing log size is too large",n),i=["error: truncated logs for flushing log size is too large"]),a=r.logSendFunction,e.abrupt("return",a(i).then((function(e){e&&e.success&&r.logBuffer.splice(0,t)})).catch((function(e){console.warn("caught flushLogs error",e)})).finally((function(){r.isFlushing=!1})));case 17:return e.abrupt("return",Promise.resolve());case 18:case"end":return e.stop()}}),e)}))),function(){return t.apply(this,arguments)})}),this.loggerPrefix=n}return _createClass(e,[{key:"getLogger",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark((function e(){return _regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),i={debug:n,info:n,warn:n,error:n};return["debug","info","warn","error"].forEach((function(n){return i[n]=t.log(n,"".concat(e,":"),r)})),i}},{key:"pushToMetricBuffer",value:function(e){this.metricBuffer.length>=MAX_LOG_COUNT?console.error("drop metric for log buffer is full: ",e):this.metricBuffer.push(e)}},{key:"pushToLogBuffer",value:function(e){this.logBuffer.length>=MAX_LOG_COUNT?console.error("drop log for log buffer is full: ",e):this.logBuffer.push(e)}},{key:"log",value:function(t){for(var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.loggerPrefix,i=arguments.length,o=new Array(i>2?i-2:0),a=2;a<i;a++)o[a-2]=arguments[a];var s=[formatToBeijingTime(new Date(getTime())),t.toLocaleUpperCase(),n].concat(o);"none"!==t&&LOG_LEVEL_NUM[t]>=e.levelThreshold&&Function.apply.call(console[t],console,s);var c=this.stringifyArgs(s);null===(r=this.afterPrinter)||void 0===r||r.call(this,c),this.logSendFunction&&this.pushToLogBuffer(c)}},{key:"stringifyArgs",value:function(e){var t=_toConsumableArray$1(e).map((function(e){var t=e;return"string"!=typeof e&&(t=tryJsonStringify(e)),t})).join(" ");return"".concat(t)}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["debug",void 0,""].concat(t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["info",void 0,""].concat(t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["warn",void 0,""].concat(t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["error",void 0,""].concat(t))}},{key:"injectLogSender",value:function(e){this.logSendFunction=e}},{key:"injectLogPrint",value:function(e){this.afterPrinter=e}}],[{key:"setLogLevel",value:function(t){e.levelThreshold=LOG_LEVEL_NUM[t]}}])}();Object.defineProperty(Logger,"levelThreshold",{enumerable:!0,configurable:!0,writable:!0,value:LOG_LEVEL_NUM.warn});var Reporter=_createClass((function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metric",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webtracking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"getLoggerWithPrefix",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var r={debug:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).debug.apply(r,[e].concat(i))},info:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).info.apply(r,[e].concat(i))},warn:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).warn.apply(r,[e].concat(i))},error:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).error.apply(r,[e].concat(i))}};return r}}),this.commonInfo={bt:Environment.browserType,bv:Environment.browserVersion,osn:Environment.system,osv:Environment.systemVersion,udid:Environment.deviceId,tabId:Environment.browserTabId},this.sender=new SLSSender,this.webtracking=new WebTrackingClient(this.commonInfo),this.trace=new Trace(this.webtracking,this.sender),this.metric=new Metric(this.sender),this.log=new Logger,this.setId(r),this.log.injectLogPrint((function(e){t.trace.simpleLogger(e)}))}),[{key:"setId",value:function(e){this.id=e,this.log.loggerPrefix="clientId ".concat(this.id)}},{key:"securityToken",get:function(){return this.sender.securityToken}},{key:"statsConfig",get:function(){return this.sender.statsConfig}},{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e),this.webtracking.updateCommonInfo(this.commonInfo),this.sender.logging.updateCommonInfo(this.commonInfo),e.serverDiffTime&&setDiffTime(e.serverDiffTime)}},{key:"updateSecurityToken",value:function(e){this.sender.updateSecurityToken(e)}},{key:"start",value:function(e){this.sender.start(e)}},{key:"stop",value:function(){this.sender.stop()}}]),clientIdToReportMap=new Map,defaultReport,registerReporter=function(e){var t;return defaultReport?defaultReport&&!defaultReport.id?(defaultReport.setId(e),t=defaultReport):t=new Reporter(e):t=defaultReport=new Reporter(e),clientIdToReportMap.set(e,t),t},getReporter=function(e){return defaultReport||(defaultReport=new Reporter),defaultReport},setLogLevel=function(e){Logger.setLogLevel(e)},_ErrorCodeAndMsgMap,DeviceErrorDescription={MESSAGE_DEVICENOTFOUND:"Requested device not found",MESSAGE_DEVICENOTALLOWED:"Permission denied",MESSAGE_MACCHROMEDEVICENOTREADABLE:"Permission denied by system",MESSAGE_MACSAFARIDEVICENOTALLOWED:"The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",MESSAGE_MOBILEDEVICE_NOTALLOWED:"video device not allowed",MESSAGE_AUDIODEVICENOTREADABLE:"Could not start audio source",MESSAGE_VIDEODEVICENOTREADABLE:"Could not start video source",NAME_ABORTEERROR:"AbortError",NAME_INVALIDSTATEERROR:"InvalidStateError",NAME_DEVICENOTALLOWED:"NotAllowedError",NAME_DEVICENOTFOUND:"NotFoundError",NAME_DEVICENOTREADABLE:"NotReadableError",NAME_DEVICEOVERCONSTRAINED:"OverconstrainedError",NAME_INVALID_ACCESS:"InvalidAccessError",NAME_TYPEERROR:"TypeError"},GSLBErrorCode,ErrorCode;!function(e){e.CLIENT_ERROR_INVALID_AUTHORIZATION="invalid authorization",e.CLIENT_ERROR_NOT_FOUND_APP="app not found",e.CLIENT_ERROR_INVALID_APP_STATUS="invalid app status",e.CLIENT_ERROR_MISSING_CHANNEL_NAME="channel missing",e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP="invalid token timestamp",e.CLIENT_ERROR_INVALID_APP_ID="invalid appId",e.CLIENT_ERROR_MISSING_REQUEST="request missing",e.CLIENT_ERROR_MISSING_DEVICE_ID="deviceId missing",e.CLIENT_ERROR_MISSING_UA="ua missing",e.CLIENT_ERROR_MISSING_CLIENT_IP="clientIp missing",e.CLIENT_ERROR_INVALID_USER_ID="invalid userId",e.CLIENT_ERROR_MISSING_SERVIC="service missing",e.CLIENT_ERROR_MISSING_TASK_ID="taskId missing",e.CLIENT_ERROR_MISSING_APP_ID="appId missing",e.CLIENT_ERROR_MISSING_USER_ID="userId missing",e.CLIENT_ERROR_MISSING_USER="user missing",e.CLIENT_ERROR_MISSING_CHANNEL_ID="channel missing",e.CLIENT_ERROR_MISSING_PARTICIPANT_ID="participantId missing",e.CLIENT_ERROR_INVALID_REQUEST="invalid request",e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL="gslb channel not found",e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR="gslb not found channelId error",e.SERVER_ERROR_INTERNAL_ERROR="internal error",e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR="media-engine access error",e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR="media-engine scheduleAndCreate error",e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR="security token not found error",e.SERVER_ERROR_GSLB_ACCESS_ERROR="gslb access error",e.SERVER_ERROR_GSLB_DISPATCH_ERROR="gslb dispatch error",e.SERVER_ERROR_GSLB_MAPI_ERROR="gslb mapi error"}(GSLBErrorCode||(GSLBErrorCode={})),function(e){e[e.JoinTimeout=16908804]="JoinTimeout",e[e.JoinChannelFailed=16974338]="JoinChannelFailed",e[e.CLIENT_ERROR_INVALID_AUTHORIZATION=33620485]="CLIENT_ERROR_INVALID_AUTHORIZATION",e[e.CLIENT_ERROR_NOT_FOUND_APP=33620481]="CLIENT_ERROR_NOT_FOUND_APP",e[e.CLIENT_ERROR_INVALID_APP_STATUS=33620486]="CLIENT_ERROR_INVALID_APP_STATUS",e[e.JoinBadParam=16974081]="JoinBadParam",e[e.CLIENT_ERROR_MISSING_CHANNEL_NAME=16974081]="CLIENT_ERROR_MISSING_CHANNEL_NAME",e[e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP=33620483]="CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP",e[e.CLIENT_ERROR_INVALID_APP_ID=33620482]="CLIENT_ERROR_INVALID_APP_ID",e[e.CLIENT_ERROR_MISSING_REQUEST=16974081]="CLIENT_ERROR_MISSING_REQUEST",e[e.CLIENT_ERROR_MISSING_CLIENT_IP=16974081]="CLIENT_ERROR_MISSING_CLIENT_IP",e[e.CLIENT_ERROR_INVALID_USER_ID=33622278]="CLIENT_ERROR_INVALID_USER_ID",e[e.CLIENT_ERROR_MISSING_SERVIC=16974081]="CLIENT_ERROR_MISSING_SERVIC",e[e.CLIENT_ERROR_MISSING_TASK_ID=16974081]="CLIENT_ERROR_MISSING_TASK_ID",e[e.CLIENT_ERROR_MISSING_APP_ID=16974081]="CLIENT_ERROR_MISSING_APP_ID",e[e.CLIENT_ERROR_MISSING_USER_ID=16974081]="CLIENT_ERROR_MISSING_USER_ID",e[e.CLIENT_ERROR_MISSING_USER=16974081]="CLIENT_ERROR_MISSING_USER",e[e.CLIENT_ERROR_MISSING_CHANNEL_ID=16974081]="CLIENT_ERROR_MISSING_CHANNEL_ID",e[e.CLIENT_ERROR_MISSING_PARTICIPANT_ID=16974081]="CLIENT_ERROR_MISSING_PARTICIPANT_ID",e[e.CLIENT_ERROR_INVALID_REQUEST=16974082]="CLIENT_ERROR_INVALID_REQUEST",e[e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL=33620484]="CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL",e[e.ServerResponseInvalid=16974354]="ServerResponseInvalid",e[e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR=33620496]="SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR",e[e.SERVER_ERROR_INTERNAL_ERROR=33620497]="SERVER_ERROR_INTERNAL_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR=33620498]="SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR=33620499]="SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR",e[e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR=33620500]="SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR",e[e.SERVER_ERROR_GSLB_ACCESS_ERROR=33622281]="SERVER_ERROR_GSLB_ACCESS_ERROR",e[e.SERVER_ERROR_GSLB_DISPATCH_ERROR=33620501]="SERVER_ERROR_GSLB_DISPATCH_ERROR",e[e.SERVER_ERROR_GSLB_MAPI_ERROR=33620502]="SERVER_ERROR_GSLB_MAPI_ERROR",e[e.MicOpenFail=17040388]="MicOpenFail",e[e.SpeakerOpenFail=17040389]="SpeakerOpenFail",e[e.MicInterrupt=17040390]="MicInterrupt",e[e.SpeakerSetNotSupported=17040416]="SpeakerSetNotSupported",e[e.SpeakerInterrupt=17040391]="SpeakerInterrupt",e[e.MicAuthFail=17040392]="MicAuthFail",e[e.MicNotAvailable=17040393]="MicNotAvailable",e[e.SpeakerNotAvailable=17040400]="SpeakerNotAvailable",e[e.SpecifiedAudioDeviceNotFound=17040401]="SpecifiedAudioDeviceNotFound",e[e.AudioMixingUnknownError=17040896]="AudioMixingUnknownError",e[e.LoadAudioFailed=17040897]="LoadAudioFailed",e[e.AudioMixingStateInvalid=17040898]="AudioMixingStateInvalid",e[e.AudioContextNotSupported=17040899]="AudioContextNotSupported",e[e.NotArrayBuffer=17040900]="NotArrayBuffer",e[e.AudioMixingMissingParam=17040901]="AudioMixingMissingParam",e[e.AudioMixingStartFailed=17040902]="AudioMixingStartFailed",e[e.AudioMixingResumeFailed=17040903]="AudioMixingResumeFailed",e[e.AudioPlayTimeError=17040912]="AudioPlayTimeError",e[e.AutoPlayFailed=17040928]="AutoPlayFailed",e[e.CameraOpenFail=17039620]="CameraOpenFail",e[e.CameraInterrupt=17039622]="CameraInterrupt",e[e.SpecifiedCameraDeviceNotFound=17039623]="SpecifiedCameraDeviceNotFound",e[e.CameraNotAvailable=17039673]="CameraNotAvailable",e[e.CameraAuthFail=17039680]="CameraAuthFail",e[e.ScreenShareOpenFail=17039624]="ScreenShareOpenFail",e[e.VideoDisplayOpenFail=17039873]="VideoDisplayOpenFail",e[e.VideoDisplayInterrupt=17039874]="VideoDisplayInterrupt",e[e.DeviceUnknownError=17040537]="DeviceUnknownError",e[e.OverConstrainedError=17040536]="OverConstrainedError",e[e.ScreenShareUnknownError=17040640]="ScreenShareUnknownError",e[e.ScreenShareNotAllowed=17040641]="ScreenShareNotAllowed",e[e.ScreenShareEnded=17040642]="ScreenShareEnded",e[e.ScreenShareNotAuthed=17040643]="ScreenShareNotAuthed",e[e.ScreenShareInvalidAccess=17040644]="ScreenShareInvalidAccess",e[e.ScreenShareAbortError=17040645]="ScreenShareAbortError",e[e.ScreenShareStateError=17040646]="ScreenShareStateError",e[e.ScreenShareTypeError=17040647]="ScreenShareTypeError",e[e.IceConnectionConnectFail=17105409]="IceConnectionConnectFail",e[e.IceConnectionReconnectFail=17105410]="IceConnectionReconnectFail",e[e.IceConnectionAnswerFail=17105426]="IceConnectionAnswerFail",e[e.IceConnectionNoCandidate=17105427]="IceConnectionNoCandidate",e[e.IceConnectionDisconnected=17105428]="IceConnectionDisconnected",e[e.IceConnectionSetLocalDescFail=17105429]="IceConnectionSetLocalDescFail",e[e.ConnectionHeartbeatTimeout=17105411]="ConnectionHeartbeatTimeout",e[e.ConnectionConnectFail=17105665]="ConnectionConnectFail",e[e.APICallTimeOut=17105681]="APICallTimeOut",e[e.PublishNoStream=16974596]="PublishNoStream",e[e.PublishInvaild=16974597]="PublishInvaild",e[e.PublishNotJoinChannel=16843782]="PublishNotJoinChannel",e[e.PublishAudioStreamFailed=16843856]="PublishAudioStreamFailed",e[e.PublishVideoStreamFailed=16843857]="PublishVideoStreamFailed",e[e.PublishScreenShareFailed=16843859]="PublishScreenShareFailed",e[e.PublishScreenShareConfigError=16843860]="PublishScreenShareConfigError",e[e.SubscribeStreamNotExisted=16974851]="SubscribeStreamNotExisted",e[e.SubscribeInvaild=16974852]="SubscribeInvaild",e[e.SubscribeNotJoinChannel=16844112]="SubscribeNotJoinChannel",e[e.SubscribeAudioStreamFailed=16844113]="SubscribeAudioStreamFailed",e[e.SubscribeVideoStreamFailed=16844114]="SubscribeVideoStreamFailed",e[e.SubscribeScreenShareFailed=16844116]="SubscribeScreenShareFailed",e[e.LogAlreadyInit=16974085]="LogAlreadyInit",e[e.LogRootPathError=16974086]="LogRootPathError",e[e.QuotaLimitExceed=16974096]="QuotaLimitExceed",e[e.BrowserNotSupported=16974101]="BrowserNotSupported",e[e.InvaildState=16974340]="InvaildState",e[e.InvaildArgument=16974083]="InvaildArgument",e[e.SessionRemoved=33620229]="SessionRemoved",e[e.AudioBufferFull=17236225]="AudioBufferFull",e[e.VideoBufferFull=17236226]="VideoBufferFull",e[e.AudioStreamError=17301761]="AudioStreamError",e[e.AudioFileOpenFail=17301762]="AudioFileOpenFail",e[e.AudioFormatNotSupported=17301763]="AudioFormatNotSupported",e[e.UpdateRoleChannel=16908801]="UpdateRoleChannel",e[e.Inner=-1]="Inner"}(ErrorCode||(ErrorCode={}));var ErrorCodeAndMsgMap=(_ErrorCodeAndMsgMap={},_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.SERVER_ERROR_GSLB_ACCESS_ERROR,"GSLB access error"),ErrorCode.CLIENT_ERROR_NOT_FOUND_APP,"AppId is not exist"),ErrorCode.CLIENT_ERROR_INVALID_APP_ID,"AppId is invalid"),ErrorCode.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL,"channel is not exist"),ErrorCode.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP,"channel is invalid"),ErrorCode.CLIENT_ERROR_INVALID_AUTHORIZATION,"token is invalid"),ErrorCode.JoinTimeout,"join timeout"),ErrorCode.JoinBadParam,"join with invalid parameter"),ErrorCode.JoinChannelFailed,"join channel failed"),ErrorCode.CLIENT_ERROR_INVALID_APP_STATUS,"invalid app status"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CLIENT_ERROR_INVALID_USER_ID,"invalid userId"),ErrorCode.CLIENT_ERROR_INVALID_REQUEST,"invalid request"),ErrorCode.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR,"gslb not found channelId error"),ErrorCode.SERVER_ERROR_INTERNAL_ERROR,"internal error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR,"media-engine access error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR,"media-engine scheduleAndCreate error"),ErrorCode.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR,"security token not found error"),ErrorCode.SERVER_ERROR_GSLB_DISPATCH_ERROR,"gslb dispatch error"),ErrorCode.SERVER_ERROR_GSLB_MAPI_ERROR,"gslb mapi error"),ErrorCode.ScreenShareUnknownError,"unknown screenShare error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.ScreenShareNotAllowed,"screenShare not allowned"),ErrorCode.ScreenShareEnded,"screenShare ended"),ErrorCode.ScreenShareNotAuthed,"screenShare no permission"),ErrorCode.ScreenShareInvalidAccess,"screenShare invalid access"),ErrorCode.ScreenShareAbortError,"screenShare abort access"),ErrorCode.ScreenShareStateError,"screenShare state error"),ErrorCode.ScreenShareTypeError,"screenShare type error"),ErrorCode.AutoPlayFailed,"auto play failed"),ErrorCode.OverConstrainedError,"Overconstrained error"),ErrorCode.DeviceUnknownError,"unknown device error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.MicOpenFail,"failed to open audio record device or audio device occupied"),ErrorCode.MicInterrupt,"audio recording error or audio device occupied"),ErrorCode.SpeakerInterrupt,"audio playing error or audio device occupied"),ErrorCode.SpeakerOpenFail,"failed to open playback device"),ErrorCode.SpeakerSetNotSupported,"not support set output device"),ErrorCode.MicAuthFail,"no audio recording permission or audio device occupied"),ErrorCode.MicNotAvailable,"no audio record device found"),ErrorCode.SpeakerNotAvailable,"no audio play device found"),ErrorCode.SpecifiedAudioDeviceNotFound,"specified audio device not found"),ErrorCode.CameraOpenFail,"failed to open camera due to no permission or camera device occupied"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CameraInterrupt,"camera capturing happens error"),ErrorCode.SpecifiedCameraDeviceNotFound,"specified camera device not found"),ErrorCode.VideoDisplayOpenFail,"failed to open render device"),ErrorCode.VideoDisplayInterrupt,"render happens error"),ErrorCode.ScreenShareOpenFail,"failed to start shareScreen"),ErrorCode.CameraNotAvailable,"no camera device found"),ErrorCode.CameraAuthFail,"no camera permission"),ErrorCode.IceConnectionConnectFail,"ICE connection failed"),ErrorCode.IceConnectionAnswerFail,"failed to answer ICE connection"),ErrorCode.IceConnectionDisconnected,"ICE connection disconnected"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.IceConnectionNoCandidate,"ICE connection has no candidates"),ErrorCode.IceConnectionSetLocalDescFail,"failed to set local SDP"),ErrorCode.ConnectionHeartbeatTimeout,"signal heartbeat timeout"),ErrorCode.ConnectionConnectFail,"signal connection failed"),ErrorCode.APICallTimeOut,"api call is timeout"),ErrorCode.IceConnectionReconnectFail,"failed to reconnect ICE connection"),ErrorCode.PublishVideoStreamFailed,"failed to publish video"),ErrorCode.PublishNoStream,"publish stream is not exist\t"),ErrorCode.PublishInvaild,"already unpublish or not publish for now"),ErrorCode.PublishNotJoinChannel,"can not publish before join channel"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.PublishAudioStreamFailed,"failed to publish audio"),ErrorCode.PublishScreenShareFailed,"failed to publish ScreenShare"),ErrorCode.PublishScreenShareConfigError,"failed to publish ScreenShare due to config error"),ErrorCode.SubscribeStreamNotExisted,"subscribe stream is not exist"),ErrorCode.SubscribeInvaild,"already unsubscribe or not subscribe for now"),ErrorCode.SubscribeNotJoinChannel,"can not subscribe before join channel"),ErrorCode.SubscribeAudioStreamFailed,"failed to subscribe audio"),ErrorCode.SubscribeScreenShareFailed,"failed to subscribe ScreenShare"),ErrorCode.SubscribeVideoStreamFailed,"failed to subscribe video"),ErrorCode.AudioMixingUnknownError,"audio mixing unknown error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LoadAudioFailed,"load audio source failed"),ErrorCode.AudioMixingStateInvalid,"invalid audio mixing state"),ErrorCode.AudioContextNotSupported,"audio context is not supported"),ErrorCode.NotArrayBuffer,"source type is not array buffer"),ErrorCode.AudioMixingMissingParam,"audio mixing is missing param"),ErrorCode.AudioMixingStartFailed,"audio mixing start failed"),ErrorCode.AudioMixingResumeFailed,"audio mixing resume failed"),ErrorCode.AudioPlayTimeError,"time out of range"),ErrorCode.QuotaLimitExceed,"task exceed limit"),ErrorCode.InvaildState,"the operation is rejected in current state"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.InvaildArgument,"invalid argument"),ErrorCode.AudioBufferFull,"external audio input buffer is full"),ErrorCode.VideoBufferFull,"external video input buffer is full"),ErrorCode.AudioStreamError,"auido stream has error"),ErrorCode.AudioFileOpenFail,"failed to open audio file"),ErrorCode.AudioFormatNotSupported,"no support the audio format"),ErrorCode.UpdateRoleChannel,"failed to update role"),ErrorCode.BrowserNotSupported,"failed to update role"),ErrorCode.Inner,"sdk internel error occured"),ErrorCode.LogAlreadyInit,"log already init"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LogRootPathError,"log root path error"),ErrorCode.SessionRemoved,"session has been removed"),ErrorCode.ServerResponseInvalid,"Server response invalid")),converToRtcErrorFromGslbCode=function(e,t){return new DingRTCError(ErrorCode[e],ErrorCodeAndMsgMap[e]||GSLBErrorCode[e]||t)},NAME_TYPEERROR=DeviceErrorDescription.NAME_TYPEERROR,NAME_ABORTEERROR=DeviceErrorDescription.NAME_ABORTEERROR,NAME_INVALID_ACCESS=DeviceErrorDescription.NAME_INVALID_ACCESS,NAME_DEVICENOTFOUND=DeviceErrorDescription.NAME_DEVICENOTFOUND,NAME_DEVICENOTALLOWED=DeviceErrorDescription.NAME_DEVICENOTALLOWED,NAME_INVALIDSTATEERROR=DeviceErrorDescription.NAME_INVALIDSTATEERROR,MESSAGE_DEVICENOTFOUND=DeviceErrorDescription.MESSAGE_DEVICENOTFOUND,NAME_DEVICENOTREADABLE=DeviceErrorDescription.NAME_DEVICENOTREADABLE,MESSAGE_DEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_DEVICENOTALLOWED,NAME_DEVICEOVERCONSTRAINED=DeviceErrorDescription.NAME_DEVICEOVERCONSTRAINED,MESSAGE_VIDEODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_VIDEODEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_AUDIODEVICENOTREADABLE,MESSAGE_MOBILEDEVICE_NOTALLOWED=DeviceErrorDescription.MESSAGE_MOBILEDEVICE_NOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_MACSAFARIDEVICENOTALLOWED,MESSAGE_MACCHROMEDEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_MACCHROMEDEVICENOTREADABLE,parseAudioDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.MicNotAvailable);if([MESSAGE_DEVICENOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED].includes(t))return new DingRTCError(ErrorCode.MicAuthFail);if([MESSAGE_MACCHROMEDEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE].includes(t)||r===NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.MicOpenFail);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseVideoDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.CameraNotAvailable);if(t==MESSAGE_DEVICENOTALLOWED||t==MESSAGE_MOBILEDEVICE_NOTALLOWED||t==MESSAGE_MACSAFARIDEVICENOTALLOWED)return new DingRTCError(ErrorCode.CameraAuthFail);if(t==MESSAGE_MACCHROMEDEVICENOTREADABLE||t==MESSAGE_VIDEODEVICENOTREADABLE||r==NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.CameraOpenFail);if(r==NAME_DEVICEOVERCONSTRAINED)return new DingRTCError(ErrorCode.OverConstrainedError);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseScreenShareError=function(e){if(e){var t=e.name,r=e.message;if("ended"==e.type)return new DingRTCError(ErrorCode.ScreenShareEnded);if(NAME_DEVICENOTALLOWED===t)return new DingRTCError(r==MESSAGE_DEVICENOTALLOWED?ErrorCode.ScreenShareNotAllowed:ErrorCode.ScreenShareNotAuthed,r);if(NAME_INVALID_ACCESS===t)return new DingRTCError(ErrorCode.ScreenShareInvalidAccess,r);if(NAME_ABORTEERROR===t)return new DingRTCError(ErrorCode.ScreenShareAbortError,r);if(NAME_INVALIDSTATEERROR===t)return new DingRTCError(ErrorCode.ScreenShareStateError,r);if(NAME_TYPEERROR===t)return new DingRTCError(ErrorCode.ScreenShareTypeError,r);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,r)}return new DingRTCError(ErrorCode.ScreenShareUnknownError,"name: ".concat(e.name," message: ").concat(e.message))};function _callSuper$m(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$m()?Reflect.construct(t,r,_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$m=function(){return!!e})()}var DingRTCError=function(e){function t(e,r){var n;return _classCallCheck(this,t),n=_callSuper$m(this,t,[r=r||ErrorCodeAndMsgMap[e]]),Object.defineProperty(n,"code",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.code=e,n.reason=r,getReporter().trace.exception(n),n}return _inherits(t,_wrapNativeSuper(Error)),_createClass(t)}(),AudioCodec,VideoCodec,AudioSourceInfo,TaskType,NetworkQualityType,SdkType,TerminalType,DropType,PubSubStates,PeerConnectionState,SubPubFailReason,ClientUserStats,VideoProfileType;function _defineProperty(e,t,r){return(t=toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _superPropBase(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf$1(e)););return e}function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=_superPropBase(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},_get.apply(null,arguments)}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(AudioCodec||(AudioCodec={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(VideoCodec||(VideoCodec={})),exports.AudioSourceInfo=void 0,AudioSourceInfo=exports.AudioSourceInfo||(exports.AudioSourceInfo={}),AudioSourceInfo.MIC="mic",AudioSourceInfo.SCREENCAST="screen-cast",AudioSourceInfo.MIXED="mixed",exports.VideoSourceInfo=void 0,function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(exports.VideoSourceInfo||(exports.VideoSourceInfo={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(TaskType||(TaskType={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(NetworkQualityType||(NetworkQualityType={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType||(SdkType={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType||(TerminalType={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(DropType||(DropType={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(PubSubStates||(PubSubStates={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(PeerConnectionState||(PeerConnectionState={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(SubPubFailReason||(SubPubFailReason={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(ClientUserStats||(ClientUserStats={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(VideoProfileType||(VideoProfileType={}));var name="dingrtc",version="3.8.12-dev.1",description="dingRTC web端 sdk",files=["dist"],main="./dist/index.js",browser="./dist/index.esm.js",types="./dist/index.d.ts",sideEffects=["dist/*"],scripts={doc:"sh ../../scripts/doc.sh",unittest:"node ./node_modules/karma/bin/karma start test/unit/config/karma.config.js",genproto:"pbjs -t static-module -w es6 -o ./src/services/protos/index.js ./src/services/protos/*.proto",proto2ts:"pbts -o ./src/services/protos/index.d.ts ./src/services/protos/index.js","update-proto":"npm run genproto && npm run proto2ts","genproto-json":"pbjs -t json -o ./src/services/protos/index.json ./src/services/protos/*.proto",e2etest:"npx playwright test --ui",e2ecodegen:"npx playwright codegen http://localhost:5174/","build:dev":"env=development app=dingrtc bash ../../scripts/build.sh",build:"env=production app=dingrtc bash ../../scripts/build.sh ","publish:npm":"npm run build && clean-package -c ../../clean-package.prod.js && pnpm publish && clean-package restore && cross-env APP=dingrtc node ../../scripts/uploadSDK.js","publish:tnpm":"npm run build:dev && clean-package -c ../../clean-package.dev.js&& pnpm publish && clean-package restore"},keywords=["web","library"],dependencies={"@dingrtc/shared":"1.1.0","@dingrtc/channel":"1.1.0","sdp-transform":"^2.14.2","webrtc-adapter":"^8.2.3"},overrides={"grunt-jsdoc":{jsdoc:"^4.0.0"},"ink-docstrap":{"sanitize-html":"^2.3.2"}},license="MIT",gitHead="e980464185949aa7edc75803f17e61ede8918021",publishConfig={registry:"https://registry.anpm.alibaba-inc.com"},repository="git@gitlab.alibaba-inc.com:oneRTC/oneRTC.git",pkg={name:name,version:version,description:description,files:files,main:main,browser:browser,types:types,sideEffects:sideEffects,scripts:scripts,keywords:keywords,dependencies:dependencies,overrides:overrides,license:license,gitHead:gitHead,publishConfig:publishConfig,repository:repository},VideoDimensions={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(exports.AudioSourceState||(exports.AudioSourceState={}));var SDK_VERSION=pkg.version,DEFAULT_GSLB_DOMAIN="https://gslb.dingrtc.com",IGNOGRED_VERSION=-999,SIGNAL_CALL_TIMEOUT=1e3,SUB_PUB_TIMEOUT=15e3,NETWORK_QUALITY_TIMEOUT=2e3,METRIC_STATS_INTERVAL=2e3,CREATE_PC_TIMEOUT=4e3,MEDIA_ELEMENT_LABEL_ATTR="rtc-label",STUCK_JUDGE_RECV_BYTES=5e3;JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),Environment.browserType,Environment.browserVersion,Environment.system,Environment.systemVersion;var USER_STATS_SYNC="onertc_state_sync",TRACK_EVENT_NAME="onertc_internal_track_event",_getReporter$b=getReporter(),logger$8=_getReporter$b.log,Support=function(){return _createClass$1((function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=Environment.system,this.browser=Environment.browserType,this.browserVersion=Environment.browserVersion}),[{key:"getSupportedCodec",value:(e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=7,r.createOffer();case 7:if(n=e.sent.sdp){e.next=10;break}return e.abrupt("return",t);case 10:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 24:throw e.prev=24,e.t0=e.catch(1),logger$8.error("get supportedCodecs failed"),new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 28:case"end":return e.stop()}}),e,null,[[1,24]])}))),function(){return e.apply(this,arguments)})},{key:"checkSupported",value:function(){var e=!1;try{var t=window.RTCPeerConnection,r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;e=!!(t&&r&&n)}catch(e){return!1}var i=!1;i=Environment.isChrome()||Environment.isFirefox()?parseInt(Environment.browserVersion,10)>=69:Environment.isOpera()?parseInt(Environment.browserVersion,10)>=45:Environment.isSafari()?parseInt(Environment.browserVersion,10)>=11:(Environment.isWeixin()||Environment.isQQBrowser(),!0);var o=e&&i;return logger$8.debug("checkSystemRequirements, api:",e,"browser",i),o}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(OSType.ANDROID)&&this.system!==OSType.IOS&&(!(this.browser===BrowserType.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===BrowserType.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var e}(),support=new Support,isSupportSimulcast=function(){var e,t=(null===(e=window.RTCRtpSender)||void 0===e?void 0:e.prototype)||{},r=t.setParameters,n=t.getParameters;return!(!r||!n)&&(!Environment.isFirefox()&&(Environment.isSafari()?parseInt(Environment.browserVersion)>=14:Environment.isChrome()?parseInt(Environment.browserVersion)>=81:!Environment.isAndroid()))};function _arrayLikeToArray$d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$d(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$d(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$d(e,t);var r={}.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)?_arrayLikeToArray$d(e,t):void 0}}function _nonIterableSpread(){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 _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$d(e)||_nonIterableSpread()}function _callSuper$l(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$l()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$l=function(){return!!e})()}var _getReporter$a=getReporter(),logger$7=_getReporter$a.log,ClientConfig=function(e){function t(){var e;return _classCallCheck$1(this,t),e=_callSuper$l(this,t),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:isSupportSimulcast()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"highStartBitrate",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e.setClientConfig({gslb:[DEFAULT_GSLB_DOMAIN]}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"setClientConfig",value:function(e){logger$7.info("setClientConfig",e);var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU,o=t.republish,a=t.disableTransportCC,s=t.highStartBitrate;"string"==typeof r&&(this.gslb=[r],setGslb(r)),Array.isArray(r)&&isString(r[0])&&(this.gslb=r,setGslb(r[0])),null!=n&&isSupportSimulcast()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i)),null!=a&&(this.disableTransportCC=Boolean(a)),null!=o&&(this.republish=Boolean(o)),null!=s&&(this.highStartBitrate=!!s)}}])}(EventEmitter),clientConfig=new ClientConfig,sortResolutions=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},getResolutions=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,_toConsumableArray(i.parameters.resolution)),n.sort(sortResolutions),n},parseSubscribeError=function(e,t){var r,n=e.media,i=n.audio,o=n.video;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if(i)r=new DingRTCError(ErrorCode.SubscribeAudioStreamFailed,t);else if(o){var a=o.source;a===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.SubscribeVideoStreamFailed,t):a===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.SubscribeScreenShareFailed,t))}return r},parsePublishError=function(e,t){var r,n=e.trackMediaType;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if("audio"===n)r=new DingRTCError(ErrorCode.PublishAudioStreamFailed,t);else{var i=e.source;i===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.PublishVideoStreamFailed,t):i===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.PublishScreenShareFailed,t))}return r},updateRemoteTrack=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?clientConfig.audioSFU?n?n.replaceStream(e):i=new RemoteAudioTrack(null,r,e):n?n.replaceTrack(a[0]):i=new RemoteAudioTrack(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new RemoteVideoTrack(o[0],r)),i},isScreenCast=function(e){return"object"===_typeof$3(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function ownKeys$a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$a(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$a(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$c(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$c(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$c(e,t);var r={}.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)?_arrayLikeToArray$c(e,t):void 0}}function _arrayLikeToArray$c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$k(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$k()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$k(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$k=function(){return!!e})()}var _getReporter$9=getReporter(),logger$6=_getReporter$9.log,DeviceManager=function(e){function t(){var e,r;return _classCallCheck$1(this,t),e=_callSuper$k(this,t),Object.defineProperty(e,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function r(){var n;return _regeneratorRuntime$1.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=2;break}return r.abrupt("return");case 2:return e.checking=!0,r.next=5,t.getDevices();case 5:n=r.sent,e.compareDevices(n,"audiooutput"),e.compareDevices(n,"videoinput"),e.compareDevices(n,"audioinput"),e.deviceList=n,e.checking=!1;case 11:case"end":return r.stop()}}),r)}))),function(){return r.apply(this,arguments)})}),Object.defineProperty(e,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(t,r){var n,i=t.filter((function(e){return e.kind===r})),o=e.deviceList.filter((function(e){return e.kind===r})),a=i.map((function(e){return e.deviceId})),s=o.map((function(e){return e.deviceId})),c=i.filter((function(e){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),l={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},d=_createForOfIteratorHelper$c(c);try{for(d.s();!(n=d.n()).done;){var p=n.value;e.emit(l[r],{device:p,state:"active"})}}catch(e){d.e(e)}finally{d.f()}var f,h=_createForOfIteratorHelper$c(u);try{for(h.s();!(f=h.n()).done;){var m=f.value;e.emit(l[r],{device:m,state:"inactive"})}}catch(e){h.e(e)}finally{h.f()}}}),t._instance?_possibleConstructorReturn$1(e,t._instance):(e.deviceList=[],support.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).then((function(t){e.deviceList=t,e.addEventListeners()})),e):_possibleConstructorReturn$1(e))}return _inherits$1(t,e),_createClass$1(t,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):addTimer(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return t._instance}},{key:"getMedias",value:function(e,t){var r,n,i=this;return isScreenCast(e)?(logger$6.info("getDisplayMedia with",t),null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t)):(logger$6.info("getUserMedia with",t),null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t})))}},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(n,i){var o;if(null!==(o=navigator.mediaDevices)&&void 0!==o&&o.enumerateDevices){var a=!1;t.audio&&t.video?a=e.audioPermitted&&e.videoPermitted:t.audio?a=e.audioPermitted:t.video&&(a=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(o){var s=o.filter((function(e){return e.deviceId})),c=s.filter((function(e){return"videoinput"===e.kind})),u=s.filter((function(e){return"audioinput"===e.kind})),l=s.filter((function(e){return"audiooutput"===e.kind})),d=[];t.audio&&(d=d.concat(u,l)),t.video&&(d=d.concat(c)),0!==d.length||a||r?d.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(d)):n(d):(logger$6.info("getUserMedia with",t),navigator.mediaDevices.getUserMedia(t).then((function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){n(e)}),i)}),i)),n(s)}))}else i(new DingRTCError(ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}(EventEmitter);Object.defineProperty(DeviceManager,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new DeviceManager}),Object.defineProperty(DeviceManager,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(e){throw parseAudioDeviceError(e)}))}}),Object.defineProperty(DeviceManager,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({video:!0}).then((function(e){return logger$6.info("getCameras",e),e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return _objectSpread$a(_objectSpread$a({},r),{},{toJSON:function(){return r}})}))})).catch((function(e){throw logger$6.error("getCameras error",e),parseVideoDeviceError(e)}))}}),Object.defineProperty(DeviceManager,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then((function(e){return logger$6.info("getMicrophones",e),e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(e){throw logger$6.error("getMicrophones error",e),parseAudioDeviceError(e)}))}});var parseVideoDimension=function(e){return{width:VideoDimensions[e][0],height:VideoDimensions[e][1]}},addAudioTrackAttribute=function(e){var t,r=Object.create({}),n={};null!==(t=navigator)&&void 0!==t&&null!==(t=t.mediaDevices)&&void 0!==t&&t.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var i=e.AEC,o=e.AGC,a=e.ANS;return e.deviceId&&(Environment.isSafari()?r.deviceId=e.deviceId:r.deviceId={exact:e.deviceId}),n.autoGainControl&&(r.autoGainControl={ideal:null==o||o}),n.echoCancellation&&(r.echoCancellation={ideal:null==i||i}),n.noiseSuppression&&(r.noiseSuppression={ideal:null==a||a}),r},createMediaStream=function(e){if(!isObject(e)||!e.audio&&!e.video)return Promise.reject(new TypeError("Invalid constrains"));var t=e.audio,r=e.video;if(!isScreenCast(e)&&"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(isScreenCast(e)&&"object"===_typeof$3(t)&&t.source!==exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!t&&!r)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n=Object.create({});if("object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.MIC||"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST?n.audio=addAudioTrackAttribute(t):n.audio=e.audio,"object"===_typeof$3(r)){var i,o=r.frameRate,a=r.deviceId,s=r.source,c=r.facingMode,u=r.displaySurface,l=r.dimension;n.video=Object.create({}),isNumber(o)&&(n.video.frameRate=Math.min(r.frameRate,30)),l&&(i=parseVideoDimension(l)),i&&i.width&&i.height&&(s===exports.VideoSourceInfo.SCREENCAST||Environment.isFirefox()?(n.video.width=i.width,n.video.height=i.height):(n.video.width={ideal:i.width,max:i.width},n.video.height={ideal:i.height,max:i.height})),isString(a)&&a&&(n.video.deviceId={exact:a}),s===exports.VideoSourceInfo.SCREENCAST&&(Environment.isFirefox()&&(n.video.mediaSource="screen"),u&&["browser","window","monitor"].includes(u)&&(n.video.displaySurface=u)),c&&["user","environment"].includes(c)&&(n.video.facingMode=c)}else n.video=r;return DeviceManager.getMedias(e,n)},_this=void 0,getPlainMediaTrackInfo=function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t},getPlainMediaStreamInfo=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map((function(e){return getPlainMediaTrackInfo(e)}));return t.trackInfos=r,t},isVideoStreamPlayable=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},getDeltaDurationInSeconds=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},transNativeAndWebNetworkRank=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},getDelta=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},tryTimes=function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.resolve,a=e.reject;if(!(r>0))throw new Error("invalid params times");var s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var n,s;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=0;case 1:if(!(s<r)){e.next=22;break}return e.prev=2,e.next=5,t();case 5:return n=e.sent,null==o||o(n),e.abrupt("break",22);case 10:if(e.prev=10,e.t0=e.catch(2),s!==r-1){e.next=17;break}return null==a||a(e.t0),e.abrupt("return",e.t0);case 17:return e.next=19,asyncDelayMs(i);case 19:s++,e.next=1;break;case 22:return e.abrupt("return",n);case 23:case"end":return e.stop()}}),e,null,[[2,10]])})));return function(){return e.apply(this,arguments)}}();return s()},asyncDelayMs=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=3;break}return e.next=3,new Promise((function(e){setTimeout(e,t)}));case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),taskQueue=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime=function(e){return new Promise((function(t){addTimer(t,1e3*e)}))},debounce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=null,i=0;return function(){for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];var c=Date.now();c-i>=t&&r?(e.apply(_this,a),i=c):(n&&clearTimeout(n),n=setTimeout((function(){e.apply(_this,a),i=c}),t))}},_getReporter$8=getReporter(),logger$5=_getReporter$8.log,MEDIA_ELEMENT_INTERSECTING_ATTR="rtc-intersecting",MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES={visible:"visible",invisible:"invisible"},MEDIA_ELEMENT_EVENT_NAMES=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],MEDIA_PLAYBACK_CHECK_PERIOD_MS=4e3,getLabel=function(e){return"".concat(null==e?void 0:e.getAttribute(MEDIA_ELEMENT_LABEL_ATTR),"-").concat(null==e?void 0:e.rtcPurpose)},isVideoTagIntersectingVisible=function(e){return e&&e.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR)===MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible},MediaElementPool=function(){return _createClass$1((function e(t,r){var n=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new Debouncer}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse)).forEach((function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject;if(t.error){var i="".concat(e,": ").concat(getLabel(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=getPlainMediaStreamInfo(r);logger$5.debug(i,o),"visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load()}if(t.paused){var a=!1;if(n.hasActivated&&"video"===n.mediaKind?isVideoTagIntersectingVisible(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(getLabel(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR),", mediaStream="),c=getPlainMediaStreamInfo(r);logger$5.error(s,c),isVideoStreamPlayable(r)&&t.load(),t.paused&&t.play().catch((function(e){console.error("inPoll",e)}))}}}})),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&!0!==(null==i?void 0:i.muted)){var o="".concat(e,": ").concat(getLabel(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=getPlainMediaStreamInfo(r);return logger$5.error(o,a),void("visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load())}n.currentTimeOfLastCheckMap.set(t,t.currentTime)}}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$5.error(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$5.debug(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject);logger$5.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse));if(!n.hasActivated&&(n.hasActivated=!0,e.forEach((function(e){e.load()})),n._activatedListener))try{n._activatedListener()}catch(e){logger$5.error("error occurred when exec activatedListener",tryJsonStringify(e))}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver((function(e){e.forEach((function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible):null===(r=e.target)||void 0===r||r.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.invisible)}))})));for(var i=0;i<r;i++){var o,a=this._createElement();null===(o=this.observer)||void 0===o||o.observe(a),this.addAtttribute(a),a.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"".concat(t,"-").concat(i)),this.mediaElementPool.push(a),this.allElements.add(a)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=addTimer((function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")}),MEDIA_PLAYBACK_CHECK_PERIOD_MS,"interval")}),[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?(this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||""):(t=document.createElement(this.mediaKind),this.addAtttribute(t)),t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter((function(t){return t!==e})),t.length!==this.mediaElementsInUse.length&&(this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(){var e,t=document.createElement(this.mediaKind);return null===(e=this.observer)||void 0===e||e.observe(t),t}},{key:"_resetMediaElement",value:function(e){MEDIA_ELEMENT_EVENT_NAMES.forEach((function(t){e["on".concat(t)]=null})),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),audioElementMgr,videoElementMgr,getAudioElementPool=function(){return audioElementMgr||initMediaElementPool(),audioElementMgr},getVideoElementPool=function(){return videoElementMgr||initMediaElementPool(),videoElementMgr},INIT_AUDIO_TAG_COUNT=2,INIT_VIDEO_TAG_COUNT=Environment.isIOS()||Environment.isAndroid()?9:25,initMediaElementPool=function(){audioElementMgr||(audioElementMgr=new MediaElementPool("audio",INIT_AUDIO_TAG_COUNT)),videoElementMgr||(videoElementMgr=new MediaElementPool("video",INIT_VIDEO_TAG_COUNT))},audioContext=new AudioContext,getAudioContext=function(){return audioContext},mergeAudioTracks=function(e){var t=e.getAudioTracks(),r=audioContext.createMediaStreamDestination();return t.forEach((function(e){audioContext.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},playVideo=function(e,t,r){var n=getVideoElementPool().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n},playAudio=function(e){var t=getAudioElementPool().popElement();return t.srcObject=e,t},getAudioVolumeLevel=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},getCurrentFrame=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},audioElementPool=getAudioElementPool(),videoElementPool=getVideoElementPool(),_getReporter$7=getReporter(),log=_getReporter$7.log,PlayerManager=function(){return _createClass$1((function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(e,t,r){var n,i=this,o=e.getTrackId(),a=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var s,c=this.findDom(t);if(!c)throw new DingRTCError(ErrorCode.InvaildArgument,"wrapper dom not found");var u=r||{},l=u.mirror,d=u.fit;if((n=this.players.find((function(e){return e.container===t})))&&(null===(s=n.track)||void 0===s?void 0:s.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stop(n.track,t),void this.play(e,t,r);n?(n.element.pause(),!e.sourceMirror!=!l?n.element.style.transform="scaleX(-1)":n.element.style.transform="",d&&(n.element.style.objectFit=d),n.element.srcObject=a,n.element.load()):((n={container:t,track:e,playerConfig:r}).element=playVideo(c,a,{mirror:!e.sourceMirror!=!l,fit:d}),this.players.push(n))}else(n=this.players.find((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})))?(n.element.pause(),n.element.srcObject=a,n.element.load()):((n={track:e}).element=playAudio(a),this.players.push(n));n.element.paused&&n.element.play().then((function(){n.isPlaying=!0})).catch((function(e){"NotAllowedError"===e.name?(log.error("autoplay failed",tryJsonStringify(e)),EventBus.emit("autoplay-failed",i)):log.warn("".concat(o," play has exception"),tryJsonStringify(e))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?audioElementPool.pushElement(t.element):videoElementPool.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),player$3=new PlayerManager,getPlayer=function(){return player$3};function _callSuper$j(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$j()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$j(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$j=function(){return!!e})()}function _superPropGet$4(e,t,r,n){var i=_get(_getPrototypeOf$1(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var _getReporter$6=getReporter(),simpleLogger$2=_getReporter$6.log,trace=_getReporter$6.trace,logger$4=simpleLogger$2,player$2=getPlayer(),Track=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$j(this,t),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:trace}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e?(n.trackMediaType=e.kind,n.trackSettings=e.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.audioContext=getAudioContext(),n.analyser=n.audioContext.createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(createUuid(6)),n.setMediaStreamTrack(e,r),n}return _inherits$1(t,e),_createClass$1(t,[{key:"isPlaying",get:function(){return player$2.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return logger$4.info("track emit event",e,null==n?void 0:n[0]),_superPropGet$4(t,"emit",this,3)([e].concat(n))}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var i;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(i=this.audioContext)||void 0===i?void 0:i.createMediaStreamSource(new MediaStream([e]));else if(t){var o,a=mergeAudioTracks(t);this.sourceNode=null===(o=this.audioContext)||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([a]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===exports.VideoSourceInfo.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===exports.AudioSourceInfo.MIC?new DingRTCError(ErrorCode.MicInterrupt):r.source===exports.VideoSourceInfo.CAMERA&&new DingRTCError(ErrorCode.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){simpleLogger$2.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(TRACK_EVENT_NAME,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===exports.VideoSourceInfo.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===exports.AudioSourceInfo.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){simpleLogger$2.info("stop paly track ".concat(this.getTrackId())),player$2.stop(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.element,n=e.config;e.updated?player$2.getPlayInfos(this).forEach((function(e){e.container?player$2.findDom(e.container)?player$2.play(t,e.container,e.playerConfig):player$2.stop(t,e.container):player$2.play(t,e.container,e.playerConfig)})):player$2.play(this,r,n);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(e){simpleLogger$2.debug("resume audioContext failed: ".concat(tryJsonStringify(e)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}(EventEmitter),ResolutionProfile;function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$d(e,t)||_nonIterableRest()}function ownKeys$9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$9(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$9(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$9(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(ResolutionProfile||(ResolutionProfile={}));var ResolutionProfileMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},ResolutionProfile.LLD,"lld"),ResolutionProfile.LD,"ld"),ResolutionProfile.SD,"sd"),ResolutionProfile.HD,"hd"),ResolutionProfile.FHD,"fhd"),ResolutionProfile.QHD,"qhd"),ResolutionRange={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},getResolutionLevel=function(e,t){var r={high:VideoProfileType.QHD,low:VideoProfileType.LD,QHD:VideoProfileType.QHD,FHD:VideoProfileType.FHD,HD:VideoProfileType.HD,SD:VideoProfileType.SD,LD:VideoProfileType.LD},n=r[e]||VideoProfileType.None,i=ResolutionRange[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(ResolutionRange).find((function(e){var t=_slicedToArray(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[_slicedToArray(a,1)[0]]}return n},is2K=function(e){return 2560===e.width&&1440===e.height},getResolutionInfo=function(e,t){return{resolution:getResolution(e,t),resolutionLevel:getResolutionLevel(e,t)}},getStreamTypeByResolutionLevel=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},getResolution=function(e,t){var r=ResolutionRange[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&is2K(i))return i;if(t[0].width*t[0].height>ResolutionRange.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},DefaultVideoMaxPixelCount=[49152,76800,307200,1228800,2764800,4915200],DefaultMaxBitrateKbps=[200,350,1e3,1800,2828,5600],DefaultResolution_16_9=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],DefaultResolution_4_3=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],getVideoProfile=function(e,t){var r=ResolutionProfile.FHD,n=e*t;return n<=DefaultVideoMaxPixelCount[ResolutionProfile.LLD]?r=ResolutionProfile.LLD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.LD]?r=ResolutionProfile.LD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.SD]?r=ResolutionProfile.SD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.HD]?r=ResolutionProfile.HD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.FHD]?r=ResolutionProfile.FHD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.QHD]&&(r=ResolutionProfile.QHD),r},getTargetResolution=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=DefaultResolution_16_9[r][0],o=DefaultResolution_16_9[r][1];else if(4*t==3*e)i=DefaultResolution_4_3[r][0],o=DefaultResolution_4_3[r][1];else{var s=Math.sqrt(1*DefaultResolution_16_9[r][0]*DefaultResolution_16_9[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},getVideoMaxbitrate=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=DefaultMaxBitrateKbps[getVideoProfile(e,t)];n=Math.round(Math.max(i*o,50))}return n},getDownByScales=function(e,t){var r=getVideoProfile(e,t),n=function(n){var i=_slicedToArray(getTargetResolution(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(ResolutionProfile.LD),sd:n(ResolutionProfile.SD),fhd:n(r)}},getVideoSenderEncodings=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=getVideoProfile(t,r),s=[],c=a>=ResolutionProfile.HD?3:2,u=function(e){var o=_slicedToArray(getTargetResolution(t,r,e,a),2),s=o[0],c=o[1],u=DefaultMaxBitrateKbps[e]/DefaultMaxBitrateKbps[a],l=1/(c/r);return{targetWidth:s,rid:ResolutionProfileMap[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:l}};a>ResolutionProfile.LLD&&s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,ResolutionProfile.LLD)===o},u(ResolutionProfile.LLD))),a>ResolutionProfile.LD&&s.push(_objectSpread$9({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,ResolutionProfile.LD)===o},u(ResolutionProfile.LD))),a>ResolutionProfile.SD&&s.push(_objectSpread$9({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,ResolutionProfile.SD)===o},u(ResolutionProfile.SD))),a===ResolutionProfile.FHD?(s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:!1},u(ResolutionProfile.HD))),s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:clientConfig.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(ResolutionProfile.FHD)))):s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var l=0,d=0;d<s.length;++d)0!=d&&(s[d].minBitrate=l),l=Math.round(Math.max((s[d].maxBitrate+s[d].minBitrate)/2,s[d].maxBitrate-400));return s.shift(),s},getHighestResolutionLevel=function(e,t){var r=getVideoProfile(e,t),n=Math.pow(2,r);return console.log(n,r),n},getVideoBitrateMap=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!clientConfig.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST||is2K({width:i,height:o}),c={resolutionLevel:getHighestResolutionLevel(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:clientConfig.republish?c.encodings=getVideoSenderEncodings({width:1920,height:1080,frameRate:30,maxBitrate:getVideoMaxbitrate(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=getVideoSenderEncodings({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function ownKeys$8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$8(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$8(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$8(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$i(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$i()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$i=function(){return!!e})()}function _superPropGet$3(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var player$1=getPlayer(),_getReporter$5=getReporter(),logger$3=_getReporter$5.log,LocalTrack=function(e){function t(e,r){var n;if(_classCallCheck$1(this,t),n=_callSuper$i(this,t,[e]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var i,o=e.muted;if(n.muted=o,!r)r=null===(i=e.getSettings())||void 0===i?void 0:i.deviceId}return n.enabled=!0,n.deviceId=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;_superPropGet$3(t,"setMediaStreamTrack",this)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(e){return logger$3.info("setEnabled",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.enabled=e,this.emit(TRACK_EVENT_NAME,e?"unmute":"mute"),e?this.updateNewTrack():(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),Promise.resolve()));var t}},{key:"close",value:function(){var e;logger$3.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(TRACK_EVENT_NAME,"stop"),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.audioContext&&(this.sourceNode=null,this.analyser=null,this.audioContext=null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return logger$3.info("setMuted",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(TRACK_EVENT_NAME,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return logger$3.debug("gengrate new audioTrack"),new Promise((function(t,r){var n;createMediaStream({audio:_objectSpread$8(_objectSpread$8({source:e.source},e.config),{},{deviceId:e.deviceId})}).then((function(e){n=e.getAudioTracks()[0]})).catch((function(t){try{var i=e.audioContext.createOscillator(),o=e.audioContext.createMediaStreamDestination();i.connect(o),n=o.stream.getAudioTracks()[0]}catch(e){logger$3.error("gengrate new audioTrack error",parseAudioDeviceError(t)),r(parseAudioDeviceError(t))}})).finally((function(){n&&t(n)}))}))}},{key:"getVideoTrack",value:function(){var e=this;return logger$3.info("gengrate new videoTrack"),new Promise((function(t,r){var n,i=_objectSpread$8({source:e.source},e.config);e.config.deviceId&&(i.deviceId=e.config.deviceId),e.config.facingMode&&e.config.deviceId&&(logger$3.info("ignore did param to create videoTrack because facingMode is",e.config.facingMode),delete i.deviceId),createMediaStream({video:i,audio:!1}).then((function(e){n=e.getVideoTracks()[0],t(n)})).catch((function(e){logger$3.error("gengrate new videoTrack error",parseVideoDeviceError(e)),r(parseVideoDeviceError(e))}))}))}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,logger$3.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof CameraVideoTrack)||"user"!==t&&"environment"!==t){e.next=7;break}this.config.facingMode=t,e.next=10;break;case 7:if(this.deviceId!==t){e.next=9;break}return e.abrupt("return");case 9:this.deviceId=t;case 10:return e.abrupt("return",this.updateNewTrack());case 11:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(logger$3.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(Track),LocalVideoTrack=function(e){function t(e,r,n){var i;if(_classCallCheck$1(this,t),(i=_callSuper$i(this,t,[e,r])).config=n,e){var o=e.getSettings(),a=o.width,s=o.height;i.maxBitrate=getVideoMaxbitrate(a,s,n.frameRate,n.maxBitrate)}return i}return _inherits$1(t,e),_createClass$1(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(e){var t=this;logger$3.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),e);var r=e.dimension,n=e.frameRate,i=e.maxBitrate,o=e.optimizationMode,a=e.mirror;if(n&&Number.isNaN(n))return Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid frameRate"));if(r&&!VideoDimensions[r])return Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid dimension"));!a!=!this.config.mirror&&(this.emit(TRACK_EVENT_NAME,"mirror",a),this.config.mirror=a),o&&o!==this.optimizationMode&&(this.config.optimizationMode=o,this.emit(TRACK_EVENT_NAME,"optimizationMode"));var s=!1;if(r&&this.config.dimension!==r&&(this.config.dimension=r,s=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),s=!0),i&&this.maxBitrate!==i&&(s=!0),!s)return Promise.resolve();var c=_objectSpread$8({frameRate:this.config.frameRate},parseVideoDimension(this.config.dimension)),u=this.getMediaStreamTrack();return null==u?void 0:u.applyConstraints(c).then((function(){var e,r=null===(e=t.getMediaStreamTrack())||void 0===e?void 0:e.getSettings(),n=r.width,o=r.height;t.maxBitrate=getVideoMaxbitrate(n,o,t.config.frameRate,i),console.log(n,o,c,t.maxBitrate),t.emit(TRACK_EVENT_NAME,"republish",t)})).catch((function(e){var r=parseVideoDeviceError(e);throw logger$3.error("videoTrack ".concat(t.getTrackId()," setEncoderConfiguration error"),r),r}))}},{key:"getCurrentFrameData",value:function(){return logger$3.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:getCurrentFrame(player$1.getElement(this)[0])}},{key:"play",value:function(e,r){return logger$3.info("local video play"),_superPropGet$3(t,"play",this)([e,r])}}])}(LocalTrack),LocalAudioTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$i(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||player$1.getElement(this)[0]&&(player$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return player$1.getElement(this)[0]?player$1.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:getAudioVolumeLevel(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return logger$3.info("local audio play"),_superPropGet$3(t,"play",this)([])}}])}(LocalTrack),CameraVideoTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$i(this,t,[e,r.deviceId,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return _inherits$1(t,e),_createClass$1(t)}(LocalVideoTrack),MicrophoneAudioTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$i(this,t,[e,(r||{}).deviceId])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=n.audioContext.createAnalyser(),n}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||player$1.getElement(this)[0]&&(player$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return player$1.getElement(this)[0]?player$1.getElement(this)[0].volume:void 0}}])}(LocalAudioTrack),createMicrophoneAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l,d;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAudioTrack",t),r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,u=void 0===c||c,e.prev=3,e.next=6,createMediaStream({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:exports.AudioSourceInfo.MIC,AEC:o,AGC:s,ANS:u}});case 6:return l=e.sent,d=l.getAudioTracks()[0],logger$3.info("MicrophoneAudioTrack created"),e.abrupt("return",new MicrophoneAudioTrack(d,Object.assign({},t,{AEC:o,AGC:s,ANS:u})));case 12:throw e.prev=12,e.t0=e.catch(3),parseAudioDeviceError(e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,12]])})));return function(t){return e.apply(this,arguments)}}(),createCameraVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createCameraVideoTrack",t),r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=3,e.next=6,createMediaStream({video:{deviceId:r,source:exports.VideoSourceInfo.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 6:return u=e.sent,l=u.getVideoTracks()[0],logger$3.info("CameraVideoTrack created"),e.abrupt("return",new CameraVideoTrack(l,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 12:throw e.prev=12,e.t0=e.catch(3),parseVideoDeviceError(e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,12]])})));return function(t){return e.apply(this,arguments)}}(),createScreenVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoTrack",t),r=t.displaySurface,n=void 0===r?"monitor":r,i=t.dimension,o=void 0===i?"VD_1920x1080":i,a=t.optimizationMode,s=void 0===a?"detail":a,c=Math.min(t.frameRate||5,30),e.prev=3,e.next=6,createMediaStream({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:n,frameRate:c,dimension:o},audio:!1});case 6:return u=e.sent,(l=new LocalVideoTrack(u.getVideoTracks()[0],null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(exports.VideoSourceInfo.SCREENCAST),logger$3.info("ScreenVideoTrack created"),e.abrupt("return",[l]);case 13:throw e.prev=13,e.t0=e.catch(3),parseScreenShareError(e.t0);case 16:case"end":return e.stop()}}),e,null,[[3,13]])})));return function(t){return e.apply(this,arguments)}}(),createMicrophoneAndCameraTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAndCameraTracks",t,r),n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,l={AEC:!0,AGC:!0,ANS:!0},p=(d=r||l).AEC,f=void 0===p||p,h=d.AGC,m=void 0===h||h,g=d.ANS,v=void 0===g||g,e.prev=5,e.next=8,createMediaStream({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:f,AGC:m,ANS:v}});case 8:return y=e.sent,b=y.getVideoTracks()[0],S=y.getAudioTracks()[0],logger$3.info("CameraVideoTrack and MicrophoneTrack created"),_=new CameraVideoTrack(b,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),E=new MicrophoneAudioTrack(S,Object.assign({},Object.assign({},r,{AEC:f,AGC:m,ANS:v}))),e.abrupt("return",[_,E]);case 17:throw e.prev=17,e.t0=e.catch(5),parseVideoDeviceError(e.t0);case 20:case"end":return e.stop()}}),e,null,[[5,17]])})));return function(t,r){return e.apply(this,arguments)}}(),createCustomVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("createCustomVideoTrack",t),n=(r=t||{}).mediaStreamTrack,i=r.dimension,o=void 0===i?"VD_640x480":i,a=r.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(t.frameRate||15,30),n instanceof MediaStreamTrack&&"video"===n.kind){e.next=5;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 5:return(u=new LocalVideoTrack(n,null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(exports.VideoSourceInfo.CAMERA),e.abrupt("return",u);case 8:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),createCustomAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("createCustomAudioTrack",t),(r=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===r.kind){e.next=4;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 4:return(n=new LocalAudioTrack(r)).setSource(exports.AudioSourceInfo.MIC),e.abrupt("return",n);case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function _superPropGet$2(e,t,r,n){var i=_get(_getPrototypeOf$1(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function _callSuper$h(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$h()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$h=function(){return!!e})()}var _getReporter$4=getReporter(),simpleLogger$1=_getReporter$4.log,player=getPlayer(),RemoteTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$h(this,t,[e,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return _inherits$1(t,e),_createClass$1(t,[{key:"getUserId",value:function(){return simpleLogger$1.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(Track),RemoteAudioTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$h(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return _inherits$1(t,e),_createClass$1(t,[{key:"getMediaStreamTrack",value:function(){return clientConfig.audioSFU?mergeAudioTracks(this.sfuStream):_superPropGet$2(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){simpleLogger$1.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){simpleLogger$1.info("setVolume",e),player.getElement(this)[0]&&(player.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(simpleLogger$1.info("getVolume"),player.getElement(this)[0])return player.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return simpleLogger$1.info("setSpeaker",e),new Promise((function(r,n){var i,o=player.getElement(t)[0];o||n(new DingRTCError(ErrorCode.InvaildState,"please playout audio first")),o.setSinkId||n(new DingRTCError(ErrorCode.SpeakerSetNotSupported)),null===(i=o.setSinkId)||void 0===i||i.call(o,e).then((function(){t.deviceId=e,r()})).catch((function(e){n(parseAudioDeviceError(e))}))}))}},{key:"getVolumeLevel",value:function(){return getAudioVolumeLevel(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return simpleLogger$1.info("remote audio play"),_superPropGet$2(t,"innnerPlay",this,3)([{}])}}])}(RemoteTrack),RemoteVideoTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$h(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"play",value:function(e,r){return simpleLogger$1.info("remote video play"),_superPropGet$2(t,"innnerPlay",this,3)([{element:e,config:r}])}},{key:"setSourceMirror",value:function(e){e!==this.sourceMirror&&(simpleLogger$1.info("remote video track set Mirror",e),this.sourceMirror=e,this.isPlaying&&_superPropGet$2(t,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return simpleLogger$1.info("getCurrentFrameData"),this.isPlaying?getCurrentFrame(player.getElement(this)[0]):null}}])}(RemoteTrack),signal_msg;!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(signal_msg||(signal_msg={}));var nested={signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"uint32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}},SIGNAL_PROTO={nested:nested},root=getProtobufRoot(SIGNAL_PROTO),Response=root.lookupType("signal_msg.Response"),BatchNotification=root.lookupType("signal_msg.BatchNotification"),MediaMessage=root.lookupType("signal_msg.MediaMessage"),StreamNotification=root.lookupType("signal_msg.StreamNotification");root.lookupType("signal_msg.ProgressNotification");var ServerFailoverNotification=root.lookupType("signal_msg.ServerFailoverNotification"),PublishRequest=root.lookupType("signal_msg.PublishRequest"),SoacRequest=root.lookupType("signal_msg.SoacRequest"),UnpublishRequest=root.lookupType("signal_msg.UnpublishRequest"),StreamControlRequest=root.lookupType("signal_msg.StreamControlRequest"),SubscribeRequest=root.lookupType("signal_msg.SubscribeRequest"),SetStreamPropertiesRequest=root.lookupType("signal_msg.SetStreamPropertiesRequest"),UnsubscribeRequest=root.lookupType("signal_msg.UnsubscribeRequest"),SubscriptionControlRequest=root.lookupType("signal_msg.SubscriptionControlRequest"),CreatePeerConnectionRequest=root.lookupType("signal_msg.CreatePeerConnectionRequest"),ClosePeerConnectionRequest=root.lookupType("signal_msg.ClosePeerConnectionRequest"),BatchPublishRequest=root.lookupType("signal_msg.BatchPublishRequest"),BatchUnpublishRequest=root.lookupType("signal_msg.BatchUnpublishRequest"),BatchSubscribeRequest=root.lookupType("signal_msg.BatchSubscribeRequest"),BatchUnsubscribeRequest=root.lookupType("signal_msg.BatchUnsubscribeRequest"),JoinGroupRequest=root.lookupType("signal_msg.JoinGroupRequest"),SetGroupPropertiesRequest=root.lookupType("signal_msg.SetGroupPropertiesRequest"),DismissGroupRequest=root.lookupType("signal_msg.DismissGroupRequest"),LeaveGroupRequest=root.lookupType("signal_msg.LeaveGroupRequest"),SyncDataRequest=root.lookupType("signal_msg.SyncDataRequest"),SyncDataByIdsRequest=root.lookupType("signal_msg.SyncDataByIdsRequest"),GroupChangeLog=root.lookupType("signal_msg.GroupChangeLog"),GroupListChangeLog=root.lookupType("signal_msg.GroupListChangeLog"),SetParticipantPropertiesRequest=root.lookupType("signal_msg.SetParticipantPropertiesRequest"),QueryStreamsVerRequest=root.lookupType("signal_msg.QueryStreamsVerRequest"),QueryStreamsRequest=root.lookupType("signal_msg.QueryStreamsRequest");function _callSuper$g(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$g()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$g(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$g=function(){return!!e})()}var RtcSignaling=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$g(this,t),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return _inherits$1(t,e),_createClass$1(t,[{key:"join",value:function(e,t){return this.channel.join(e,t).then((function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}}))}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",StreamNotification.decode(t)):"serverFailover"===e?this.emit("serverFailover",ServerFailoverNotification.decode(t)):"media-message"===e?this.emit("media-message",MediaMessage.decode(t)):"group"===e?this.emit("group",GroupChangeLog.decode(t)):"group-list"===e&&this.emit("group-list",GroupListChangeLog.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;BatchNotification.decode(e).notificationItem.forEach((function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)}))}},{key:"createPeerConnection",value:function(e){var t=CreatePeerConnectionRequest.encode(e).finish();return this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=ClosePeerConnectionRequest.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=BatchSubscribeRequest.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=SetGroupPropertiesRequest.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=BatchUnsubscribeRequest.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=BatchPublishRequest.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=BatchUnpublishRequest.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=PublishRequest.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){var t=SetParticipantPropertiesRequest.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=SoacRequest.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=UnpublishRequest.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=StreamControlRequest.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=SetStreamPropertiesRequest.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=SubscribeRequest.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=UnsubscribeRequest.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=SubscriptionControlRequest.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=QueryStreamsVerRequest.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=QueryStreamsRequest.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=JoinGroupRequest.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=LeaveGroupRequest.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=DismissGroupRequest.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=SyncDataRequest.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=SyncDataByIdsRequest.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then((function(e){return e.syncDataByIdsResponse}))}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then((function(e){return e.observeAllGroupsResponse}))}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then((function(e){return e.unobserveAllGroupsResponse}))}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(i,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),n),r.channel.signaling.rpc(e,t,n).then((function(t){var n=Response.decode(t);n.code===signal_msg.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),n),i(n)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),n),o(n))})).catch((function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)}))}))}}])}(EventEmitter);function _callSuper$f(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$f()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$f(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$f=function(){return!!e})()}var Monitor=function(e){function t(){var e;_classCallCheck$1(this,t),e=_callSuper$f(this,t),Object.defineProperty(e,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var r=getReporter().statsConfig;return e.interval=(null==r?void 0:r.statsIntervalMs)||METRIC_STATS_INTERVAL,e.start(),e}return _inherits$1(t,e),_createClass$1(t,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=addTimer((function(){e.makeReport()}),this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null)}}])}(EventEmitter);function ownKeys$7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$7(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$7(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$b(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$b(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$b(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$b(e,t);var r={}.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)?_arrayLikeToArray$b(e,t):void 0}}function _arrayLikeToArray$b(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$e(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$e()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$e=function(){return!!e})()}var initAudioSendInfo={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},initVideoSendInfo={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},PublishMonitor=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$e(this,t),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var n=e.tracks.filter((function(e){return"video"===e.trackMediaType}))[0];return r.source=null==n?void 0:n.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},initVideoSendInfo),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},initAudioSendInfo),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source,trackStats:[]},initVideoSendInfo,this.connection.peerConnectionStats);if(r.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=n.frameRate;r.captureFramesPerSecond=a===1/0?0:a||0,r.captureFrameWidth=i||0,r.captureFrameHeight=o||0}var s=new Map,c=getDeltaDurationInSeconds(r,this.lastVideoSendInfo);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)){var n=s.get(e.ssrc)||{},i=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};if(n.sendFrameWidth=e.frameWidth||0,n.sendFrameHeight=e.frameHeight||0,n.framesSent=e.framesSent||0,n.framesEncoded=e.framesEncoded||0,n.targetBitrate=e.targetBitrate||0,n.qpSum=e.qpSum||0,n.bytesSent=e.bytesSent||0,n.packetsSent=e.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=e.timestamp||0,n.totalEncodeTime=e.totalEncodeTime||0,n.keyFramesEncoded=e.keyFramesEncoded||0,n.firCount=e.firCount||0,n.pliCount=e.pliCount||0,n.retransmittedBytesSent=e.retransmittedBytesSent||0,n.retransmittedPacketsSent=e.retransmittedPacketsSent||0,n.qualityLimitationReason=e.qualityLimitationReason||"",n.sendFramesPerSecond=e.framesPerSecond||0,n.sendFrameWidth>r.maxSendFrameWidth){if(r.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&i){var o=getDelta(n.framesSent||n.framesEncoded,i.framesSent||i.framesEncoded);n.sendFramesPerSecond=Math.round(o/c)}if(n.framesEncoded){var a=getDelta(n.framesEncoded,null==i?void 0:i.framesEncoded);r.encodeFramesPerSecond=Math.round(a/c)}r.sendFramesPerSecond=n.sendFramesPerSecond}s.set(e.ssrc,n),r.targetBitrate=n.targetBitrate,r.totalBytesSent+=n.bytesSent,r.totalPacketsSent+=n.packetsSent,r.totalEncodedTime+=n.totalEncodeTime,r.totalFramesEncoded+=n.framesEncoded,r.totalFramesSent+=n.framesSent,r.totalQpSum+=n.qpSum,r.maxSendFrameHeight=Math.max(n.sendFrameHeight,r.maxSendFrameHeight),s.set(e.ssrc,n)}else if(/track/i.test(e.type)&&!1===e.remoteSource){if(Environment.isSafari()){var u=s.get(e.ssrc)||{};u.sendFrameHeight>0||(u.sendFrameWidth=e.frameWidth||0,u.sendFrameHeight=e.frameHeight||0),u.framesSent=e.framesSent||0,u.totalEncodeTime=e.totalEncodeTime||0,s.set(e.ssrc,u),r.totalFramesEncoded+=u.framesEncoded,r.totalEncodedTime+=u.totalEncodeTime,r.totalFramesSent+=u.framesSent,s.set(e.ssrc,u)}}else if(/remote-inbound-rtp/i.test(e.type)){var l=s.get(e.ssrc)||{},d=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};l.packetsLost=e.packetsLost||0,l.lostTimestamp=e.timestamp,r.totalPacketsLost+=l.packetsLost,l.packetsLost===(d.packetsLost||0)&&(l.packetsSentForLost=d.packetsSentForLost||0,l.lostTimestamp=d.lostTimestamp||0),s.set(e.ssrc,l)}})),r.trackStats=s,r}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=_createForOfIteratorHelper$b(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=_slicedToArray(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=getDelta(a.framesSent,s.framesSent),u=getDelta(a.framesEncoded,s.framesEncoded),l=getDelta(a.keyFramesEncoded,s.keyFramesEncoded),d=getDelta(a.retransmittedBytesSent,s.retransmittedBytesSent),p=getDelta(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=getDelta(a.firCount,s.firCount),h=getDelta(a.pliCount,s.pliCount),m=getDelta(a.packetsSent,s.packetsSent),g=getDelta(a.packetsSentForLost,s.packetsSentForLost),v=getDelta(a.lostTimestamp,s.lostTimestamp),y=getDelta(a.sentTimestamp,s.sentTimestamp),b=getDelta(a.packetsLost,s.packetsLost),S=getDelta(a.totalEncodeTime,s.totalEncodeTime),_=getDelta(a.qpSum,s.qpSum),E=a.qualityLimitationReason,T=a.sendFrameWidth,R=_objectSpread$7(_objectSpread$7({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:E},a),{},{deltaQbSum:_,deltaPacketsSent:m,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:v,deltaFramesEncoded:u,deltaKeyFramesEncoded:l,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:h,deltaTimestampForSent:y,deltaPacketsSentForLost:g,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:p});r.push(R)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,l=getDelta(e.timestamp,this.lastVideoSendInfo.timestamp),d=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var h=f.deltaFramesEncoded||f.deltaFramesSent;d&&(d=0===h),s.attr_encoded_framerate_sim.push(_defineProperty({},p,Math.round(1e3*h/l))),s.attr_encode_qp_sim.push(_defineProperty({},p,Math.round((f.deltaQbSum||0)/(h||Number.EPSILON))));var m=f.deltaTimestampForLost,g=f.deltaTimestampForSent,v=f.deltaPacketsLost,y=f.deltaPacketsSentForLost;if(v&&y&&m&&g){var b=v/m/(y/g);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,_=Object.entries(s);S<_.length;S++){var E=_slicedToArray(_[S],2),T=E[0],R=E[1];t[T]=R.length?JSON.stringify(R):""}var C=0,w=getDelta(o,this.lastVideoSendInfo.totalFramesEncoded),O=getDelta(a,this.lastVideoSendInfo.totalEncodedTime);w&&O&&(C=Math.round(1e3*O/w));var P=getDelta(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=l,t.attr_bitrate=l>0?Math.min(Math.round(8*P*1e3/l),2e7):0,t.attr_enc_average_elapsed_ms=C,this.videoSendReport=t,d&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:l,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},initAudioSendInfo,this.connection.peerConnectionStats);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(getDelta(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*getDelta(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/getDelta(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,i=this.pc;if(!i||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then((function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e)}}))}}])}(Monitor);function _createForOfIteratorHelper$a(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$a(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$a(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$a(e,t);var r={}.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)?_arrayLikeToArray$a(e,t):void 0}}function _arrayLikeToArray$a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$d(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$d()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$d=function(){return!!e})()}function _superPropGet$1(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var initAudioReceiveInfo={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},initVideoReciveInfo={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},SubscribeMonitor=function(e){function t(e){var r,n;_classCallCheck$1(this,t),n=_callSuper$d(this,t),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.connection,o=e.transceiver,a=e.uid,s=e.stream,c=e.transceivers;return n.connection=i,n.pc=i.pc,n.tranceiver=o,n.tranceivers=c,n.firstReportTimer=addTimer((function(){n.getStats().then((function(e){n.makeFirstReport(e)}))}),400,"interval"),n.source="mcu"!==a&&(null===(r=s.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},initVideoReciveInfo),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},initAudioReceiveInfo),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return _inherits$1(t,e),_createClass$1(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=_createForOfIteratorHelper$a(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},initVideoReciveInfo,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(getDelta(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=getDelta(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=getDelta(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=getDelta(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,l=t.packetsReceivedForLost,d=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=getDelta(e.timestamp,i);if(e.bytesReceived-u>=0){var h=getDelta(e.packetsLost,a),m=getDelta(e.packetsReceivedForLost,l),g=0;try{g=Math.round(h/m*255)}catch(e){g=0}isNaN(g)&&(g=0);var v=getDelta(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*v/f),attr_dec_frames:v,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:getDelta(e.framesDropped,c),attr_fir_count:getDelta(e.firCount,r),attr_freeze_count:getDelta(e.freezeCount,o),attr_pli_count:getDelta(e.pliCount,n),attr_retx_bytes:getDelta(e.retransmittedBytesReceived,d),attr_retx_packets:getDelta(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*getDelta(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(g,255)),attr_resolution:JSON.stringify([{count:v,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,i=this.pc;if(!(i&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var o=n.map((function(e){return e.receiver.track})).filter((function(e){return!!e}));return Promise.all(o.map((function(e){return i.getStats(e)}))).then((function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}}))}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?i.getStats(r.receiver.track).then((function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}})):void 0}},{key:"stop",value:function(){_superPropGet$1(t,"stop",this)([]),this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}(Monitor),lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.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(grammar$2).forEach((function(e){grammar$2[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(r[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var s=0;s<(n[t]||[]).length;s+=1){var c=n[t][s];if(c.reg.test(i))return r(c,a,i)}})),t.media=o,t};var o=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var o=t.names[i];t.name?n.push(r[t.name][o]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach((function(t){grammar$1[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))})),e.media.forEach((function(e){i.push(makeLine("m",grammar$1.m[0],e)),n.forEach((function(t){grammar$1[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(makeLine(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;function _createForOfIteratorHelper$9(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$9(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$9(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$9(e,t);var r={}.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)?_arrayLikeToArray$9(e,t):void 0}}function _arrayLikeToArray$9(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$6(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$6(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$6(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$6(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$c(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$c()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$c=function(){return!!e})()}lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;var _getReporter$3=getReporter(),logger$2=_getReporter$3.log,Subscription=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$c(this,t),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.stream,o=e.uid,a=e.resolutionInfo,s=e.userConfigResolution;return r.connection=n,r.resolutionInfo=a,r.userConfigResolution=s,r.rtcSignaling=n.rtcSignaling,r.stream=i,r.uid=o,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[subscription]"),r.connection.once("ended",(function(){r.clear()})),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=PubSubStates.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return _inherits$1(t,e),_createClass$1(t,[{key:"handleStreamAdd",value:function(e,t){var r,n=this,i=function(){n.reporter.trace.subscribe({init:!1,capabilities:n.stream.media,remoteStreamId:n.stream.id,remoteUserId:n.uid,sessionId:n.id,elapse:Date.now()-n.startTime,resolutionInfo:n.resolutionInfo}),n.startTime=Date.now()};if(clientConfig.audioSFU&&"audio"===e.kind){var o,a=null===(o=this.transceivers)||void 0===o?void 0:o.map((function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id}));null!=a&&a.includes(e.id)&&!this._stream&&(this._stream=t,i())}else e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)&&(this._stream=new MediaStream([e]),i())}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===PubSubStates.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch((function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))}))}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=getActualResolution(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==PubSubStates.End&&(this.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:-1,remoteUserId:this.uid})}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=getDeltaDurationInSeconds(n,d),f=getDelta(n.bytesReceived,d.bytesReceived),h={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(getDelta(null==n?void 0:n.framesDecoded,d.framesDecoded)/p),receiveFrameRate:Math.round(getDelta(null==n?void 0:n.framesReceived,d.framesReceived)/p),receiveFramesDropped:getDelta(null==n?void 0:n.framesDropped,d.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},m=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),g=(null===(l=this.stream.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.source)===exports.VideoSourceInfo.CAMERA&&f>STUCK_JUDGE_RECV_BYTES&&0===h.decodeFrameRate;"network"===t&&(this.stucked&&g?m&&h.receiveFramesDropped>0&&!clientConfig.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=g),this.videoStatsMap.set(t,h)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-first-packet",(function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("audio-first-frame",(function(){e.emit("audio-first-frame")}))):(this.monitor.on("video-first-packet",(function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("video-recv-stream",(function(t){e.reporter.metric.videoRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(EventEmitter),getActualResolution=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=getStreamTypeByResolutionLevel(n);return getResolutionInfo(i,getResolutions(e))}return t},prepareForBatchSubscribe=function(e){var t,r={audio:[],video:[]},n=_createForOfIteratorHelper$9(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo;if(a)logger$2.error("skip subscribe",o,a);else{var c=getSingleMediaOption(o,s),u=c.audio,l=c.video;if(u){var d=_objectSpread$6(_objectSpread$6({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:generateSubSsrc()}]});clientConfig.audioSFU&&(d.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:generateSubSsrc()}}))),r.audio.push(d)}else if(l){var p,f;r.video.push(_objectSpread$6(_objectSpread$6({},l),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:generateSubSsrc(),rtxSsrc:generateSubSsrc()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},getSingleMediaOption=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:getActualResolution(e,t)}}return a},batchSubscribeStart=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=[],o={},t.forEach((function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var u=new Subscription(_objectSpread$6(_objectSpread$6({},r),{},{uid:s,userConfigResolution:c,resolutionInfo:c&&getActualResolution(n,c),stream:n}));o[n.id]=u}})),s=new Promise((function(e,r){a=function(){var a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function a(){var s;return _regeneratorRuntime$1.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=prepareForBatchSubscribe(t),a.next=3,adjustDownlinkSDPWhenSubscribe(n,s,o);case 3:n.rtcSignaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:clientConfig.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function r(n){var a,s,c,u,l;return _regeneratorRuntime$1.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=4;break}return i.forEach((function(e){e.error=e.error||parseSubscribeError(e.stream,s)})),r.abrupt("return",e(i));case 4:c=_createForOfIteratorHelper$9(a),r.prev=5,l=_regeneratorRuntime$1.mark((function e(){var r,n,a,s,c,l;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],l=t.findIndex((function(e){return e.stream.id===s.id})),"ok"===a&&c?(c.id=n,i[l].id=n,i[l].subscription=c):"ok"!==a&&(i[l].error=parseSubscribeError(c.stream,a));case 4:case"end":return e.stop()}}),e)})),c.s();case 8:if((u=c.n()).done){r.next=12;break}return r.delegateYield(l(),"t0",10);case 10:r.next=8;break;case 12:r.next=17;break;case 14:r.prev=14,r.t1=r.catch(5),c.e(r.t1);case 17:return r.prev=17,c.f(),r.finish(17);case 20:e(i);case 21:case"end":return r.stop()}}),r,null,[[5,14,17,20]])})));return function(e){return r.apply(this,arguments)}}()).catch(r);case 4:case"end":return a.stop()}}),a)})));return function(){return a.apply(this,arguments)}}()})),n.addTask(a),e.abrupt("return",s);case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),batchSubscribeStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,o=new Promise((function(e,r){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function n(){var o,a;return _regeneratorRuntime$1.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)})).map((function(e){return e.id})),n.next=4,adjustDownlinkSDPWhenUnsubscribe(i,t);case 4:i.rtcSignaling.batchUnSubscribe({connectionId:i.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",o);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function ownKeys$5(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$5(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$5(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$5(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$8(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$8(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$8(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$8(e,t);var r={}.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)?_arrayLikeToArray$8(e,t):void 0}}function _arrayLikeToArray$8(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var _getReporter$2=getReporter(),logger$1=_getReporter$2.log,optionzationMap={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},ssrcPrefix=0,ssrcMask=0,ssrcSeed=0,inUseSsrcSet=new Set,parseSubSsrcInfo=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(ssrcMask=e,ssrcPrefix=(t<<r|2147483648)>>>0)},generateSubSsrc=function(){if(0==ssrcPrefix||0==ssrcMask)return 0;var e=Math.min(ssrcMask+1,1e4);do{var t=ssrcPrefix+(ssrcMask&ssrcSeed++);if(0!=t&&!inUseSsrcSet.has(t))return t}while(--e>0);return 0},useSubSsrcGroup=function(e){e.ssrc&&inUseSsrcSet.add(e.ssrc),e.rtxSsrc&&inUseSsrcSet.add(e.rtxSsrc)},addRidsToMline=function(e,t){var r,n;if((null===(r=e.rids)||void 0===r?void 0:r.length)>1)return Environment.isFirefox()&&(t=addRidExtForFirefox(t)),t.rids=null===(n=e.rids)||void 0===n?void 0:n.map((function(e){return{direction:"recv",id:e.id}})),t.simulcast={dir1:"recv",list1:e.simulcast.list1},t},adjustUplinkSDPWhenApplyOptions=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=4,o.createOffer();case 4:return a=e.sent,e.next=7,o.setLocalDescription(a);case 7:return r.localSDP=lib.parse(a.sdp),s=r.localSDP.media.find((function(e){return e.mid==n.mid})),c=i.media.find((function(e){return e.mid==n.mid})),addRidsToMline(s,c),e.next=13,o.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 13:r.remoteSDP=i;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenPublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.idToTransceiverMap,o=t.remoteSDP,a=new MediaStream(r.map((function(e){return e.getMediaStreamTrack()}))),s=r.map((function(e){var r={direction:"sendonly"};if(e instanceof LocalVideoTrack){var n=getVideoBitrateMap(e).encodings;r.sendEncodings=n.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var o=t.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,r);if(e instanceof LocalVideoTrack&&o.sender.setParameters){var a=e.optimizationMode,s=o.sender.getParameters();s.degradationPreference=optionzationMap[a]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(logger$1.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach((function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,logger$1.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}}))),logger$1.info("adjustUplinkSDPWhenPublish setParameters",s),o.sender.setParameters(s)}return i.set(e.getTrackId(),o),o})),e.next=5,n.createOffer();case 5:return c=e.sent,u=lib.parse(c.sdp),e.next=9,n.setLocalDescription(c);case 9:t.localSDP=u,o.groups[0].mids=t.localSDP.groups[0].mids,l=_createForOfIteratorHelper$8(s),e.prev=12,p=_regeneratorRuntime$1.mark((function e(){var t,r,n,i,a,s,c;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=d.value,r=o.media.find((function(e){return e.type===t.sender.track.kind})),Environment.isFirefox()&&"video"===r.type&&(delete r.rids,delete r.simulcast),n=_objectSpread$5(_objectSpread$5({},r),{},{ext:_toConsumableArray(r.ext),mid:t.mid}),i=u.media.find((function(e){return e.mid==t.mid})),a=new URLSearchParams(location.search).get("startkbs")||2e3,s=new URLSearchParams(location.search).get("minkbs"),c=new URLSearchParams(location.search).get("maxkbs"),logger$1.info("startkbs, minkbs",a,s),n.fmtp.map((function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter((function(e){return!/x-google-start-bitrate/i.test(e)}));a&&clientConfig.highStartBitrate&&t.push("x-google-start-bitrate=".concat(a)),s&&t.push("x-google-min-bitrate=".concat(s)),c&&t.push("x-google-max-bitrate=".concat(c)),e.config=t.join(";")}})),addRidsToMline(i,n),o.media.push(n);case 12:case"end":return e.stop()}}),e)})),l.s();case 15:if((d=l.n()).done){e.next=19;break}return e.delegateYield(p(),"t0",17);case 17:e.next=15;break;case 19:e.next=24;break;case 21:e.prev=21,e.t1=e.catch(12),l.e(e.t1);case 24:return e.prev=24,l.f(),e.finish(24);case 27:return window.remoteSDP=o,e.next=30,n.setRemoteDescription({type:"answer",sdp:lib.write(o)});case 30:return t.remoteSDP=o,e.abrupt("return",{localSDP:t.localSDP,stream:a});case 32:case"end":return e.stop()}}),e,null,[[12,21,24,27]])})));return function(t,r){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenUnpublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map((function(e){return e.transceiver})).forEach((function(e){if(e){n.removeTrack(e.sender);var t=i.media.find((function(t){return t.mid==(null==e?void 0:e.mid)}));e.direction="inactive",t.direction="inactive"}})),e.next=5,n.createOffer();case 5:return o=e.sent,a=lib.parse(o.sdp),e.next=9,n.setLocalDescription(o);case 9:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=14,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),addSSRC=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;useSubSsrcGroup(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter((function(e){return void 0!==e})).forEach((function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:createUuid(),id:e})}))},addRidExtForFirefox=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some((function(e){return e.uri.includes("rtp-stream-id")}))||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},adjustDownlinkSDPWhenSubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E,T,R,C,w,O,P,k,I,A;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=t.pc,s=t.idToTransceiverMap,c=t.remoteSDP,u=t.idToTransceiversMap,l=c.media.find((function(e){return"video"===e.type})),d=c.media.find((function(e){return"audio"===e.type})),p=null===(i=l.ssrcs)||void 0===i?void 0:i.find((function(e){return"msid"===e.attribute})).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(h=null===(f=r.audio)||void 0===f?void 0:f[0],m=h.from,clientConfig.audioSFU){if(u.get(m)){g=_createForOfIteratorHelper$8(u.get(m));try{for(g.s();!(v=g.n()).done;)v.value.direction="recvonly"}catch(e){g.e(e)}finally{g.f()}y=c.media.filter((function(e){return"audio"===e.type})),b=_createForOfIteratorHelper$8(y);try{for(b.s();!(S=b.n()).done;)S.value.direction="sendonly"}catch(e){b.e(e)}finally{b.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})})),u.set(m,t.mcuAudioTranceivers);n[m].addTransceivers(u.get(m))}else s.get(m)||s.set(m,t.mcuAudioTranceiver),s.get(m).direction="recvonly",d.direction="sendonly",n[m].addTransceiver(s.get(m));_=_createForOfIteratorHelper$8(r.video),e.prev=6,T=_regeneratorRuntime$1.mark((function e(){var t,r,i,o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=E.value,r=t.from,i=s.get(r)){e.next=7;break}s.set(r,a.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===i.direction){e.next=18;break}return i.direction="inactive",e.next=11,a.createOffer();case 11:return o=e.sent,e.next=14,a.setLocalDescription(o);case 14:return c.media.find((function(e){return e.mid==i.mid})).direction="inactive",e.next=18,a.setRemoteDescription({type:"answer",sdp:lib.write(c)});case 18:s.get(r).direction="recvonly";case 19:n[r].addTransceiver(s.get(r));case 20:case"end":return e.stop()}}),e)})),_.s();case 9:if((E=_.n()).done){e.next=13;break}return e.delegateYield(T(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),_.e(e.t1);case 18:return e.prev=18,_.f(),e.finish(18);case 21:return e.next=23,a.createOffer();case 23:return R=e.sent,C=lib.parse(R.sdp),c.groups[0].mids=C.groups[0].mids,e.next=28,a.setLocalDescription(R);case 28:t.localSDP=C,clientConfig.audioSFU&&r.audio[0]&&(w=r.audio[0],O=w.ssrcGroup,P=w.from,u.get(P).forEach((function(e,t){var r,n=null===(r=O[t])||void 0===r?void 0:r.ssrc,i=c.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=_objectSpread$5(_objectSpread$5({},d),{},{mid:e.mid}),c.media.push(i)),i.ssrcs=getSsrcInfo(n,p),i.direction="sendonly"}))),k=_createForOfIteratorHelper$8(r.video),e.prev=31,A=_regeneratorRuntime$1.mark((function e(){var t,r,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=I.value,r=t.from,i=t.subSsrcGroup,o=s.get(r),a=c.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})),a||((a=_objectSpread$5({},l)).mid=o.mid,c.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,addSSRC(i,a,p);case 8:case"end":return e.stop()}}),e)})),k.s();case 34:if((I=k.n()).done){e.next=38;break}return e.delegateYield(A(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),k.e(e.t3);case 43:return e.prev=43,k.f(),e.finish(43);case 46:return t.remoteSDP=c,e.next=49,a.setRemoteDescription({type:"answer",sdp:lib.write(c)});case 49:case"end":return e.stop()}}),e,null,[[6,15,18,21],[31,40,43,46]])})));return function(t,r,n){return e.apply(this,arguments)}}(),adjustDownlinkSDPWhenUnsubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=_createForOfIteratorHelper$8(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,l=c.transceivers,u?o.push(u):l&&o.push.apply(o,_toConsumableArray(l))}catch(e){a.e(e)}finally{a.f()}return o.forEach((function(e){e.direction="inactive"})),e.next=7,n.createOffer();case 7:return d=e.sent,e.next=10,n.setLocalDescription(d);case 10:t.localSDP=lib.parse(d.sdp),p=_regeneratorRuntime$1.mark((function e(){var t;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=h[f],i.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),f=0,h=o;case 13:if(!(f<h.length)){e.next=18;break}return e.delegateYield(p(),"t0",15);case 15:f++,e.next=13;break;case 18:return t.remoteSDP=i,e.next=21,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 21:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),adjustRemoteSDPWhenFailover=function(e,t){var r=t.media.find((function(e){return"audio"===e.type})),n=t.media.find((function(e){return"video"===e.type}));return e.media.forEach((function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,l=t.rids,d=void 0===l?[]:l;"audio"===t.type?e.media[i]=_objectSpread$5(_objectSpread$5({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=_objectSpread$5(_objectSpread$5({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),d.length&&(e.media[i].rids=d,e.media[i].simulcast={dir1:"recv",list1:d.map((function(e){return"~".concat(e.id)})).join(";")}))})),e},adjustLocalSDPWhenFailover=function(e,t){var r=t.media;return e.media.forEach((function(e){var t=e.mid,n=e.ssrcGroups,i=void 0===n?[]:n,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex((function(e){return e.mid==t&&e.type===s}));c>-1&&(r[c]=_objectSpread$5(_objectSpread$5({},r[c]),{},{ssrcGroups:i,ssrcs:a}))})),t},getSsrcInfo=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:createUuid(),id:e}]},remoteSDPAdaptor=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"all",i=t.direction,o=t.remoteSDP,a=lib.parse(e);"relay"===n&&a.media.forEach((function(e){e.candidates=e.candidates.filter((function(e){return isPrivateIP(e.ip)}))})),r&&(a=adjustRemoteSDPWhenFailover(o,a));var s=a.media.find((function(e){return"video"===e.type}));if("uplink"===i&&Environment.isFirefox()&&clientConfig.simulcast&&(s.ext=s.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!s.ssrcs&&"downlink"===i){var c=generateSubSsrc(),u=a.msidSemantic.token;s.ssrcs=getSsrcInfo(c,u)}return t.remoteSDP=a,a},removeTransportCC=function(e){e.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!e.uri.includes("transport-wide-cc")})),e.rtcpFb=e.rtcpFb.filter((function(e){return"transport-cc"!==e.type}))}))},localSDPAdaptor=function(e,t){var r=t.direction,n=["uplink"===r,clientConfig.downlinkForbidHighProfile],i=lib.parse(e);if(n.some((function(e){return e}))&&(i=removeProfileByPrefix(i,"64")),clientConfig.disableTransportCC&&"uplink"===r&&removeTransportCC(i),"downlink"===r&&!clientConfig.downlinkForbidHighProfile){var o=[];i.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&o.push(t)})),t.subSdpFmtpLines=o}if(Environment.isFirefox()&&(i=removeProfileOfUnsetPacketzationMode(i)),"uplink"===r&&Environment.isFirefox()&&clientConfig.simulcast){var a=i.media.find((function(e){return"video"===e.type}));addRidExtForFirefox(a)}return t.localSDP=i,i},adjustOfferWhenFailover=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),l=_toConsumableArray(n.sessions.values());if("downlink"===c){var d=r.media.slice(2),p=l.filter((function(e){return e instanceof Subscription})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!clientConfig.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var h=[];u.forEach((function(e){var t={direction:e.direction},r=d.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&h.push(i))})),h.length&&f&&(e.mcuAudioTranceivers=h,s.set(f.id,h),f.addTransceivers(h))}else{var m=l.filter((function(e){return e instanceof Publication}));u.forEach((function(e){var t={direction:e.direction},r=m.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof LocalVideoTrack){var s=getVideoBitrateMap(n).encodings;t.sendEncodings=s.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}},removePayloadTypes=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=_createForOfIteratorHelper$8(n);try{for(u.s();!(r=u.n()).done;){var l=r.value,d=l.config,p=l.payload,f=d.split(";");c[p]={};var h,m=_createForOfIteratorHelper$8(f);try{for(m.s();!(h=m.n()).done;){var g=_slicedToArray(h.value.split("="),2),v=g[0],y=g[1];c[p][v]=y}}catch(e){m.e(e)}finally{m.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var _=n.length-1;_>=0;_--){var E=n[_].payload;s.includes(E)&&n.splice(_,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var R=a.length-1;R>=0;R--)s.includes(a[R].payload)&&a.splice(R,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},removeProfileByPrefix=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return removePayloadTypes(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},removeProfileOfUnsetPacketzationMode=function(e){var t=e.media.find((function(e){return"video"===e.type}));return removePayloadTypes(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function ownKeys$4(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$4(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$4(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$4(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$7(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$7(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$7(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$7(e,t);var r={}.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)?_arrayLikeToArray$7(e,t):void 0}}function _arrayLikeToArray$7(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$b(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$b()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$b=function(){return!!e})()}var _getReporter$1=getReporter(),logger=_getReporter$1.log,Publication=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$b(this,t),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.uid,o=e.tracks,a=void 0===o?[]:o;return r.tracks=a,r.connection=n,r.rtcSignaling=n.rtcSignaling,r.uid=i,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[publication]"),r.state=PubSubStates.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),r.applyOptions=r.applyOptions.bind(r),r.applyOptions=debounce(r.applyOptions,1e3,!1),a.forEach((function(e){e.on(TRACK_EVENT_NAME,r.handleTracEvent)})),r.encodings=getVideoBitrateMap(a[0]).encodings,r.state=PubSubStates.Processing,r.connection.once("ended",(function(){r.clear()})),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stop",value:function(){var e=this;return this.state!==PubSubStates.Processing?Promise.resolve():batchPublishStop([this],{connection:this.connection}).catch((function(t){e.clear(),e.logger.warn("negative ack for unpublish, ".concat(tryJsonStringify(t)))}))}},{key:"mute",value:function(){if(this.tracks.length&&this.state===PubSubStates.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!0,this.id),this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:e})}}},{key:"unmute",value:function(){if(this.tracks.length&&this.state===PubSubStates.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!1,this.id),this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:e})}}},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0];this.addTransceiver(this.connection.idToTransceiverMap.get(t.getTrackId())),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this.connection,r=this.transceiver,n=e.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=getHighestResolutionLevel(i,o);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:a});var s=getDownByScales(i,o);t.addTask(_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return logger.info("scales",s),(t=r.sender.getParameters()).encodings.forEach((function(e){e.scaleResolutionDownBy=s[e.rid]})),logger.info("handleRepublish setParameters",t),e.abrupt("return",r.sender.setParameters(t).then((function(){console.log(r.sender.getParameters().encodings)})));case 5:case"end":return e.stop()}}),e)}))))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){clientConfig.republish?n.handleRepublish(t):n.stop().then((function(){n.connection.sessionManager.serviceManager.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==PubSubStates.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(TRACK_EVENT_NAME,e.handleTracEvent)})),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(this.logger.debug("applyOptions",e),!(n<this.feedbackIndex||this.state!==PubSubStates.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask((function(){return new Promise((function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map((function(e){return e.rid})),l=_createForOfIteratorHelper$7(c.encodings);try{for(l.s();!(n=l.n()).done;){var d,p=n.value,f=_createForOfIteratorHelper$7(e);try{for(f.s();!(d=f.n()).done;){d.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){l.e(e)}finally{l.f()}if(logger.info("encodings",c.encodings),s)return logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then((function(){return adjustUplinkSDPWhenApplyOptions(t).then(r)}));r()}))}))}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof LocalVideoTrack&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask((function(){var e=n.sender.getParameters();return e.degradationPreference=optionzationMap[o]||"balanced",logger.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),adjustUplinkSDPWhenApplyOptions(t)}))}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=PubSubStates.Processing,this.feedbackIndex=-1,this.monitor=new PublishMonitor(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;this.transceiver&&(null===(t=this.transceiver.sender.track)||void 0===t||t.stop(),this.transceiver.sender.replaceTrack(e))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===d?[]:d,f=(null===(l=this.metricsMap.get(t))||void 0===l?void 0:l.videoMetrics)||{},h=getDeltaDurationInSeconds(n,f),m=getDelta(n.totalBytesSent,f.totalBytesSent),g={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*m/h};this.videoStatsMap.set(t,g)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(_objectSpread$4({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(_objectSpread$4({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(_objectSpread$4({sessionId:e.id},t))}))}}])}(EventEmitter),prepareForPublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o,a,s,c=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>2&&void 0!==c[2]?c[2]:["common"],i={},e.next=4,adjustUplinkSDPWhenPublish(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof LocalVideoTrack){var c;i.video=i.video||[];var u=o.ssrcGroups,l=void 0===u?[]:u,d=getVideoBitrateMap(e),p=d.encodings,f=d.resolutionLevel;p.length>1&&(l=p.map((function(){return{semantics:"FID",ssrcs:"".concat(generateSubSsrc()," ").concat(generateSubSsrc())}})));var h=l.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),m=p[p.length-1],g={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:h,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==h||null===(c=h[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(m.maxBitrate),resolution:{width:m.targetWidth,height:m.targetHeight},framerate:m.maxFramerate},ssrcParameters:h.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}}))};i.video.push(g)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),batchPublishStart=function(e){var t,r=e.tracks,n=e.connection,i=e.labels,o=r.map((function(t){return{publication:new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[t]})),track:t}})),a=new Promise((function(e,a){t=function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function t(){var s,c;return _regeneratorRuntime$1.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,prepareForPublish(r,n,i);case 2:return s=t.sent,c={connectionId:n.id,media:s,simulcast:clientConfig.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.rtcSignaling.batchPublish(c).then(function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function t(r){var n,i,a,s,c;return _regeneratorRuntime$1.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=4;break}return o.forEach((function(e){e.error=parsePublishError(e.track,i)})),t.abrupt("return",e(o));case 4:a=_createForOfIteratorHelper$7(n),t.prev=5,c=_regeneratorRuntime$1.mark((function e(){var t,r,n,i,a,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,a=o.findIndex((function(e){return e.track.getTrackId()===n.id})),c=o[a]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(o[a].error=parsePublishError(o[a].track,i));case 4:case"end":return e.stop()}}),e)})),a.s();case 8:if((s=a.n()).done){t.next=12;break}return t.delegateYield(c(),"t0",10);case 10:t.next=8;break;case 12:t.next=17;break;case 14:t.prev=14,t.t1=t.catch(5),a.e(t.t1);case 17:return t.prev=17,a.f(),t.finish(17);case 20:e(o);case 21:case"end":return t.stop()}}),t,null,[[5,14,17,20]])})));return function(e){return t.apply(this,arguments)}}()).catch((function(e){logger.info("batchPublishStart error",e),a(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),a},batchPublishStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise((function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function n(){var o,a;return _regeneratorRuntime$1.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),n.next=4,adjustUplinkSDPWhenUnpublish(r.connection,t);case 4:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(i);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function _callSuper$a(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$a()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$a=function(){return!!e})()}var initPeerConnectionMetrics={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},PeerConnectionMonitor=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$a(this,t),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},initPeerConnectionMetrics)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractMetrics",value:function(e){var t=Object.assign({},this.connectionMetrics),r="";return e.forEach((function(e){var n;if(!e.isRemote)if(/local-candidate/i.test(e.type)&&e.id===r)Environment.networkType=(null!==(n=e.networkType)&&void 0!==n?n:Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(e.type)&&"succeeded"===e.state)r=e.localCandidateId,Environment.isFirefox()||(t.roundTripTime=1e3*(e.currentRoundTripTime||e.totalRoundTripTime/e.responsesReceived)),void 0!==e.availableOutgoingBitrate&&(t.availableOutgoingBitrate=e.availableOutgoingBitrate);else if(/codec/i.test(e.type)){var i,o;null!==(i=e.mimeType)&&void 0!==i&&i.includes("audio")?t.audioCodec=e.mimeType.replace("audio/",""):null!==(o=e.mimeType)&&void 0!==o&&o.includes("video")&&(t.videoCodec=e.mimeType.replace("video/",""),t.sdpFmtpLine=e.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},t),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then((function(t){return e.extractMetrics(t)}))}}])}(Monitor);function _createForOfIteratorHelper$6(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$6(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$6(e,t);var r={}.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)?_arrayLikeToArray$6(e,t):void 0}}function _arrayLikeToArray$6(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$9(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$9()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$9(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$9=function(){return!!e})()}var icePolicyMap={uplink:"",downlink:""},PeerConnection=function(e){function t(e){var r,n;_classCallCheck$1(this,t),r=_callSuper$9(this,t),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pendingTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:PeerConnectionState.New}),Object.defineProperty(r,"exchangeSdpTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,n=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&void 0!==n[0]&&n[0],"uplink"===r.direction?(r.pc.addTransceiver("audio",{direction:"sendonly"}),r.pc.addTransceiver("video",{direction:"sendonly"})):(r.mcuAudioStream=null,r.mcuAudioTranceiver=r.pc.addTransceiver("audio",{direction:"recvonly"}),r.pc.addTransceiver("video",{direction:"recvonly"})),t&&adjustOfferWhenFailover(r),e.next=5,r.exchangeSDP(t);case 5:r.state=PeerConnectionState.Idle,r.enquenTask.start();case 7:case"end":return e.stop()}}),e)}))),function(){return n.apply(this,arguments)})}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.logger.info("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),r.pc=null;var i=e.direction,o=e.sessionManager;return r.rtcSignaling=o.serviceManager.rtcSignaling,r.sessionManager=o,r.reporter=o.reporter,r.logger=r.reporter.getLoggerWithPrefix("[peerconn]"),r.enquenTask=taskQueue(),r.subSdpFmtpLines=[],r.direction=i,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(createUuid()),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"reset",value:function(){this.pendingTask&&(this.pendingTask=null)}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?clientConfig.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==PeerConnectionState.Ended&&(this.state=PeerConnectionState.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"clearPcForReoffer",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==PeerConnectionState.New){e.next=2;break}return e.abrupt("return",Promise.reject());case 2:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),e.prev=3,e.next=6,this.stopSinglePC(!0);case 6:this.removeAllListeners(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(3),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(tryJsonStringify(e.t0)));case 12:this.closePeerConnection();case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),this.logger.info("connectionId:".concat(this.id," connection state changed to ").concat(t)),"failed"===t||"closed"===t?(this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=addTimer((function(){e.state!==PeerConnectionState.New&&(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))}),SIGNAL_CALL_TIMEOUT)):"connected"===t&&(this.clientFailoverTimer&&(removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(removeTimer(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var e=this.sessionManager.serviceManager.iceConfig,t=e.username,r=e.password,n=e.port,i=e.iceServerList,o={bundlePolicy:"max-bundle",iceTransportPolicy:i.length?"relay":"all",sdpSemantics:"unified-plan"};if(i.length){var a,s=[],c=_createForOfIteratorHelper$6(i);try{for(c.s();!(a=c.n()).done;){var u=a.value;s.push("turn:".concat(u,":").concat(n,"?transport=udp"),"turn:".concat(u,":").concat(n,"?transport=tcp"))}}catch(e){c.e(e)}finally{c.f()}Environment.isFirefox()&&s.splice(4,2),"relay"===icePolicyMap[this.direction]&&(icePolicyMap[this.direction]="all",o.iceTransportPolicy="all"),o.iceServers=[{urls:s,username:t,credential:r}]}return icePolicyMap[this.direction]=o.iceTransportPolicy,this.logger.info("PeerConnectionConfig",o),o}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.logger.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=addTimer((function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.exchangeSdpTask||(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))}),CREATE_PC_TIMEOUT))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new PeerConnectionMonitor(this),this.monitor.on("metrics",(function(t){e.peerConnectionStats=t})))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then((function(e){r.peerConnectionStats=e})):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&removeTimer(this.createPeerConnectionTimer),this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"startTask",value:function(){var e=this;return new Promise((function(t,r){e.pendingTask={resolve:t,reject:r},e.exchangeSDP(),addTimer((function(){var t;e.pendingTask&&e.state===PeerConnectionState.Processing&&(null===(t=e.pendingTask)||void 0===t||t.reject(),e.fireEndedEvent())}),SUB_PUB_TIMEOUT)}))}},{key:"exchangeSDP",value:function(){var e,t=this,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return new Promise((function(n,i){t.exchangeSdpTask={resolve:n,reject:i},t.pc.createOffer().then((function(n){return e=n,r&&(e.sdp=lib.write(adjustLocalSDPWhenFailover(t.localSDP,lib.parse(e.sdp)))),t.pc.setLocalDescription(e).catch((function(e){throw t.logger.error("connectionId:".concat(t.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){t.logger.info("connectionId:".concat(t.id," set local sdp success"));var o=localSDPAdaptor(e.sdp,t);e.sdp=lib.write(o),t.offerSDP=o,e.sdp=lib.write(o);var a,s={direction:"downlink"!==t.direction?"in":"out",sdpOffer:e.sdp,connectionId:t.id,isFailover:r,optionsJsonStr:JSON.stringify({supportCVO:1})};if(r){var c=lib.parse(e.sdp);c.media=c.media.slice(0,2),c.groups=[{mids:"0 1",type:"BUNDLE"}],s.sdpOffer=lib.write(c)}tryTimes({key:"createPeerConnection_".concat(t.direction),fn:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===(null===(n=t.sessionManager)||void 0===n||null===(n=n.serviceManager)||void 0===n||null===(n=n.client)||void 0===n?void 0:n.connectionState)){e.next=2;break}return e.abrupt("return");case 2:if(s.isFailover||!t.prevId){e.next=7;break}return e.next=5,t.stopSinglePC(!0);case 5:t.id="".concat(t.direction,"_").concat(createUuid()),s.connectionId=t.id;case 7:return t.prevId=t.id,e.abrupt("return",t.rtcSignaling.createPeerConnection(s).then((function(e){var n=e.sdpAnswer,i=remoteSDPAdaptor(n,t,r,icePolicyMap[t.direction]);t.pc.setRemoteDescription({sdp:lib.write(i),type:"answer"}).then((function(){var e;t.logger.info("connectionId:".concat(t.id," receive answer success")),null===(e=t.exchangeSdpTask)||void 0===e||e.resolve(),t.exchangeSdpTask=void 0})).catch((function(e){var r,n;t.logger.error("connectionId:".concat(t.id," Set remote description failed: ").concat(e)),null===(r=t.exchangeSdpTask)||void 0===r||r.reject(e),t.exchangeSdpTask=void 0,null===(n=t.pendingTask)||void 0===n||n.reject(new DingRTCError(ErrorCode.IceConnectionAnswerFail)),t.fireEndedEvent()}))})));case 9:case"end":return e.stop()}}),e)}))),function(){return a.apply(this,arguments)}),times:3,interval:2e3,reject:i,resolve:n})})).catch((function(e){var r,n;t.logger.error("connectionId:".concat(t.id," Failed to create offer or set SDP. Message: ").concat(e.message)),null===(r=t.pendingTask)||void 0===r||r.reject(new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail)),t.fireEndedEvent(),null===(n=t.exchangeSdpTask)||void 0===n||n.reject(e),t.exchangeSdpTask=void 0}))}))}},{key:"reoffer",value:function(){return this.state===PeerConnectionState.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=PeerConnectionState.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){clientConfig.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}(EventEmitter);function ownKeys$3(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$3(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$3(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$3(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _createForOfIteratorHelper$5(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$5(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$5(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$5(e,t);var r={}.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)?_arrayLikeToArray$5(e,t):void 0}}function _arrayLikeToArray$5(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$8(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$8()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$8(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$8=function(){return!!e})()}var media_reconnect_duration_ms=45e3,media_reconnect_single_round_min_duration_ms=2e3,SessionManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$8(this,t),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.serviceManager=r,n.client=e,n.reporter=r.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),n.streamIdToSessionId=new Map,n.sessions=new Map,n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n.handleRepulish=n.handleRepulish.bind(n),n.handleResubscribe=n.handleResubscribe.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"getOrCreatePeerConnection",value:(m=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=10;break}if(this.uplink){e.next=7;break}return this.uplink=new PeerConnection({direction:t,sessionManager:this}),e.next=5,this.uplink.startSinglePC();case 5:this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){r.uplink=null}));case 7:return e.abrupt("return",this.uplink);case 10:if(this.downlink){e.next=16;break}return this.downlink=new PeerConnection({direction:t,sessionManager:this}),e.next=14,this.downlink.startSinglePC();case 14:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){r.downlink=null}));case 16:return e.abrupt("return",this.downlink);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return m.apply(this,arguments)})},{key:"handleRepulish",value:(h=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this.logger.info("handle repub"),r=_toConsumableArray(this.client.localTracks),n=_createForOfIteratorHelper$5(this.sessions.values());try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Publication&&o.state===PubSubStates.Processing&&(o.clear(),this.sessions.delete(o.id))}catch(e){n.e(e)}finally{n.f()}this.client.emit("media-reconnect-start",this.client.userId),a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+media_reconnect_duration_ms,u=!1,l=0;case 10:if(!(l<23&&Date.now()<=c)){e.next=42;break}if(!((d=Date.now())<s+l*media_reconnect_single_round_min_duration_ms)){e.next=15;break}return e.next=15,asyncDelayMs(s+l*media_reconnect_single_round_min_duration_ms-d);case 15:if(this.logger.debug("repub round=".concat(l,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=18;break}return e.abrupt("continue",39);case 18:return e.prev=18,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(l,", clearPcForReoffer start ").concat(r.map((function(e){return e.trackMediaType})).join())),e.next=23,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 23:if(this.uplink=null,this.logger.info("repub round=".concat(l,", batchPublish start ").concat(r.map((function(e){return e.trackMediaType})).join())),!r.length){e.next=29;break}return e.next=28,this.batchPublish(r);case 28:this.logger.info("".concat(this.client.userId," batchPublish finished for repub"));case 29:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),u=!0,e.abrupt("break",42);case 36:e.prev=36,e.t0=e.catch(18),this.logger.error("".concat(this.client.userId," republish failed for"),e.t0);case 39:l++,e.next=10;break;case 42:u||(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),this.client.emit("media-reconnect-end",this.client.userId),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error"));case 43:case"end":return e.stop()}}),e,this,[[18,36]])}))),function(){return h.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(f=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 3:r=[],n=_createForOfIteratorHelper$5(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Subscription&&o.state===PubSubStates.Processing&&(r.push({stream:o.stream,uid:o.uid,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=9,e.next=12,this.batchUnscribe(r);case 12:return e.next=14,this.batchSubscribe(r);case 14:s=e.sent,c=_createForOfIteratorHelper$5(s);try{for(c.s();!(u=c.n()).done;)l=u.value,d=l.subscription,p=l.error,d&&!p&&this.handleSubscribeReoffer(d)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=25;break;case 20:e.prev=20,e.t0=e.catch(9),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),e.t0),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 25:case"end":return e.stop()}}),e,this,[[9,20]])}))),function(e){return f.apply(this,arguments)})},{key:"handleResubscribe",value:(p=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,m,g,v,y,b,S,_,E=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=E.length>0&&void 0!==E[0]&&E[0],this.logger.info("handle resub fromServer=",r),n=r?"server":"client",i=[],o=_createForOfIteratorHelper$5(this.sessions.values());try{for(o.s();!(a=o.n()).done;)(s=a.value)instanceof Subscription&&s.state===PubSubStates.Processing&&(i.push({stream:s.stream,uid:s.uid}),this.removeSession(s.id))}catch(e){o.e(e)}finally{o.f()}c=i.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",c),this.logger.info("resubscribe start ".concat(c)),u=null===(t=this.downlink)||void 0===t?void 0:t.id,l=Date.now(),d=l+media_reconnect_duration_ms,p=!1,f=0;case 14:if(!(f<23&&Date.now()<=d)){e.next=46;break}if(!((h=Date.now())<l+f*media_reconnect_single_round_min_duration_ms)){e.next=19;break}return e.next=19,asyncDelayMs(l+f*media_reconnect_single_round_min_duration_ms-h);case 19:if(this.logger.debug("resub round=".concat(f,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=22;break}return e.abrupt("continue",43);case 22:return e.prev=22,this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferStart")),e.next=26,null===(m=this.downlink)||void 0===m?void 0:m.clearPcForReoffer();case 26:if(this.downlink=null,!i.length){e.next=33;break}return e.next=30,this.batchSubscribe(i);case 30:g=e.sent,v=_createForOfIteratorHelper$5(g);try{for(v.s();!(y=v.n()).done;)b=y.value,S=b.subscription,_=b.error,S&&!_&&this.handleSubscribeReoffer(S)}catch(e){v.e(e)}finally{v.f()}case 33:return this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferSuccess")),this.logger.debug("resub round=".concat(f," resubscribe ").concat(c," success")),this.client.emit("media-reconnect-end",c),p=!0,e.abrupt("break",46);case 40:e.prev=40,e.t0=e.catch(22),this.logger.debug("resub round=".concat(f," resubscribe failed for"),e.t0);case 43:f++,e.next=14;break;case 46:p||(this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferFailed")),this.client.emit("media-reconnect-end",c),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error"));case 47:case"end":return e.stop()}}),e,this,[[22,40]])}))),function(){return p.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return this.sessions.get(this.streamIdToSessionId.get(e))}},{key:"handleSubscribeReoffer",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(clientConfig.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var l=this.serviceManager.rtcUserManager.remoteUsers.find((function(e){return e.userId===r}));a&&null!=l&&l.auxiliaryTrack&&i?l.auxiliaryTrack.replaceTrack(a):a&&null!=l&&l.videoTrack&&!i&&l.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,n=e.actions,i=_createForOfIteratorHelper$5(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,l=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then((function(){t.logger.info("".concat(u," republish ").concat(l.map((function(e){return e.trackMediaType})).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)})).catch((function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")}))}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?NetworkQualityType.BAD:e>30||t>450?NetworkQualityType.POOR:e>20||t>300?NetworkQualityType.NORMAL:e>10||t>200?NetworkQualityType.GOOD:e>=0||t>=0?NetworkQualityType.GREAT:NetworkQualityType.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(d=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=_toConsumableArray(this.sessions.values())).length){e.next=4;break}return this.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN),e.abrupt("return");case 4:if(0!==t.filter((function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)})).length){e.next=8;break}return this.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED),e.abrupt("return");case 8:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then((function(e){var t=_slicedToArray(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,l=0,d=0,p=0;if(n){var f=n.camera,h=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,d=Math.max(d,f.rtt||0)),h&&(c+=h.sendPacketsLost,s+=h.sendPackets,d=Math.max(d,h.rtt||0))}for(var m in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,d=Math.max(d,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,l+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var g=a[m],v=g.camera,y=g.auxiliary;v&&(u+=v.receivePacketsLost,l+=v.receivePackets,p=Math.max(p,v.rtt||0)),y&&(u+=y.receivePacketsLost,l+=y.receivePackets,p=Math.max(p,y.rtt||0))}var b=-1,S=-1,_={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:l};if(s){var E,T,R=c-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsLost)||0);if(R<0&&(R=c),_.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==R){var C;_.totalUplinkPacketsSentForLost=s;var w=s-((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalUplinkPacketsSentForLost)||0);w<0&&(w=s),b=R/w}}if(l){var O,P,k,I,A=u-((null===(O=r.lastChannelNetworkQuality)||void 0===O?void 0:O.totalDownlinkPacketsLost)||0);A<0&&(A=u),_.totalDownlinkPacketsRecvForLost=(null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalDownlinkPacketsRecvForLost)||0,null===(k=r.lastChannelNetworkQuality)||void 0===k||k.totalDownlinkPacketsRecvForLost,A&&(u!==((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0)&&(_.totalDownlinkPacketsRecvForLost=l),S=A/l)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),d),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=_}));case 9:case"end":return e.stop()}}),e,this)}))),function(){return d.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e))}},{key:"batchPublish",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t,r){var n,i,o=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return i=e.sent,e.abrupt("return",batchPublishStart({uid:this.client.userId,tracks:t,connection:i,labels:r}).then((function(e){var t,r=_createForOfIteratorHelper$5(e);try{var i=function(){var e=t.value,r=e.error,i=e.publication,a=e.track;r?o.reporter.trace.publish(!1,a,"",Date.now()-n):(o.addSession(a.getTrackId(),i),o.reporter.trace.publish(!0,a,i.id,Date.now()-n),o.reporter.trace.publish(!1,a,i.id,Date.now()-n),i.on("ended",(function(){o.removeSession(i.id)})))};for(r.s();!(t=r.n()).done;)i()}catch(e){r.e(e)}finally{r.f()}})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return l.apply(this,arguments)})},{key:"batchUnPublish",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return",Promise.resolve());case 2:return e.next=4,this.getOrCreatePeerConnection("uplink");case 4:return r=e.sent,e.abrupt("return",batchPublishStop(t,{connection:r}).then((function(){var e,r=_createForOfIteratorHelper$5(t);try{for(r.s();!(e=r.n()).done;){var i,o,a,s=e.value;n.streamIdToSessionId.delete(null===(i=s.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=(a=i).getTrackId)||void 0===o?void 0:o.call(a)),n.removeSession(s.id)}}catch(e){r.e(e)}finally{r.f()}})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,i=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(r){var o;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getOrCreatePeerConnection("downlink");case 2:return o=e.sent,e.abrupt("return",batchSubscribeStart(r,{connection:o}).then(function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(o){var a,s,c,u;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<o.length;c++)"RoomBusy"===(null===(u=o[c].error)||void 0===u?void 0:u.message)&&(s.push(r[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){e.next=12;break}return n++,e.next=7,awaitTime(1);case 7:if("connected"!==t.client.connectionState){e.next=12;break}return e.next=10,i(s);case 10:e.sent.forEach((function(e,t){var r=a.get(t);o[r]=e}));case 12:return e.abrupt("return",o);case 13:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();return i(e).then((function(e){var n,i=_createForOfIteratorHelper$5(e);try{var o=function(){var e=n.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;o&&(t.reporter.trace.subscribe({init:!0,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:a,resolutionInfo:u}),"mcu"===o.uid&&t.reporter.trace.subscribe({init:!1,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:o.id,resolutionInfo:u}),t.addSession(s.id,o),o.on("ended",(function(){t.logger.info("remove subscription for ended",a),t.removeSession(a)}))),i&&(t.logger.error("batchSubscribe error",s,i),t.reporter.trace.subscribe({init:!1,capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:"",resolutionInfo:u}))};for(i.s();!(n=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return t.logger.info("batchSubscribe result",null==e?void 0:e.map((function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}}))),e}))}},{key:"batchUnscribe",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))})),e.next=6,this.getOrCreatePeerConnection("downlink");case 6:return o=e.sent,e.abrupt("return",batchSubscribeStop(n,{connection:o}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r})));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach((function(e){r.removeSession(e.id)})),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(removeTimer(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return this.uplink=e.sent,e.next=6,this.getOrCreatePeerConnection("downlink");case 6:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 9:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=addTimer((function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",NetworkQualityType.BAD,NetworkQualityType.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN)}),NETWORK_QUALITY_TIMEOUT,"interval")}},{key:"getLocalAudioStats",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter((function(e){var t,r;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"getLocalVideoStats",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,m=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=m.length>0&&void 0!==m[0]?m[0]:"network",i=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType})),e.next=4,Promise.all(i.map((function(e){return e.getMetrics(n)})));case 4:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter((function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")})).map((function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex((function(e){return e.includes("profile-level-id")}));return r[n].split("=")[1]})))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find((function(e){return"video"===e.type})),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find((function(e){return"video"===e.type})),c={uplinkProfile:_toConsumableArray(new Set(o(a))),downlinkProfile:_toConsumableArray(new Set(o(s)))},u=_createForOfIteratorHelper$5(i),e.prev=9,u.s();case 11:if((l=u.n()).done){e.next=21;break}if(d=l.value,p=d.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=d.tracks,h=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[h?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return o.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video})),e.next=4,Promise.all(r.map((function(e){return e.getMetrics(t)})));case 4:n={},i=_createForOfIteratorHelper$5(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,l=s.stream,d=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=l.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=_objectSpread$3(_objectSpread$3({},n[u]||{}),{},_defineProperty({},p,d));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return i.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter((function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(t){var r,n,i,o,a;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=4;break}return e.abrupt("return");case 4:n=_toConsumableArray(this.sessions.values()).filter((function(e){return e instanceof Publication&&e.state===PubSubStates.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA})),i=_createForOfIteratorHelper$5(n),e.prev=6,a=_regeneratorRuntime$1.mark((function e(){var t,n;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter((function(e){return e.mid==t.transceiver.mid}))).length&&t.applyOptions(n);case 3:case"end":return e.stop()}}),e)})),i.s();case 9:if((o=i.n()).done){e.next=13;break}return e.delegateYield(a(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),i.e(e.t1);case 18:return e.prev=18,i.f(),e.finish(18);case 21:case"end":return e.stop()}}),e,this,[[6,15,18,21]])}))),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c,u,l,d,p,f,h,m}(EventEmitter);function _createForOfIteratorHelper$4(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$4(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$4(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$4(e,t);var r={}.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)?_arrayLikeToArray$4(e,t):void 0}}function _arrayLikeToArray$4(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$7(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$7()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$7(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$7=function(){return!!e})()}var PropertyNameMap={name:"name"},GroupManager=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$7(this,t),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"joinedIds",get:function(){var e=this.serviceManager.rtcUserManager.currentPid,t=new Set;return this.groups.forEach((function(r){var n=r.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.serviceManager.rtcUserManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,i=e.userData;if(this.joinedIds.has(n))throw new DingRTCError(ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:i,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new DingRTCError(ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:t,reasonCode:signal_msg.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new DingRTCError(ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find((function(t){return t.pid===e.pid}))&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex((function(t){return t.pid===e.pid}));i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||n!==signal_msg.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.logger.info("on group event:",e);var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==signal_msg.OptType.OPT_TYPE_ADD||u){if(s===signal_msg.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===signal_msg.OptType.OPT_TYPE_UPDATE){var l=c.updateAction,d=c.participants;if(u&&(u.ver+1===o||r)){if(l===signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map((function(e){return e.pid})),h=_createForOfIteratorHelper$4(d);try{for(h.s();!(p=h.n()).done;){var m=p.value;f.includes(m.pid)||(u.participants.push(m),this.emit("group","user-join",i,{userId:m.uid,userData:m.userData}))}}catch(e){h.e(e)}finally{h.f()}}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=d.map((function(e){return e.pid})),v=_toConsumableArray(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),v.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(i," audioStream lost"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(i," audioStream recover"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach((function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach((function(t){t.key===e.key&&(t.value=e.value,r=!1)})),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(PropertyNameMap[e.key]),value:e.value})}));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var y,b=c.properties.map((function(e){return e.key}));u.properties=null===(y=u.properties)||void 0===y?void 0:y.filter((function(e){var t=e.key;return!b.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(PropertyNameMap[e.key])})}))}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],l=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),d=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==l[e.key]})),h=c.filter((function(e){return!l.has(e.key)})),m=a.filter((function(e){return!d.includes(e.pid)})),g=u.filter((function(e){return!p.includes(e.pid)}));m.length&&t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:m}},!0),g.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:g}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:h}},!0)}else t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:signal_msg.DataType.DATA_TYPE_GROUP,ids:e.map((function(e){return{id:e}}))}).then((function(e){e.fullSync.groupData.groupInfos.forEach((function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)}))}))}},{key:"syncGroupList",value:function(){var e=this;this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then((function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter((function(t){return!e.groupIds.has(t)})),s=_toConsumableArray(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}(EventEmitter);function _callSuper$6(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$6()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$6(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$6=function(){return!!e})()}var User=function(e){function t(e,r){var n;_classCallCheck$1(this,t),n=_callSuper$6(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.user;return n.userId=i,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.serviceManager=r,n.joinedTime=Date.now(),n.update(e),n}return _inherits$1(t,e),_createClass$1(t,[{key:"relatedStreams",get:function(){var e=this;return _toConsumableArray(this.serviceManager.streamManager.streams.values()).filter((function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id}))}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some((function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST}))}},{key:"hasVideo",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.CAMERA}))}},{key:"hasAudio",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===exports.AudioSourceInfo.MIC}))}},{key:"audioMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC}))}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST}))}},{key:"videoMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.CAMERA}))}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==SdkType$1.Web&&e){var r=e.split("");r[ClientUserStats.UPLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.UPLINK]),r[ClientUserStats.DOWNLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[USER_STATS_SYNC])&&(this.properties[USER_STATS_SYNC]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[USER_STATS_SYNC])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=updateRemoteTrack(e.mediaStream,"video",this.userId,r);return r||i.once("first-frame-decoded",(function(){e.handleVideoFirstFrame()})),t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}(EventEmitter);function _createForOfIteratorHelper$3(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$3(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$3(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$3(e,t);var r={}.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)?_arrayLikeToArray$3(e,t):void 0}}function _arrayLikeToArray$3(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$5(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$5()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$5(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$5=function(){return!!e})()}var RtcUserManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$5(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.serviceManager=e,n.reporter=e.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-userMgr]"),n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){var e=this;return uniqBy(_toConsumableArray(this.users.values()).sort((function(e,t){return e.joinedTime-t.joinedTime})),"userId").filter((function(t){return t.userId&&t.id!==e.currentPid}))}},{key:"init",value:function(e,t){var r,n=_createForOfIteratorHelper$3(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new User(i,this.serviceManager);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var n=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new User(t,this.serviceManager);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map((function(e){return e.id})));_toConsumableArray(this.streamManager.streams.values()).filter((function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)})).map((function(e){return e.id})).forEach((function(e){return n.streamManager.remove(e,!0)}));var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new User(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(_defineProperty({},USER_STATS_SYNC,e))})}}])}(EventEmitter);function _createForOfIteratorHelper$2(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$2(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}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,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$2(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$2(e,t);var r={}.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)?_arrayLikeToArray$2(e,t):void 0}}function _arrayLikeToArray$2(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread$2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _callSuper$4(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$4()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$4(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_isNativeReflectConstruct$4=function(){return!!e})()}var StreamManager=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$4(this,t),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var n=e.rtcSignaling,i=e.reporter;return r.rtcSignaling=n,r.reporter=i,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.sync=r.sync.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find((function(e){return"admin"===e.info.owner&&"mixed"===e.type}));null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map((function(e){return[e.id,e]}))),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=_toConsumableArray(this.streams.values()).find((function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s}));c&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===VideoSourceInfo.SCREENCAST;((null==o?void 0:o.source)===VideoSourceInfo.CAMERA||u)&&this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u}),(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIC&&(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","add",{id:r,owner:n,mediaType:"audio"})}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===VideoSourceInfo.SCREENCAST;((null==i?void 0:i.source)===VideoSourceInfo.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIC&&(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return _toConsumableArray(this.streams.values()).find((function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e}))}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties","highestResolutionLevel"]}[i];c.length&&!c.includes(a.field)||this.logger.info("streamEvent",e);var u=this.totalVer;if(s===u+1||s==IGNOGRED_VERSION||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var l=a.field,d=a.streamStatus,p=a.activeStream,f=a.extraValue,h=a.streamVer,m=a.propertiesJsonStr,g=a.highestResolutionLevel,v=this.streams.get(n);if(v){h!==IGNOGRED_VERSION&&(v.version=h);var y=v.media,b=y.audio,S=y.video,_=v.info.owner;if("audio.status"===l||"video.status"===l){var E;"audio.status"===l?(E="audio",b.status=d):"video.status"===l&&(E="video",S.status=d),this.reporter.trace.streamsEvent(n,"".concat(E," ").concat(d));var T="active"===d?"unmute":"mute";this.emit("stream","update",{owner:_,id:n,updateStatus:"".concat(T,"-").concat(E)})}else if("activeInput"===l){var R=[p].concat(f||[]).map((function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner})).filter((function(e){return!!e}));this.reporter.trace.streamsEvent(JSON.stringify(R),l),this.emit("stream","volumeActive",{owners:R})}else if("properties"==l){var C,w=JSON.parse(m);v.info.attributesJsonStr=JSON.stringify(_objectSpread$2(_objectSpread$2({},JSON.parse(v.info.attributesJsonStr)),w));var O=(null===(C=v.media)||void 0===C||null===(C=C.video)||void 0===C?void 0:C.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,properties:w,auxiliary:O})}else"highestResolutionLevel"===l&&(v.media.video.highestResolutionLevel=g,this.emit("stream","update",{owner:_,id:n,highestResolutionLevel:g}))}}t||s<=this.totalVer&&s!==IGNOGRED_VERSION||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&this.sync())}},{key:"sync",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h=this;return _regeneratorRuntime$1.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=4,this.rtcSignaling.getStreamsVer({});case 4:n=e.sent,i=n.streamVersions,o=n.totalVer,a=_toConsumableArray(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=_createForOfIteratorHelper$2(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,l=u.streamId,d=u.streamVer,!l.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(l))?p&&p.version!==d&&t.push(l):(r.push(l),t.push(l));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),a.filter((function(e){return!f.includes(e)})).forEach((function(e){h.handleEvent({status:"remove",streamId:e,stream:h.streams.get(e),totalVer:o},!0)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=34;break}return e.abrupt("return");case 34:this.rtcSignaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=_createForOfIteratorHelper$2(h.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,l=_createForOfIteratorHelper$2(o);try{for(l.s();!(u=l.n()).done;){var d=u.value;h.streams.has(d.id)?h.streams.set(d.id,d.stream):a.set(d.id,d.stream)}}catch(e){l.e(e)}finally{l.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var m=p[f];r.includes(m.id)&&h.handleEvent({status:"add",streamId:m.id,stream:m,totalVer:i},!0)}a.clear(),h.totalVer=i}));case 35:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}(EventEmitter),wasm=null;
|
|
17
17
|
/**
|
|
18
18
|
* @license
|
|
19
19
|
* Copyright 2009 The Closure Library Authors
|