/** * AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTC=t()}(this,(function(){"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n=function(e){try{return!!e()}catch(e){return!0}},r=!n((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),o=r,s=Function.prototype,a=s.call,c=o&&s.bind.bind(a,a),d=o?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math==Math&&e},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||function(){return this}()||t||Function("return this")(),p=r,_=Function.prototype,E=_.apply,f=_.call,m="object"==typeof Reflect&&Reflect.apply||(p?f.bind(E):function(){return f.apply(E,arguments)}),T=d,S=T({}.toString),g=T("".slice),R=function(e){return g(S(e),8,-1)},C=R,I=d,v=function(e){if("Function"===C(e))return I(e)},y="object"==typeof document&&document.all,A={all:y,IS_HTMLDDA:void 0===y&&void 0!==y},b=A.all,w=A.IS_HTMLDDA?function(e){return"function"==typeof e||e===b}:function(e){return"function"==typeof e},O={},N=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),D=r,P=Function.prototype.call,L=D?P.bind(P):function(){return P.apply(P,arguments)},k={},M={}.propertyIsEnumerable,U=Object.getOwnPropertyDescriptor,x=U&&!M.call({1:2},1);k.f=x?function(e){var t=U(this,e);return!!t&&t.enumerable}:M;var V,F,B=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},j=n,G=R,W=Object,H=d("".split),K=j((function(){return!W("z").propertyIsEnumerable(0)}))?function(e){return"String"==G(e)?H(e,""):W(e)}:W,Y=function(e){return null==e},q=Y,z=TypeError,J=function(e){if(q(e))throw z("Can't call method on "+e);return e},X=K,Q=J,Z=function(e){return X(Q(e))},$=w,ee=A.all,te=A.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:$(e)||e===ee}:function(e){return"object"==typeof e?null!==e:$(e)},ie={},ne=ie,re=h,oe=w,se=function(e){return oe(e)?e:void 0},ae=function(e,t){return arguments.length<2?se(ne[e])||se(re[e]):ne[e]&&ne[e][t]||re[e]&&re[e][t]},ce="undefined"!=typeof navigator&&String(navigator.userAgent)||"",de=h,le=ce,ue=de.process,he=de.Deno,pe=ue&&ue.versions||he&&he.version,_e=pe&&pe.v8;_e&&(F=(V=_e.split("."))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&le&&(!(V=le.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=le.match(/Chrome\/(\d+)/))&&(F=+V[1]);var Ee=F,fe=Ee,me=n,Te=h.String,Se=!!Object.getOwnPropertySymbols&&!me((function(){var e=Symbol();return!Te(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&fe&&fe<41})),ge=Se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,Ce=w,Ie=l,ve=Object,ye=ge?function(e){return"symbol"==typeof e}:function(e){var t=Re("Symbol");return Ce(t)&&Ie(t.prototype,ve(e))},Ae=String,be=function(e){try{return Ae(e)}catch(e){return"Object"}},we=w,Oe=be,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+" is not a function")},Pe=De,Le=Y,ke=function(e,t){var i=e[t];return Le(i)?void 0:Pe(i)},Me=L,Ue=w,xe=te,Ve=TypeError,Fe={exports:{}},Be=h,je=Object.defineProperty,Ge=function(e,t){try{je(Be,e,{value:t,configurable:!0,writable:!0})}catch(i){Be[e]=t}return t},We="__core-js_shared__",He=h[We]||Ge(We,{}),Ke=He;(Fe.exports=function(e,t){return Ke[e]||(Ke[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ye=Fe.exports,qe=J,ze=Object,Je=function(e){return ze(qe(e))},Xe=Je,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Xe(e),t)},$e=d,et=0,tt=Math.random(),it=$e(1..toString),nt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+it(++et+tt,36)},rt=Ye,ot=Ze,st=nt,at=Se,ct=ge,dt=h.Symbol,lt=rt("wks"),ut=ct?dt.for||dt:dt&&dt.withoutSetter||st,ht=function(e){return ot(lt,e)||(lt[e]=at&&ot(dt,e)?dt[e]:ut("Symbol."+e)),lt[e]},pt=L,_t=te,Et=ye,ft=ke,mt=function(e,t){var i,n;if("string"===t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!xe(n=Me(i,e)))return n;if("string"!==t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;throw Ve("Can't convert object to primitive value")},Tt=TypeError,St=ht("toPrimitive"),gt=function(e,t){if(!_t(e)||Et(e))return e;var i,n=ft(e,St);if(n){if(void 0===t&&(t="default"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw Tt("Can't convert object to primitive value")}return void 0===t&&(t="number"),mt(e,t)},Rt=ye,Ct=function(e){var t=gt(e,"string");return Rt(t)?t:t+""},It=te,vt=h.document,yt=It(vt)&&It(vt.createElement),At=function(e){return yt?vt.createElement(e):{}},bt=At,wt=!N&&!n((function(){return 7!=Object.defineProperty(bt("div"),"a",{get:function(){return 7}}).a})),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=Ct,Mt=Ze,Ut=wt,xt=Object.getOwnPropertyDescriptor;O.f=Ot?xt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return xt(e,t)}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t])};var Vt=n,Ft=w,Bt=/#|\.prototype\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?Vt(t):!!t)},Gt=jt.normalize=function(e){return String(e).replace(Bt,".").toLowerCase()},Wt=jt.data={},Ht=jt.NATIVE="N",Kt=jt.POLYFILL="P",Yt=jt,qt=De,zt=r,Jt=v(v.bind),Xt=function(e,t){return qt(e),void 0===t?e:zt?Jt(e,t):function(){return e.apply(t,arguments)}},Qt={},Zt=N&&n((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),$t=te,ei=String,ti=TypeError,ii=function(e){if($t(e))return e;throw ti(ei(e)+" is not an object")},ni=N,ri=wt,oi=Zt,si=ii,ai=Ct,ci=TypeError,di=Object.defineProperty,li=Object.getOwnPropertyDescriptor,ui="enumerable",hi="configurable",pi="writable";Qt.f=ni?oi?function(e,t,i){if(si(e),t=ai(t),si(i),"function"==typeof e&&"prototype"===t&&"value"in i&&pi in i&&!i[pi]){var n=li(e,t);n&&n[pi]&&(e[t]=i.value,i={configurable:hi in i?i[hi]:n[hi],enumerable:ui in i?i[ui]:n[ui],writable:!1})}return di(e,t,i)}:di:function(e,t,i){if(si(e),t=ai(t),si(i),ri)try{return di(e,t,i)}catch(e){}if("get"in i||"set"in i)throw ci("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var _i=Qt,Ei=B,fi=N?function(e,t,i){return _i.f(e,t,Ei(1,i))}:function(e,t,i){return e[t]=i,e},mi=h,Ti=m,Si=v,gi=w,Ri=O.f,Ci=Yt,Ii=ie,vi=Xt,yi=fi,Ai=Ze,bi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return Ti(e,this,arguments)};return t.prototype=e.prototype,t},wi=function(e,t){var i,n,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?mi:p?mi[u]:(mi[u]||{}).prototype,f=h?Ii:Ii[u]||yi(Ii,u,{})[u],m=f.prototype;for(o in t)n=!(i=Ci(h?o:u+(p?".":"#")+o,e.forced))&&E&&Ai(E,o),a=f[o],n&&(c=e.dontCallGetSet?(l=Ri(E,o))&&l.value:E[o]),s=n&&c?c:t[o],n&&typeof a==typeof s||(d=e.bind&&n?vi(s,mi):e.wrap&&n?bi(s):_&&gi(s)?Si(s):s,(e.sham||s&&s.sham||a&&a.sham)&&yi(d,"sham",!0),yi(f,o,d),_&&(Ai(Ii,r=u+"Prototype")||yi(Ii,r,{}),yi(Ii[r],o,s),e.real&&m&&(i||!m[o])&&yi(m,o,s)))},Oi=Math.ceil,Ni=Math.floor,Di=Math.trunc||function(e){var t=+e;return(t>0?Ni:Oi)(t)},Pi=Di,Li=function(e){var t=+e;return t!=t||0===t?0:Pi(t)},ki=Li,Mi=Math.max,Ui=Math.min,xi=function(e,t){var i=ki(e);return i<0?Mi(i+t,0):Ui(i,t)},Vi=Li,Fi=Math.min,Bi=function(e){return e>0?Fi(Vi(e),9007199254740991):0},ji=Bi,Gi=function(e){return ji(e.length)},Wi=Z,Hi=xi,Ki=Gi,Yi=function(e){return function(t,i,n){var r,o=Wi(t),s=Ki(o),a=Hi(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},qi={includes:Yi(!0),indexOf:Yi(!1)},zi=qi.includes;wi({target:"Array",proto:!0,forced:n((function(){return!Array(1).includes()}))},{includes:function(e){return zi(this,e,arguments.length>1?arguments[1]:void 0)}});var Ji=ie,Xi=function(e){return Ji[e+"Prototype"]},Qi=Xi("Array").includes,Zi=te,$i=R,en=ht("match"),tn=function(e){var t;return Zi(e)&&(void 0!==(t=e[en])?!!t:"RegExp"==$i(e))},nn=tn,rn=TypeError,on={};on[ht("toStringTag")]="z";var sn="[object z]"===String(on),an=sn,cn=w,dn=R,ln=ht("toStringTag"),un=Object,hn="Arguments"==dn(function(){return arguments}()),pn=an?dn:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=un(e),ln))?i:hn?dn(t):"Object"==(n=dn(t))&&cn(t.callee)?"Arguments":n},_n=pn,En=String,fn=function(e){if("Symbol"===_n(e))throw TypeError("Cannot convert a Symbol value to a string");return En(e)},mn=ht("match"),Tn=wi,Sn=function(e){if(nn(e))throw rn("The method doesn't accept regular expressions");return e},gn=J,Rn=fn,Cn=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[mn]=!1,"/./"[e](t)}catch(e){}}return!1},In=d("".indexOf);Tn({target:"String",proto:!0,forced:!Cn("includes")},{includes:function(e){return!!~In(Rn(gn(this)),Rn(Sn(e)),arguments.length>1?arguments[1]:void 0)}});var vn=Xi("String").includes,yn=l,An=Qi,bn=vn,wn=Array.prototype,On=String.prototype,Nn=function(e){var t=e.includes;return e===wn||yn(wn,e)&&t===wn.includes?An:"string"==typeof e||e===On||yn(On,e)&&t===On.includes?bn:t},Dn=i(Nn),Pn=De,Ln=Je,kn=K,Mn=Gi,Un=TypeError,xn=function(e){return function(t,i,n,r){Pn(i);var o=Ln(t),s=kn(o),a=Mn(o),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw Un("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=i(r,s[c],c,o));return r}},Vn={left:xn(!1),right:xn(!0)},Fn=n,Bn=function(e,t){var i=[][e];return!!i&&Fn((function(){i.call(null,t||function(){return 1},1)}))},jn="undefined"!=typeof process&&"process"==R(process),Gn=Vn.left;wi({target:"Array",proto:!0,forced:!jn&&Ee>79&&Ee<83||!Bn("reduce")},{reduce:function(e){var t=arguments.length;return Gn(this,e,t,t>1?arguments[1]:void 0)}});var Wn=Xi("Array").reduce,Hn=l,Kn=Wn,Yn=Array.prototype,qn=function(e){var t=e.reduce;return e===Yn||Hn(Yn,e)&&t===Yn.reduce?Kn:t},zn=qn,Jn=i(zn);let Xn=!0,Qn=!0;function Zn(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function $n(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function er(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function tr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Qn=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function ir(){if("object"==typeof window){if(Xn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function nr(e,t){Qn&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rr(e){return"[object Object]"===Object.prototype.toString.call(e)}function or(e){var t;return rr(e)?Jn(t=Object.keys(e)).call(t,(function(t,i){const n=rr(e[i]),r=n?or(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function sr(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?sr(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{sr(e,e.get(t),i)}))})))}function ar(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&sr(e,i,r)}))})),r}var cr=nt,dr=Ye("keys"),lr=function(e){return dr[e]||(dr[e]=cr(e))},ur=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),hr=Ze,pr=w,_r=Je,Er=ur,fr=lr("IE_PROTO"),mr=Object,Tr=mr.prototype,Sr=Er?mr.getPrototypeOf:function(e){var t=_r(e);if(hr(t,fr))return t[fr];var i=t.constructor;return pr(i)&&t instanceof i?i.prototype:t instanceof mr?Tr:null},gr=d,Rr=De,Cr=w,Ir=String,vr=TypeError,yr=function(e,t,i){try{return gr(Rr(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},Ar=ii,br=function(e){if("object"==typeof e||Cr(e))return e;throw vr("Can't set "+Ir(e)+" as a prototype")},wr=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=yr(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return Ar(i),br(n),t?e(i,n):i.__proto__=n,i}}():void 0),Or={},Nr={},Dr=Ze,Pr=Z,Lr=qi.indexOf,kr=Nr,Mr=d([].push),Ur=function(e,t){var i,n=Pr(e),r=0,o=[];for(i in n)!Dr(kr,i)&&Dr(n,i)&&Mr(o,i);for(;t.length>r;)Dr(n,i=t[r++])&&(~Lr(o,i)||Mr(o,i));return o},xr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Vr=Ur,Fr=xr.concat("length","prototype");Or.f=Object.getOwnPropertyNames||function(e){return Vr(e,Fr)};var Br={};Br.f=Object.getOwnPropertySymbols;var jr=ae,Gr=Or,Wr=Br,Hr=ii,Kr=d([].concat),Yr=jr("Reflect","ownKeys")||function(e){var t=Gr.f(Hr(e)),i=Wr.f;return i?Kr(t,i(e)):t},qr=Ze,zr=Yr,Jr=O,Xr=Qt,Qr={},Zr=Ur,$r=xr,eo=Object.keys||function(e){return Zr(e,$r)},to=N,io=Zt,no=Qt,ro=ii,oo=Z,so=eo;Qr.f=to&&!io?Object.defineProperties:function(e,t){ro(e);for(var i,n=oo(t),r=so(t),o=r.length,s=0;o>s;)no.f(e,i=r[s++],n[i]);return e};var ao,co=ae("document","documentElement"),lo=ii,uo=Qr,ho=xr,po=Nr,_o=co,Eo=At,fo="prototype",mo="script",To=lr("IE_PROTO"),So=function(){},go=function(e){return"<"+mo+">"+e+""},Ro=function(e){e.write(go("")),e.close();var t=e.parentWindow.Object;return e=null,t},Co=function(){try{ao=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;Co="undefined"!=typeof document?document.domain&&ao?Ro(ao):(t=Eo("iframe"),i="java"+mo+":",t.style.display="none",_o.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(go("document.F=Object")),e.close(),e.F):Ro(ao);for(var n=ho.length;n--;)delete Co[fo][ho[n]];return Co()};po[To]=!0;var Io=Object.create||function(e,t){var i;return null!==e?(So[fo]=lo(e),i=new So,So[fo]=null,i[To]=e):i=Co(),void 0===t?i:uo.f(i,t)},vo=te,yo=fi,Ao=Error,bo=d("".replace),wo=String(Ao("zxcasd").stack),Oo=/\n\s*at [^:]*:[^\n]*/,No=Oo.test(wo),Do=B,Po=!n((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Do(1,7)),7!==e.stack)})),Lo=fi,ko=function(e,t){if(No&&"string"==typeof e&&!Ao.prepareStackTrace)for(;t--;)e=bo(e,Oo,"");return e},Mo=Po,Uo=Error.captureStackTrace,xo={},Vo=xo,Fo=ht("iterator"),Bo=Array.prototype,jo=function(e){return void 0!==e&&(Vo.Array===e||Bo[Fo]===e)},Go=pn,Wo=ke,Ho=Y,Ko=xo,Yo=ht("iterator"),qo=function(e){if(!Ho(e))return Wo(e,Yo)||Wo(e,"@@iterator")||Ko[Go(e)]},zo=L,Jo=De,Xo=ii,Qo=be,Zo=qo,$o=TypeError,es=function(e,t){var i=arguments.length<2?Zo(e):t;if(Jo(i))return Xo(zo(i,e));throw $o(Qo(e)+" is not iterable")},ts=L,is=ii,ns=ke,rs=function(e,t,i){var n,r;is(e);try{if(!(n=ns(e,"return"))){if("throw"===t)throw i;return i}n=ts(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return is(n),i},os=Xt,ss=L,as=ii,cs=be,ds=jo,ls=Gi,us=l,hs=es,ps=qo,_s=rs,Es=TypeError,fs=function(e,t){this.stopped=e,this.result=t},ms=fs.prototype,Ts=function(e,t,i){var n,r,o,s,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=os(t,l),f=function(e){return n&&_s(n,"normal",e),new fs(!0,e)},m=function(e){return u?(as(e),_?E(e[0],e[1],f):E(e[0],e[1])):_?E(e,f):E(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=ps(e)))throw Es(cs(e)+" is not iterable");if(ds(r)){for(o=0,s=ls(e);s>o;o++)if((a=m(e[o]))&&us(ms,a))return a;return new fs(!1)}n=hs(e,r)}for(c=h?e.next:n.next;!(d=ss(c,n)).done;){try{a=m(d.value)}catch(e){_s(n,"throw",e)}if("object"==typeof a&&a&&us(ms,a))return a}return new fs(!1)},Ss=fn,gs=wi,Rs=l,Cs=Sr,Is=wr,vs=function(e,t,i){for(var n=zr(t),r=Xr.f,o=Jr.f,s=0;s2&&ws(i,arguments[2]);var r=[];return Ns(e,ks,{that:r}),As(i,"errors",r),i};Is?Is(Ms,Ls):vs(Ms,Ls,{name:!0});var Us=Ms.prototype=ys(Ls.prototype,{constructor:bs(1,Ms),message:bs(1,""),name:bs(1,"AggregateError")});gs({global:!0,constructor:!0,arity:2},{AggregateError:Ms});var xs,Vs,Fs,Bs=w,js=h.WeakMap,Gs=Bs(js)&&/native code/.test(String(js)),Ws=h,Hs=te,Ks=fi,Ys=Ze,qs=He,zs=lr,Js=Nr,Xs="Object already initialized",Qs=Ws.TypeError,Zs=Ws.WeakMap;if(Gs||qs.state){var $s=qs.state||(qs.state=new Zs);$s.get=$s.get,$s.has=$s.has,$s.set=$s.set,xs=function(e,t){if($s.has(e))throw Qs(Xs);return t.facade=e,$s.set(e,t),t},Vs=function(e){return $s.get(e)||{}},Fs=function(e){return $s.has(e)}}else{var ea=zs("state");Js[ea]=!0,xs=function(e,t){if(Ys(e,ea))throw Qs(Xs);return t.facade=e,Ks(e,ea,t),t},Vs=function(e){return Ys(e,ea)?e[ea]:{}},Fs=function(e){return Ys(e,ea)}}var ta,ia,na,ra={set:xs,get:Vs,has:Fs,enforce:function(e){return Fs(e)?Vs(e):xs(e,{})},getterFor:function(e){return function(t){var i;if(!Hs(t)||(i=Vs(t)).type!==e)throw Qs("Incompatible receiver, "+e+" required");return i}}},oa=N,sa=Ze,aa=Function.prototype,ca=oa&&Object.getOwnPropertyDescriptor,da=sa(aa,"name"),la={EXISTS:da,PROPER:da&&"something"===function(){}.name,CONFIGURABLE:da&&(!oa||oa&&ca(aa,"name").configurable)},ua=fi,ha=function(e,t,i,n){return n&&n.enumerable?e[t]=i:ua(e,t,i),e},pa=n,_a=w,Ea=te,fa=Io,ma=Sr,Ta=ha,Sa=ht("iterator"),ga=!1;[].keys&&("next"in(na=[].keys())?(ia=ma(ma(na)))!==Object.prototype&&(ta=ia):ga=!0);var Ra=!Ea(ta)||pa((function(){var e={};return ta[Sa].call(e)!==e}));_a((ta=Ra?{}:fa(ta))[Sa])||Ta(ta,Sa,(function(){return this}));var Ca={IteratorPrototype:ta,BUGGY_SAFARI_ITERATORS:ga},Ia=pn,va=sn?{}.toString:function(){return"[object "+Ia(this)+"]"},ya=sn,Aa=Qt.f,ba=fi,wa=Ze,Oa=va,Na=ht("toStringTag"),Da=function(e,t,i,n){if(e){var r=i?e:e.prototype;wa(r,Na)||Aa(r,Na,{configurable:!0,value:t}),n&&!ya&&ba(r,"toString",Oa)}},Pa=Ca.IteratorPrototype,La=Io,ka=B,Ma=Da,Ua=xo,xa=function(){return this},Va=function(e,t,i,n){var r=t+" Iterator";return e.prototype=La(Pa,{next:ka(+!n,i)}),Ma(e,r,!1,!0),Ua[r]=xa,e},Fa=wi,Ba=L,ja=la,Ga=Va,Wa=Sr,Ha=Da,Ka=ha,Ya=xo,qa=Ca,za=ja.PROPER,Ja=qa.BUGGY_SAFARI_ITERATORS,Xa=ht("iterator"),Qa="keys",Za="values",$a="entries",ec=function(){return this},tc=function(e,t,i,n,r,o,s){Ga(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Ja&&e in p)return p[e];switch(e){case Qa:case Za:case $a:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[Xa]||p["@@iterator"]||r&&p[r],E=!Ja&&_||l(r),f="Array"==t&&p.entries||_;if(f&&(a=Wa(f.call(new e)))!==Object.prototype&&a.next&&(Ha(a,u,!0,!0),Ya[u]=ec),za&&r==Za&&_&&_.name!==Za&&(h=!0,E=function(){return Ba(_,this)}),r)if(c={values:l(Za),keys:o?E:l(Qa),entries:l($a)},s)for(d in c)(Ja||h||!(d in p))&&Ka(p,d,c[d]);else Fa({target:t,proto:!0,forced:Ja||h},c);return s&&p[Xa]!==E&&Ka(p,Xa,E,{name:r}),Ya[t]=E,c},ic=function(e,t){return{value:e,done:t}},nc=Z,rc=xo,oc=ra;Qt.f;var sc=tc,ac=ic,cc="Array Iterator",dc=oc.set,lc=oc.getterFor(cc);sc(Array,"Array",(function(e,t){dc(this,{type:cc,target:nc(e),index:0,kind:t})}),(function(){var e=lc(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,ac(void 0,!0)):ac("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),rc.Arguments=rc.Array;var uc=Qt,hc=function(e,t,i){return uc.f(e,t,i)},pc=ae,_c=hc,Ec=N,fc=ht("species"),mc=l,Tc=TypeError,Sc=function(e,t){if(mc(t,e))return e;throw Tc("Incorrect invocation")},gc=w,Rc=He,Cc=d(Function.toString);gc(Rc.inspectSource)||(Rc.inspectSource=function(e){return Cc(e)});var Ic=Rc.inspectSource,vc=d,yc=n,Ac=w,bc=pn,wc=Ic,Oc=function(){},Nc=[],Dc=ae("Reflect","construct"),Pc=/^\s*(?:class|function)\b/,Lc=vc(Pc.exec),kc=!Pc.exec(Oc),Mc=function(e){if(!Ac(e))return!1;try{return Dc(Oc,Nc,e),!0}catch(e){return!1}},Uc=function(e){if(!Ac(e))return!1;switch(bc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return kc||!!Lc(Pc,wc(e))}catch(e){return!0}};Uc.sham=!0;var xc,Vc,Fc,Bc,jc=!Dc||yc((function(){var e;return Mc(Mc.call)||!Mc(Object)||!Mc((function(){e=!0}))||e}))?Uc:Mc,Gc=jc,Wc=be,Hc=TypeError,Kc=ii,Yc=function(e){if(Gc(e))return e;throw Hc(Wc(e)+" is not a constructor")},qc=Y,zc=ht("species"),Jc=function(e,t){var i,n=Kc(e).constructor;return void 0===n||qc(i=Kc(n)[zc])?t:Yc(i)},Xc=d([].slice),Qc=TypeError,Zc=function(e,t){if(e=a?e?"":void 0:(n=Sh(o,s))<55296||n>56319||s+1===a||(r=Sh(o,s+1))<56320||r>57343?e?Th(o,s):n:e?gh(o,s,s+2):r-56320+(n-55296<<10)+65536}},Ch={codeAt:Rh(!1),charAt:Rh(!0)},Ih=Ch.charAt,vh=fn,yh=ra,Ah=tc,bh=ic,wh="String Iterator",Oh=yh.set,Nh=yh.getterFor(wh);Ah(String,"String",(function(e){Oh(this,{type:wh,string:vh(e),index:0})}),(function(){var e,t=Nh(this),i=t.string,n=t.index;return n>=i.length?bh(void 0,!0):(e=Ih(i,n),t.index+=e.length,bh(e,!1))}));var Dh=ie.Promise,Ph={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Lh=h,kh=pn,Mh=fi,Uh=xo,xh=ht("toStringTag");for(var Vh in Ph){var Fh=Lh[Vh],Bh=Fh&&Fh.prototype;Bh&&kh(Bh)!==xh&&Mh(Bh,xh,Vh),Uh[Vh]=Uh.Array}var jh=Dh,Gh=i(jh);const Wh=ir;function Hh(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>{var i;return Dn(i=e.label.toLowerCase()).call(i,t)}))));return!s&&i.length&&Dn(t).call(t,"back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),Wh("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Wh("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Gh.reject(o(e))))))}}}function Kh(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Yh(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else $n(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qh(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function zh(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Gh(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function Jh(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ar(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),$n(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ar(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Gh.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Gh.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Xh(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Qh(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Xh(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find((e=>e.track===t));if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Gh.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Zh(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function $h(e,t){$n(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ep=Object.freeze({__proto__:null,fixNegotiationNeeded:$h,shimAddTrackRemoveTrack:Qh,shimAddTrackRemoveTrackWithNative:Xh,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:qh,shimGetStats:zh,shimGetUserMedia:Hh,shimMediaStream:Kh,shimOnTrack:Yh,shimPeerConnection:Zh,shimSenderReceiverGetStats:Jh});function tp(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){nr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function ip(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function np(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function rp(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Gh.resolve(new Map)}}function op(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),$n(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sp(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){nr("removeStream","removeTrack"),this.getSenders().forEach((t=>{var i;t.track&&Dn(i=e.getTracks()).call(i,t.track)&&this.removeTrack(t)}))})}function ap(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function cp(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function dp(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function lp(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Gh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function up(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Gh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var hp=Object.freeze({__proto__:null,shimAddTransceiver:cp,shimCreateAnswer:up,shimCreateOffer:lp,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Gh.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:dp,shimGetUserMedia:tp,shimOnTrack:ip,shimPeerConnection:np,shimRTCDataChannel:ap,shimReceiverGetStats:op,shimRemoveStream:sp,shimSenderGetStats:rp});function pp(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var i;this._localStreams||(this._localStreams=[]),Dn(i=this._localStreams).call(i,e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r{var t;this._localStreams?Dn(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{Dn(i).call(i,e.track)&&this.removeTrack(e)}))})}}function _p(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{var t;if(this._remoteStreams||(this._remoteStreams=[]),Dn(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const i=new Event("addstream");i.stream=e,this.dispatchEvent(i)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Ep(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Gh.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Gh.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Gh.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Gh.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Gh.resolve()):n},t.addIceCandidate=a}function fp(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(mp(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function mp(e){return e&&void 0!==e.video?Object.assign({},e,{video:or(e.video)}):e}function Tp(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function Sp(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function gp(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Rp(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Cp=Object.freeze({__proto__:null,shimAudioContext:Rp,shimCallbacksAPI:Ep,shimConstraints:mp,shimCreateOfferLegacy:gp,shimGetUserMedia:fp,shimLocalStreamsAPI:pp,shimRTCIceServerUrls:Tp,shimRemoteStreamsAPI:_p,shimTrackEventTransceiver:Sp}),Ip="\t\n\v\f\r                 \u2028\u2029\ufeff",vp=J,yp=fn,Ap=Ip,bp=d("".replace),wp=RegExp("^["+Ap+"]+"),Op=RegExp("(^|[^"+Ap+"])["+Ap+"]+$"),Np=function(e){return function(t){var i=yp(vp(t));return 1&e&&(i=bp(i,wp,"")),2&e&&(i=bp(i,Op,"$1")),i}},Dp={start:Np(1),end:Np(2),trim:Np(3)},Pp=la.PROPER,Lp=n,kp=Ip,Mp=Dp.trim;wi({target:"String",proto:!0,forced:function(e){return Lp((function(){return!!kp[e]()||"​…᠎"!=="​…᠎"[e]()||Pp&&kp[e].name!==e}))}("trim")},{trim:function(){return Mp(this)}});var Up=Xi("String").trim,xp=l,Vp=Up,Fp=String.prototype,Bp=function(e){var t=e.trim;return"string"==typeof e||e===Fp||xp(Fp,e)&&t===Fp.trim?Vp:t},jp=i(Bp),Gp={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function qp(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||$n(e,"icecandidate",(e=>{if(e.candidate){const t=Hp.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function zp(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Hp.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Hp.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},o=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Hp.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=o(arguments[0],e);let s;s=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function Jp(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},$n(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Xp(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Qp(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==jp(e).call(e))).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Zp(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Gh.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Gh.resolve())})}function $p(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var e_=Object.freeze({__proto__:null,removeExtmapAllowMixed:Qp,shimAddIceCandidateNullOrEmpty:Zp,shimConnectionState:Xp,shimMaxMessageSize:zp,shimParameterlessSetLocalDescription:$p,shimRTCIceCandidate:Yp,shimRTCIceCandidateRelayProtocol:qp,shimSendThrowTypeError:Jp});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=ir,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Zn(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Zn(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Zn(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:e_,extractVersion:Zn,disableLog:er,disableWarnings:tr,sdp:Kp};switch(n.browser){case"chrome":if(!ep||!Zh||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=ep,Zp(e,n),$p(e),Hh(e,n),Kh(e),Zh(e,n),Yh(e),Qh(e,n),qh(e),zh(e),Jh(e),$h(e,n),Yp(e),qp(e),Xp(e),zp(e,n),Jp(e),Qp(e,n);break;case"firefox":if(!hp||!np||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=hp,Zp(e,n),$p(e),tp(e,n),np(e,n),ip(e),sp(e),rp(e),op(e),ap(e),cp(e),dp(e),lp(e),up(e),Yp(e),Xp(e),zp(e,n),Jp(e);break;case"safari":if(!Cp||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Cp,Zp(e,n),$p(e),Tp(e),gp(e),Ep(e),pp(e),_p(e),Sp(e),fp(e),Rp(e),Yp(e),qp(e),zp(e,n),Jp(e),Qp(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var t_=Xi("Array").keys,i_=pn,n_=Ze,r_=l,o_=t_,s_=Array.prototype,a_={DOMTokenList:!0,NodeList:!0},c_=function(e){var t=e.keys;return e===s_||r_(s_,e)&&t===s_.keys||n_(a_,i_(e))?o_:t},d_=i(c_),l_=be,u_=TypeError,h_=Ct,p_=Qt,__=B,E_=function(e,t,i){var n=h_(t);n in e?p_.f(e,n,__(0,i)):e[n]=i},f_=xi,m_=Gi,T_=E_,S_=Array,g_=Math.max,R_=function(e,t,i){for(var n=m_(e),r=f_(t,n),o=f_(void 0===i?n:i,n),s=S_(g_(o-r,0)),a=0;r0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},A_=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s3)){if(H_)return!0;if(Y_)return Y_<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)q_.push({k:t+n,v:i})}for(q_.sort((function(e,t){return t.v-e.v})),n=0;nF_(i)?1:-1}}(e)),i=x_(r),n=0;n0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r2&&(e[d]="iPad",e[u]=m),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,T,g.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,T,g.os),!e[l]&&S&&"Unknown"!=S.platform&&(e[l]=S.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return T},this.setUA=function(e){return T=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(T),this};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,h,u,E,f,T,m,S,g]),X.ENGINE=X.OS=G([l,p]),e.exports&&(i=e.exports=X),i.UAParser=X;var Q=typeof t!==o&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new X;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:t)}(sE,sE.exports);var aE=i(sE.exports),cE=pn,dE=Ze,lE=Y,uE=xo,hE=ht("iterator"),pE=Object,_E=function(e){if(lE(e))return!1;var t=pE(e);return void 0!==t[hE]||"@@iterator"in t||dE(uE,cE(t))},EE=i(_E),fE=h;wi({global:!0,forced:fE.globalThis!==fE},{globalThis:fE});var mE=i(h);function TE(e,t){return function(){return e.apply(t,arguments)}}const{toString:SE}=Object.prototype,{getPrototypeOf:gE}=Object,RE=(CE=Object.create(null),e=>{const t=SE.call(e);return CE[t]||(CE[t]=t.slice(8,-1).toLowerCase())});var CE;const IE=e=>(e=e.toLowerCase(),t=>RE(t)===e),vE=e=>t=>typeof t===e,{isArray:yE}=Array,AE=vE("undefined");const bE=IE("ArrayBuffer");const wE=vE("string"),OE=vE("function"),NE=vE("number"),DE=e=>null!==e&&"object"==typeof e,PE=e=>{if("object"!==RE(e))return!1;const t=gE(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||EE(e))},LE=IE("Date"),kE=IE("File"),ME=IE("Blob"),UE=IE("FileList"),xE=IE("URLSearchParams");function VE(e,t){let i,n,{allOwnKeys:r=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null!=e)if("object"!=typeof e&&(e=[e]),yE(e))for(i=0,n=e.length;i0;)if(n=i[r],t===n.toLowerCase())return n;return null}const BE=void 0!==mE?mE:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,jE=e=>!AE(e)&&e!==BE;const GE=(WE="undefined"!=typeof Uint8Array&&gE(Uint8Array),e=>WE&&e instanceof WE);var WE;const HE=IE("HTMLFormElement"),KE=(e=>{let{hasOwnProperty:t}=e;return(e,i)=>t.call(e,i)})(Object.prototype),YE=IE("RegExp"),qE=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};VE(i,((i,r)=>{let o;!1!==(o=t(i,r,e))&&(n[r]=o||i)})),Object.defineProperties(e,n)},zE="abcdefghijklmnopqrstuvwxyz",JE="0123456789",XE={DIGIT:JE,ALPHA:zE,ALPHA_DIGIT:zE+zE.toUpperCase()+JE};const QE=IE("AsyncFunction");var ZE={isArray:yE,isArrayBuffer:bE,isBuffer:function(e){return null!==e&&!AE(e)&&null!==e.constructor&&!AE(e.constructor)&&OE(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||OE(e.append)&&("formdata"===(t=RE(e))||"object"===t&&OE(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&bE(e.buffer),t},isString:wE,isNumber:NE,isBoolean:e=>!0===e||!1===e,isObject:DE,isPlainObject:PE,isUndefined:AE,isDate:LE,isFile:kE,isBlob:ME,isRegExp:YE,isFunction:OE,isStream:e=>DE(e)&&OE(e.pipe),isURLSearchParams:xE,isTypedArray:GE,isFileList:UE,forEach:VE,merge:function e(){const{caseless:t}=jE(this)&&this||{},i={},n=(n,r)=>{const o=t&&FE(i,r)||r;PE(i[o])&&PE(n)?i[o]=e(i[o],n):PE(n)?i[o]=e({},n):yE(n)?i[o]=n.slice():i[o]=n};for(let e=0,t=arguments.length;e3&&void 0!==arguments[3]?arguments[3]:{};return VE(t,((t,n)=>{i&&OE(t)?e[n]=TE(t,i):e[n]=t}),{allOwnKeys:n}),e},trim:e=>jp(e)?jp(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,n)=>{let r,o,s;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==i&&gE(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:RE,kindOfTest:IE,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return-1!==n&&n===i},toArray:e=>{if(!e)return null;if(yE(e))return e;let t=e.length;if(!NE(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:HE,hasOwnProperty:KE,hasOwnProp:KE,reduceDescriptors:qE,freezeMethods:e=>{qE(e,((t,i)=>{if(OE(e)&&-1!==["arguments","caller","callee"].indexOf(i))return!1;const n=e[i];OE(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))}))},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach((e=>{i[e]=!0}))};return yE(e)?n(e):n(String(e).split(t)),i},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,i){return t.toUpperCase()+i})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:FE,global:BE,isContextDefined:jE,ALPHABET:XE,generateString:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:XE.ALPHA_DIGIT,i="";const{length:n}=t;for(;e--;)i+=t[Math.random()*n|0];return i},isSpecCompliantForm:function(e){return!!(e&&OE(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(DE(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const r=yE(e)?[]:{};return VE(e,((e,t)=>{const o=i(e,n+1);!AE(o)&&(r[t]=o)})),t[n]=void 0,r}}return e};return i(e,0)},isAsyncFn:QE,isThenable:e=>e&&(DE(e)||OE(e))&&OE(e.then)&&OE(e.catch)};function $E(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}ZE.inherits($E,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ZE.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ef=$E.prototype,tf={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{tf[e]={value:e}})),Object.defineProperties($E,tf),Object.defineProperty(ef,"isAxiosError",{value:!0}),$E.from=(e,t,i,n,r,o)=>{const s=Object.create(ef);return ZE.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),$E.call(s,e.message,t,i,n,r),s.cause=e,s.name=e.name,o&&Object.assign(s,o),s};function nf(e){return ZE.isPlainObject(e)||ZE.isArray(e)}function rf(e){return ZE.endsWith(e,"[]")?e.slice(0,-2):e}function of(e,t,i){return e?e.concat(t).map((function(e,t){return e=rf(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}const sf=ZE.toFlatObject(ZE,{},null,(function(e){return/^is[A-Z]/.test(e)}));function af(e,t,i){if(!ZE.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(i=ZE.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ZE.isUndefined(t[e])}))).metaTokens,r=i.visitor||d,o=i.dots,s=i.indexes,a=(i.Blob||"undefined"!=typeof Blob&&Blob)&&ZE.isSpecCompliantForm(t);if(!ZE.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ZE.isDate(e))return e.toISOString();if(!a&&ZE.isBlob(e))throw new $E("Blob is not supported. Use a Buffer instead.");return ZE.isArrayBuffer(e)||ZE.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,i,r){let a=e;if(e&&!r&&"object"==typeof e)if(ZE.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(ZE.isArray(e)&&function(e){return ZE.isArray(e)&&!e.some(nf)}(e)||(ZE.isFileList(e)||ZE.endsWith(i,"[]"))&&(a=ZE.toArray(e)))return i=rf(i),a.forEach((function(e,n){!ZE.isUndefined(e)&&null!==e&&t.append(!0===s?of([i],n,o):null===s?i:i+"[]",c(e))})),!1;return!!nf(e)||(t.append(of(r,i,o),c(e)),!1)}const l=[],u=Object.assign(sf,{defaultVisitor:d,convertValue:c,isVisitable:nf});if(!ZE.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!ZE.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),ZE.forEach(i,(function(i,o){!0===(!(ZE.isUndefined(i)||null===i)&&r.call(t,i,ZE.isString(o)?jp(o).call(o):o,n,u))&&e(i,n?n.concat(o):[o])})),l.pop()}}(e),t}function cf(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function df(e,t){this._pairs=[],e&&af(e,this,t)}const lf=df.prototype;function uf(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function hf(e,t,i){if(!t)return e;const n=i&&i.encode||uf,r=i&&i.serialize;let o;if(o=r?r(t,i):ZE.isURLSearchParams(t)?t.toString():new df(t,i).toString(n),o){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}lf.append=function(e,t){this._pairs.push([e,t])},lf.toString=function(e){const t=e?function(t){return e.call(this,t,cf)}:cf;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var pf=class{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ZE.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},_f={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ef={exports:{}},ff=wi,mf=N,Tf=Qt.f;ff({target:"Object",stat:!0,forced:Object.defineProperty!==Tf,sham:!mf},{defineProperty:Tf});var Sf=ie.Object,gf=Ef.exports=function(e,t,i){return Sf.defineProperty(e,t,i)};Sf.defineProperty.sham&&(gf.sham=!0);var Rf=i(Ef.exports),Cf=R,If=Array.isArray||function(e){return"Array"==Cf(e)},vf=TypeError,yf=If,Af=jc,bf=te,wf=ht("species"),Of=Array,Nf=function(e){var t;return yf(e)&&(t=e.constructor,(Af(t)&&(t===Of||yf(t.prototype))||bf(t)&&null===(t=t[wf]))&&(t=void 0)),void 0===t?Of:t},Df=function(e,t){return new(Nf(e))(0===t?0:t)},Pf=n,Lf=Ee,kf=ht("species"),Mf=function(e){return Lf>=51||!Pf((function(){var t=[];return(t.constructor={})[kf]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},Uf=wi,xf=n,Vf=If,Ff=te,Bf=Je,jf=Gi,Gf=function(e){if(e>9007199254740991)throw vf("Maximum allowed index exceeded");return e},Wf=E_,Hf=Df,Kf=Mf,Yf=Ee,qf=ht("isConcatSpreadable"),zf=Yf>=51||!xf((function(){var e=[];return e[qf]=!1,e.concat()[0]!==e})),Jf=function(e){if(!Ff(e))return!1;var t=e[qf];return void 0!==t?!!t:Vf(e)};Uf({target:"Array",proto:!0,arity:1,forced:!zf||!Kf("concat")},{concat:function(e){var t,i,n,r,o,s=Bf(this),a=Hf(s,0),c=0;for(t=-1,n=arguments.length;tT;T++)if((a||T in E)&&(p=f(h=E[T],T,_),e))if(t)g[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:Sm(g,h)}else switch(e){case 4:return!1;case 7:Sm(g,h)}return o?-1:n||r?r:g}},Rm={forEach:gm(0),map:gm(1),filter:gm(2),some:gm(3),every:gm(4),find:gm(5),findIndex:gm(6),filterReject:gm(7)},Cm=wi,Im=h,vm=L,ym=d,Am=N,bm=Se,wm=n,Om=Ze,Nm=l,Dm=ii,Pm=Z,Lm=Ct,km=fn,Mm=B,Um=Io,xm=eo,Vm=Or,Fm=Xf,Bm=Br,jm=O,Gm=Qt,Wm=Qr,Hm=k,Km=ha,Ym=hc,qm=Ye,zm=Nr,Jm=nt,Xm=ht,Qm=im,Zm=cm,$m=pm,eT=Da,tT=ra,iT=Rm.forEach,nT=lr("hidden"),rT="Symbol",oT="prototype",sT=tT.set,aT=tT.getterFor(rT),cT=Object[oT],dT=Im.Symbol,lT=dT&&dT[oT],uT=Im.TypeError,hT=Im.QObject,pT=jm.f,_T=Gm.f,ET=Fm.f,fT=Hm.f,mT=ym([].push),TT=qm("symbols"),ST=qm("op-symbols"),gT=qm("wks"),RT=!hT||!hT[oT]||!hT[oT].findChild,CT=Am&&wm((function(){return 7!=Um(_T({},"a",{get:function(){return _T(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=pT(cT,t);n&&delete cT[t],_T(e,t,i),n&&e!==cT&&_T(cT,t,n)}:_T,IT=function(e,t){var i=TT[e]=Um(lT);return sT(i,{type:rT,tag:e,description:t}),Am||(i.description=t),i},vT=function(e,t,i){e===cT&&vT(ST,t,i),Dm(e);var n=Lm(t);return Dm(i),Om(TT,n)?(i.enumerable?(Om(e,nT)&&e[nT][n]&&(e[nT][n]=!1),i=Um(i,{enumerable:Mm(0,!1)})):(Om(e,nT)||_T(e,nT,Mm(1,{})),e[nT][n]=!0),CT(e,n,i)):_T(e,n,i)},yT=function(e,t){Dm(e);var i=Pm(t),n=xm(i).concat(OT(i));return iT(n,(function(t){Am&&!vm(AT,i,t)||vT(e,t,i[t])})),e},AT=function(e){var t=Lm(e),i=vm(fT,this,t);return!(this===cT&&Om(TT,t)&&!Om(ST,t))&&(!(i||!Om(this,t)||!Om(TT,t)||Om(this,nT)&&this[nT][t])||i)},bT=function(e,t){var i=Pm(e),n=Lm(t);if(i!==cT||!Om(TT,n)||Om(ST,n)){var r=pT(i,n);return!r||!Om(TT,n)||Om(i,nT)&&i[nT][n]||(r.enumerable=!0),r}},wT=function(e){var t=ET(Pm(e)),i=[];return iT(t,(function(e){Om(TT,e)||Om(zm,e)||mT(i,e)})),i},OT=function(e){var t=e===cT,i=ET(t?ST:Pm(e)),n=[];return iT(i,(function(e){!Om(TT,e)||t&&!Om(cT,e)||mT(n,TT[e])})),n};bm||(dT=function(){if(Nm(lT,this))throw uT("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?km(arguments[0]):void 0,t=Jm(e),i=function(e){this===cT&&vm(i,ST,e),Om(this,nT)&&Om(this[nT],t)&&(this[nT][t]=!1),CT(this,t,Mm(1,e))};return Am&&RT&&CT(cT,t,{configurable:!0,set:i}),IT(t,e)},Km(lT=dT[oT],"toString",(function(){return aT(this).tag})),Km(dT,"withoutSetter",(function(e){return IT(Jm(e),e)})),Hm.f=AT,Gm.f=vT,Wm.f=yT,jm.f=bT,Vm.f=Fm.f=wT,Bm.f=OT,Qm.f=function(e){return IT(Xm(e),e)},Am&&Ym(lT,"description",{configurable:!0,get:function(){return aT(this).description}})),Cm({global:!0,constructor:!0,wrap:!0,forced:!bm,sham:!bm},{Symbol:dT}),iT(xm(gT),(function(e){Zm(e)})),Cm({target:rT,stat:!0,forced:!bm},{useSetter:function(){RT=!0},useSimple:function(){RT=!1}}),Cm({target:"Object",stat:!0,forced:!bm,sham:!Am},{create:function(e,t){return void 0===t?Um(e):yT(Um(e),t)},defineProperty:vT,defineProperties:yT,getOwnPropertyDescriptor:bT}),Cm({target:"Object",stat:!0,forced:!bm},{getOwnPropertyNames:wT}),$m(),eT(dT,rT),zm[nT]=!0;var NT=Se&&!!Symbol.for&&!!Symbol.keyFor,DT=wi,PT=ae,LT=Ze,kT=fn,MT=Ye,UT=NT,xT=MT("string-to-symbol-registry"),VT=MT("symbol-to-string-registry");DT({target:"Symbol",stat:!0,forced:!UT},{for:function(e){var t=kT(e);if(LT(xT,t))return xT[t];var i=PT("Symbol")(t);return xT[t]=i,VT[i]=t,i}});var FT=wi,BT=Ze,jT=ye,GT=be,WT=NT,HT=Ye("symbol-to-string-registry");FT({target:"Symbol",stat:!0,forced:!WT},{keyFor:function(e){if(!jT(e))throw TypeError(GT(e)+" is not a symbol");if(BT(HT,e))return HT[e]}});var KT=If,YT=w,qT=R,zT=fn,JT=d([].push),XT=wi,QT=ae,ZT=m,$T=L,eS=d,tS=n,iS=w,nS=ye,rS=Xc,oS=function(e){if(YT(e))return e;if(KT(e)){for(var t=e.length,i=[],n=0;n0?arguments[0]:void 0));hg||(this.size=e.entries.length)},mR=fR.prototype;if(fg(mR,{append:function(e,t){var i=Vg(this);Pg(arguments.length,2),$g(i.entries,{key:bg(e),value:bg(t)}),hg||this.length++,i.updateURL()},delete:function(e){for(var t=Vg(this),i=Pg(arguments.length,1),n=t.entries,r=bg(e),o=i<2?void 0:arguments[1],s=void 0===o?o:bg(o),a=0;at.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Vg(this).entries,n=Ig(e,arguments.length>1?arguments[1]:void 0),r=0;r1?gR(arguments[1]):{})}}),Rg(Wg)){var RR=function(e){return gg(this,Kg),new Wg(e,arguments.length>1?gR(arguments[1]):{})};Kg.constructor=RR,RR.prototype=Kg,cg({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:RR})}}var CR={URLSearchParams:fR,getState:Vg},IR=i(ie.URLSearchParams),vR={isBrowser:!0,classes:{URLSearchParams:void 0!==IR?IR:df,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const yR="undefined"!=typeof window&&"undefined"!=typeof document,AR=(bR="undefined"!=typeof navigator&&navigator.product,yR&&["ReactNative","NativeScript","NS"].indexOf(bR)<0);var bR;const wR="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;function OR(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function NR(e){for(var t=1;t=e.length;if(o=!o&&ZE.isArray(n)?n.length:o,a)return ZE.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!s;n[o]&&ZE.isObject(n[o])||(n[o]=[]);return t(e,i,n[o],r)&&ZE.isArray(n[o])&&(n[o]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let o;for(n=0;n{t(function(e){return bC(ZE).call(ZE,/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const OC={transitional:_f,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=ZE.isObject(e);r&&ZE.isHTMLForm(e)&&(e=new FormData(e));if(ZE.isFormData(e))return n?JSON.stringify(wC(e)):e;if(ZE.isArrayBuffer(e)||ZE.isBuffer(e)||ZE.isStream(e)||ZE.isFile(e)||ZE.isBlob(e))return e;if(ZE.isArrayBufferView(e))return e.buffer;if(ZE.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return af(e,new DR.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return DR.isNode&&ZE.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((o=ZE.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return af(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if(ZE.isString(e))try{return(t||JSON.parse)(e),jp(ZE).call(ZE,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||OC.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&ZE.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw $E.from(e,$E.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:DR.classes.FormData,Blob:DR.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ZE.forEach(["delete","get","head","post","put","patch"],(e=>{OC.headers[e]={}}));var NC=OC;const DC=ZE.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const PC=Symbol("internals");function LC(e){var t;return e&&jp(t=String(e)).call(t).toLowerCase()}function kC(e){return!1===e||null==e?e:ZE.isArray(e)?e.map(kC):String(e)}function MC(e,t,i,n,r){return ZE.isFunction(n)?n.call(this,t,i):(r&&(t=i),ZE.isString(t)?ZE.isString(n)?-1!==t.indexOf(n):ZE.isRegExp(n)?n.test(t):void 0:void 0)}class UC{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=LC(t);if(!r)throw new Error("header name must be a non-empty string");const o=ZE.findKey(n,r);(!o||void 0===n[o]||!0===i||void 0===i&&!1!==n[o])&&(n[o||t]=kC(e))}const o=(e,t)=>ZE.forEach(e,((e,i)=>r(e,i,t)));var s;return ZE.isPlainObject(e)||e instanceof this.constructor?o(e,t):ZE.isString(e)&&(e=jp(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(jp(s=e).call(s))?o((e=>{const t={};let i,n,r;return e&&e.split("\n").forEach((function(e){var o,s;r=e.indexOf(":"),i=jp(o=e.substring(0,r)).call(o).toLowerCase(),n=jp(s=e.substring(r+1)).call(s),!i||t[i]&&DC[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t):null!=e&&r(t,e,i),this}get(e,t){if(e=LC(e)){const i=ZE.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if(ZE.isFunction(t))return t.call(this,e,i);if(ZE.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=LC(e)){const i=ZE.findKey(this,e);return!(!i||void 0===this[i]||t&&!MC(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=LC(e)){const r=ZE.findKey(i,e);!r||t&&!MC(0,i[r],r,t)||(delete i[r],n=!0)}}return ZE.isArray(e)?e.forEach(r):r(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!MC(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return ZE.forEach(this,((n,r)=>{var o;const s=ZE.findKey(i,r);if(s)return t[s]=kC(n),void delete t[r];const a=e?function(e){return jp(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):jp(o=String(r)).call(o);a!==r&&delete t[r],t[a]=kC(n),i[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),i=0;i{null!=i&&!1!==i&&(t[n]=e&&ZE.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let[t,i]=e;return t+": "+i})).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e){const t=new this(e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;rt.set(e))),t}static accessor(e){const t=(this[PC]=this[PC]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=LC(e);t[n]||(!function(e,t){const i=ZE.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{value:function(e,i,r){return this[n].call(this,t,e,i,r)},configurable:!0})}))}(i,e),t[n]=!0)}return ZE.isArray(e)?e.forEach(n):n(e),this}}UC.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ZE.reduceDescriptors(UC.prototype,((e,t)=>{let{value:i}=e,n=t[0].toUpperCase()+t.slice(1);return{get:()=>i,set(e){this[n]=e}}})),ZE.freezeMethods(UC);var xC=UC;function VC(e,t){const i=this||NC,n=t||i,r=xC.from(n.headers);let o=n.data;return ZE.forEach(e,(function(e){o=e.call(i,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function FC(e){return!(!e||!e.__CANCEL__)}function BC(e,t,i){$E.call(this,null==e?"canceled":e,$E.ERR_CANCELED,t,i),this.name="CanceledError"}ZE.inherits(BC,$E,{__CANCEL__:!0});var jC=DR.hasStandardBrowserEnv?{write(e,t,i,n,r,o){const s=[e+"="+encodeURIComponent(t)];ZE.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),ZE.isString(n)&&s.push("path="+n),ZE.isString(r)&&s.push("domain="+r),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function GC(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var WC=DR.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function n(i){let n=i;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return i=n(window.location.href),function(e){const t=ZE.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host}}():function(){return!0};function HC(e,t){let i=0;const n=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[s];r||(r=c),i[o]=a,n[o]=c;let l=s,u=0;for(;l!==o;)u+=i[l++],l%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-r{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=o-i,c=n(a);i=o;const d={loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:r};d[t?"download":"upload"]=!0,e(d)}}var KC="undefined"!=typeof XMLHttpRequest&&function(e){return new Gh((function(t,i){let n=e.data;const r=xC.from(e.headers).normalize();let o,s,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(o),e.signal&&e.signal.removeEventListener("abort",o)}if(ZE.isFormData(n))if(DR.hasStandardBrowserEnv||DR.hasStandardBrowserWebWorkerEnv)r.setContentType(!1);else if(!1!==(s=r.getContentType())){const[e,...t]=s?s.split(";").map((e=>jp(e).call(e))).filter(Boolean):[];r.setContentType([e||"multipart/form-data",...t].join("; "))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";r.set("Authorization","Basic "+btoa(t+":"+i))}const u=GC(e.baseURL,e.url);function h(){if(!l)return;const n=xC.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new $E("Request failed with status code "+i.status,[$E.ERR_BAD_REQUEST,$E.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}((function(e){t(e),d()}),(function(e){i(e),d()}),{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),hf(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=h:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(h)},l.onabort=function(){l&&(i(new $E("Request aborted",$E.ECONNABORTED,e,l)),l=null)},l.onerror=function(){i(new $E("Network Error",$E.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||_f;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new $E(t,n.clarifyTimeoutError?$E.ETIMEDOUT:$E.ECONNABORTED,e,l)),l=null},DR.hasStandardBrowserEnv&&(c&&ZE.isFunction(c)&&(c=c(e)),c||!1!==c&&WC(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&jC.read(e.xsrfCookieName);t&&r.set(e.xsrfHeaderName,t)}void 0===n&&r.setContentType(null),"setRequestHeader"in l&&ZE.forEach(r.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),ZE.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",HC(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",HC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(o=t=>{l&&(i(!t||t.type?new BC(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(o),e.signal&&(e.signal.aborted?o():e.signal.addEventListener("abort",o)));const p=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);p&&-1===DR.protocols.indexOf(p)?i(new $E("Unsupported protocol "+p+":",$E.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const YC={http:null,xhr:KC};ZE.forEach(YC,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const qC=e=>"- ".concat(e),zC=e=>ZE.isFunction(e)||null===e||!1===e;var JC={getAdapter:e=>{e=ZE.isArray(e)?e:[e];const{length:t}=e;let i,n;const r={};for(let o=0;o{let[t,i]=e;return"adapter ".concat(t," ")+(!1===i?"is not supported by the environment":"is not available in the build")}));throw new $E("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(qC).join("\n"):" "+qC(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:YC};function XC(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new BC(null,e)}function QC(e){XC(e),e.headers=xC.from(e.headers),e.data=VC.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return JC.getAdapter(e.adapter||NC.adapter)(e).then((function(t){return XC(e),t.data=VC.call(e,e.transformResponse,t),t.headers=xC.from(t.headers),t}),(function(t){return FC(t)||(XC(e),t&&t.response&&(t.response.data=VC.call(e,e.transformResponse,t.response),t.response.headers=xC.from(t.response.headers))),Gh.reject(t)}))}function ZC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const $C=e=>e instanceof xC?function(e){for(var t=1;tr($C(e),$C(t),!0)};return ZE.forEach(Object.keys(Object.assign({},e,t)),(function(n){const o=c[n]||r,s=o(e[n],t[n],n);ZE.isUndefined(s)&&o!==a||(i[n]=s)})),i}const tI="1.6.8",iI={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{iI[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const nI={};iI.transitional=function(e,t,i){function n(e,t){return"[Axios v"+tI+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,r,o)=>{if(!1===e)throw new $E(n(r," has been removed"+(t?" in "+t:"")),$E.ERR_DEPRECATED);return t&&!nI[r]&&(nI[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,o)}};var rI={assertOptions:function(e,t,i){if("object"!=typeof e)throw new $E("options must be an object",$E.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-- >0;){const o=n[r],s=t[o];if(s){const t=e[o],i=void 0===t||s(t,o,e);if(!0!==i)throw new $E("option "+o+" must be "+i,$E.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new $E("Unknown option "+o,$E.ERR_BAD_OPTION)}},validators:iI};const oI=rI.validators;let sI=class{constructor(e){this.defaults=e,this.interceptors={request:new pf,response:new pf}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error;const i=t.stack?t.stack.replace(/^.+\n/,""):"";e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=eI(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&rI.assertOptions(i,{silentJSONParsing:oI.transitional(oI.boolean),forcedJSONParsing:oI.transitional(oI.boolean),clarifyTimeoutError:oI.transitional(oI.boolean)},!1),null!=n&&(ZE.isFunction(n)?t.paramsSerializer={serialize:n}:rI.assertOptions(n,{encode:oI.function,serialize:oI.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&ZE.merge(r.common,r[t.method]);r&&ZE.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete r[e]})),t.headers=xC.concat(o,r);const s=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,u=0;if(!a){const e=[QC.bind(this),void 0];for(e.unshift.apply(e,s),e.push.apply(e,c),l=e.length,d=Gh.resolve(t);u{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Gh((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new BC(e,n,r),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new cI((function(t){e=t})),cancel:e}}}var dI=cI;const lI={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(lI).forEach((e=>{let[t,i]=e;lI[i]=t}));var uI=lI;const hI=function e(t){const i=new aI(t),n=TE(aI.prototype.request,i);return ZE.extend(n,aI.prototype,i,{allOwnKeys:!0}),ZE.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(eI(t,i))},n}(NC);hI.Axios=aI,hI.CanceledError=BC,hI.CancelToken=dI,hI.isCancel=FC,hI.VERSION=tI,hI.toFormData=af,hI.AxiosError=$E,hI.Cancel=hI.CanceledError,hI.all=function(e){return Gh.all(e)},hI.spread=function(e){return function(t){return e.apply(null,t)}},hI.isAxiosError=function(e){return ZE.isObject(e)&&!0===e.isAxiosError},hI.mergeConfig=eI,hI.AxiosHeaders=xC,hI.formToJSON=e=>wC(ZE.isHTMLForm(e)?new FormData(e):e),hI.getAdapter=JC.getAdapter,hI.HttpStatusCode=uI,hI.default=hI;var pI=hI;const _I=()=>{};function EI(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:_I};return e.promise=new Gh(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const fI=new Map,mI=new Map,TI=new Map;let SI=function(e){return e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot",e}({}),gI=function(e){return e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger",e}({});const RI=new aE;let CI=RI.getResult(),II=null;function vI(e){if(!II){e&&RI.setUA(e),CI=RI.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return gI.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return gI.CHROME;case"Safari":case"Mobile Safari":return gI.SAFARI;case"Edge":return gI.EDGE;case"Firefox":return gI.FIREFOX;case"QQ":case"QQBrowser":return gI.QQ;case"Opera":return gI.OPERA;case"WeChat":return gI.WECHAT;default:return e.browser.name||""}}(CI),i=yI(CI),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(CI),r=CI.os.version,o=yI(CI,!1),s=CI.device.type;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s};II={name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s}}return II}function yI(e){let t,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",i?t.split(".")[0]:t}function AI(){return vI().os}function bI(){const e=vI();return"".concat(e.os," ").concat(e.osVersion)}function wI(){const e=vI();return!!("WebKit"===CI.engine.name&&e.os===SI.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==gI.SAFARI||LI()&&e.name!==gI.SAFARI)}function OI(){return vI().name===gI.CHROME}function NI(){return vI().name===gI.SAFARI}function DI(){return vI().name===gI.EDGE}function PI(){return vI().name===gI.FIREFOX}function LI(){return vI().os===SI.IOS}function kI(e){const t=vI();return!(t.name!==gI.CHROME||!t.osVersion)&&Number(t.version)>=e}function MI(e){const t=vI();return!(t.name!==gI.CHROME||!t.osVersion)&&Number(t.version)=e}function xI(e){const t=vI();return!(t.name!==gI.SAFARI||!t.osVersion)&&Number(t.version)>=e}function VI(e,t,i){const n=vI();if(n.os!==SI.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])=e}function jI(){const e=vI();if(e.os!==SI.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function GI(){const e=vI();if(e.os!==SI.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function WI(){const e=vI();if(e.os!==SI.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function HI(){const e=vI();if(e.os!==SI.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function KI(){return NI()&&navigator.maxTouchPoints>0}function YI(){return vI().name===gI.WECHAT}function qI(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function zI(){const e=AI();return function(){const{deviceType:e}=vI();return"mobile"===e||"tablet"===e}()||e===SI.ANDROID||e===SI.IOS||e===SI.HARMONY_OS}function JI(){const e=vI();return e.name!==gI.EDGE&&e.name!==gI.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function XI(){return AI()===SI.ANDROID}function QI(){const e=vI();return XI()&&(e.name===gI.CHROME||e.name===gI.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function ZI(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function $I(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ev(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),ZI(this,"code",void 0),ZI(this,"message",void 0),ZI(this,"data",void 0),ZI(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack)}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function nv(e,t){if("boolean"!=typeof e)throw new iv(tv.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function rv(e,t,i){if(!Dn(i).call(i,e))throw new iv(tv.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function ov(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(en||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new iv(tv.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function sv(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new iv(tv.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&ov(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&ov(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&ov(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&ov(e.ideal,"".concat(t,".ideal"),1,1/0)}else ov(e,t,1,1/0)}function av(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new iv(tv.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!lv(e,i,n,r))throw new iv(tv.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function cv(e,t){if(!Array.isArray(e))throw new iv(tv.INVALID_PARAMS,"".concat(t," should be an array"))}function dv(e){return null==e}function lv(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return!1;for(let t=0;t255)return!1}return!0}(e))}var uv=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(uv||{}),hv=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(hv||{});const pv=new class{constructor(){ZI(this,"_clientSize",null),ZI(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),ZI(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),ZI(this,"getStyle",(e=>window.getComputedStyle(e,null))),ZI(this,"checkCssVisibleProperty",(e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:o,opacity:s,filter:a}=n;return("none"===r||Dn(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter((e=>{var t;const i=e.split("(")[0];return Dn(t=["brightness","blur","opacity"]).call(t,i)})).map((e=>{const[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1)}})),i)})),ZI(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let i=!0,n=!0;const r=e=>t(e);let o=e;for(;o&&n;)r(o)||(i=!1,n=!1),o=o.parentElement,o||(n=!1);return i})),ZI(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),ZI(this,"getSizeAboutClient",(e=>{const{width:t,height:i,left:n,right:r,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),ZI(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),ZI(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),ZI(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),ZI(this,"getPointPositionList",(()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,o=t/6,s=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(o*t*a-1e5)/a:o*t)*a)/a;s.push({x:c,y:d})}return[...s]})),ZI(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),ZI(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),ZI(this,"checkSizeOfPartInClient",(()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:o,clientMin:s}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e(this._clientSize=null,{visible:!1,reason:e}))),ZI(this,"checkOneElementVisible",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(uv.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(uv.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(uv.SIZE)}}return this.returnHiddenResult(uv.STYLE)}return this.returnHiddenResult(hv.UNMOUNTED)}return this.returnHiddenResult(hv.INVALID_HTML_ELEMENT)})),ZI(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function _v(e){return(new TextEncoder).encode(e)}const Ev=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i};const fv=async e=>function(e,t){let i="";return new Uint8Array(e).forEach((e=>{i+=e.toString(t).padStart(2,"0")})),i}(await crypto.subtle.digest("SHA-256",_v(e)),16);let mv=class{constructor(){ZI(this,"_events",{}),ZI(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r1?t-1:0),n=1;n{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}};let Tv=null;function Sv(){if(Tv)return Tv;if(window.electron)return Tv=window.electron;if(!window.require)return null;try{return Tv=window.require("electron"),Tv}catch(e){return null}}let gv=function(e){return e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.PRELOAD="PRELOAD",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload",e}({}),Rv=function(e){return e.TRACER="tracer",e}({});function Cv(e){return ov(e.timeout,"config.timeout",0,1e5),ov(e.timeoutFactor,"config.timeoutFactor",0,100,!1),ov(e.maxRetryCount,"config.maxRetryConfig",0,1/0),ov(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let Iv=function(e){return e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",e}({}),vv=function(e){return e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.FALLBACK="FALLBACK",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e}({});function yv(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function Av(e){return av(e.turnServerURL,"turnServerURL"),av(e.username,"username"),av(e.password,"password"),e.udpport&&ov(e.udpport,"udpport",1,99999,!0),e.forceturn&&nv(e.forceturn,"forceturn"),e.security&&nv(e.security,"security"),e.tcpport&&ov(e.tcpport,"tcpport",1,99999,!0),!0}function bv(e){return void 0!==e.level&&rv(e.level,"level",[1,2,3]),void 0!==e.delay&&ov(e.delay,"delay",0,3e3,!0),!0}let wv=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",e}({}),Ov=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),Nv=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),Dv=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function Pv(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r{e.emit(t,...n,i,r)}))}function Lv(e,t){if(0===e.getListeners(t).length)return Gh.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r2?i-2:0),r=2;r2?r-2:0),s=2;s{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new iv(tv.UNEXPECTED_ERROR,"handler is not sync");return i}const Uv=new class extends mv{set networkState(e){this.emit(Dv.NETWORK_STATE_CHANGE,e,this._networkState),e===Nv.ONLINE?this.emit(Dv.ONLINE):e===Nv.OFFLINE&&(this.onlineWaiter=new Gh((e=>{this.once(Dv.ONLINE,(()=>{this.onlineWaiter=void 0,e(Nv.ONLINE)}))})),this.emit(Dv.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===Nv.ONLINE}constructor(){super(),ZI(this,"_moduleName","network-indicator"),ZI(this,"_networkState",Nv.ONLINE),ZI(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=Nv.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=Nv.OFFLINE}))}};function xv(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function Vv(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function Fv(e){void 0!==Gh?Gh.resolve().then(e):setTimeout(e,0)}function Bv(e){return JSON.parse(JSON.stringify(e))}function jv(e){try{return Bv(e)}catch(t){return e}}const Gv={};function Wv(e,t){Gv[t]||(Gv[t]=!0,e())}function Hv(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:16,i=(new TextEncoder).encode(e);if(i.length>t)i=i.slice(0,t);else if(i.lengthe+t.length),0),r=new Uint8Array(new ArrayBuffer(n));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function zv(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function Jv(e){let t=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+="string"==typeof e?zv(e):e.size})),t+138}function Xv(e){const t=new iv(tv.TIMEOUT,"timeout");return new Gh(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function Qv(e){return new Gh((t=>{window.setTimeout(t,e)}))}function Zv(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+Zv(e-i.length,"")}function $v(){return Zv(32,"").toUpperCase()}const ey=()=>{},ty=new class{constructor(){ZI(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:s,args:o,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,ev(ev({},r),{},{fn:e,args:o,skipFn:n}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:o,skipFn:n})}}},iy=ty.throttleByKey.bind(ty);function ny(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function ry(e,t){if(!ny(e)||!ny(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i}function sy(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function ay(e){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,o,s){return n(function(e,t){return e<>>32-t}(n(n(t,e),n(r,s)),o),i)}function o(e,t,i,n,o,s,a){return r(t&i|~t&n,e,t,o,s,a)}function s(e,t,i,n,o,s,a){return r(t&n|i&~n,e,t,o,s,a)}function a(e,t,i,n,o,s,a){return r(t^i^n,e,t,o,s,a)}function c(e,t,i,n,o,s,a){return r(i^(t|~n),e,t,o,s,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t>2]|=e.charCodeAt(t)<>2]|=128<0}lock(e){let t;this.locks+=1,dy.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new Gh((i=>{t=()=>{this.locks-=1,dy.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}};function uy(e,t){return function(i,n,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var s=arguments.length,a=new Array(s),c=0;c{await function(e){return new Gh((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new Gh((async(n,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;ca=!0,c}class Ey{constructor(e){ZI(this,"input",[]),ZI(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:Jn(e=this.input).call(e,((e,t)=>e+t))/this.input.length}}let fy,my=0,Ty=0;function Sy(e,t,i,n){return new Gh(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),my+=zv(t.data)):i&&(t.data.size?my+=t.data.size:t.data instanceof FormData?my+=Jv(t.data):my+=zv(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,pI.request(t).then((e=>{"string"==typeof e.data?Ty+=zv(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Ty+=e.data.byteLength:Ty+=zv(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{pI.isCancel(e)?o(new iv(tv.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new iv(tv.NETWORK_TIMEOUT,e.message)):e.response?o(new iv(tv.NETWORK_RESPONSE_ERROR,e.response.status)):o(new iv(tv.NETWORK_ERROR,e.message))}))}))}async function gy(e,t){const i=new Blob([t.data],{type:"buffer"});return await Sy(e,ev(ev({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const Ry=()=>void 0!==window.isSecureContext;const Cy=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return"".concat(e,".").concat(100*(Number(t)+1))}return"4.0.0.999"}("4.22.0"),Iy=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let vy=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const yy={MIN_FRAME_RATE:1,MAX_FRAME_RATE:30,MAX_THRESHOLD_FRAMERATE:30,BITRATE_MIN_THRESHOLD:100,BITRATE_MAX_THRESHOLD:100,MAX_SCALE:5,BWE_SCALE_UP_THRESHOLD:.6,BWE_SCALE_DOWN_THRESHOLD:.6,PERF_SCALE_UP_THRESHOLD:.7,PERF_SCALE_DOWN_THRESHOLD:.6,MOTION_RESOLUTION_FACTOR:.8,MOTION_BITRATE_FACTOR:.6,DETAIL_FRAMERATE_FACTOR:.8,DETAIL_BITRATE_FACTOR:.6,BALANCE_RESOLUTION_FACTOR:.9,BALANCE_FRAMERATE_FACTOR:.9,BALANCE_BITRATE_FACTOR:.6,OVERUSE_TIMES_THRESHOLD:10,UNDERUSE_TIMES_THRESHOLD:40},Ay="v4.22.0-0-g8569241d-dirty(8/15/2024, 7:04:06 PM)",by=ev(ev({PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:yy,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,CUSTOM_ADAPTATION_DEFAULT_MODE:"",ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,ENABLE_PRELOAD:!0},{ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,USE_PUB_RTX:!0,USE_SUB_RTX:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_DATASTREAM_2:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,USE_XR:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,ENABLE_PREALLOC_PC:!1,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,PRE_SUB_NUM:2,ENABLE_PRE_SUB:!1,ENABLE_AUT_FEEDBACK:!1}),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1});function wy(e,t,i){var n,r,o;Dn(n=Object.keys(by)).call(n,e)&&(!i&&Dn(r=Object.keys(Ny)).call(r,e)||(by[e]=t,"ENABLE_VIDEO_SEI"===e&&!0===t&&(by.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,by.USE_NEW_NETWORK_CONFIG=o,o&&(by.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],by.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],by.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],by.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],by.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",by.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",by.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(by.ENABLE_INSTANT_VIDEO=!0,by.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(by.ENABLE_AUT_CC=!0)))}function Oy(e){return by[e]}const Ny={};var Dy=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}(Dy||{});class Py{constructor(e,t,i,n){ZI(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:vy.Default}}dispatch(e){this.state=function(e,t){switch(t.type){case Dy.SET_SESSION_ID:return ev(ev({},e),{},{sessionId:t.sessionId});case Dy.SET_P2P_ID:return ev(ev({},e),{},{p2pId:t.p2pId});case Dy.SET_UID:return ev(ev({},e),{},{uid:t.uid});case Dy.SET_INT_UID:return ev(ev({},e),{},{intUid:t.intUid});case Dy.SET_PUB_ID:return ev(ev({},e),{},{pubId:t.pubId});case Dy.KEY_METRIC_CLIENT_CREATED:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{clientCreated:t.metric})});case Dy.KEY_METRIC_JOIN_START:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{joinStart:t.metric})});case Dy.AVOID_JOIN_START:return ev(ev({},e),{},{avoidJoinStart:t.avoidJoinStart});case Dy.KEY_METRIC_JOIN_END:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{joinEnd:t.metric})});case Dy.KEY_METRIC_REQUEST_AP_START:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{requestAPStart:t.metric})});case Dy.KEY_METRIC_REQUEST_AP_END:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{requestAPEnd:t.metric})});case Dy.KEY_METRIC_JOIN_GATEWAY_START:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case Dy.KEY_METRIC_JOIN_GATEWAY_END:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case Dy.KEY_METRIC_PEER_CONNECTION_START:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case Dy.KEY_METRIC_PEER_CONNECTION_END:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case Dy.KEY_METRIC_DESCRIPTION_START:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{descriptionStart:t.metric})});case Dy.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case Dy.KEY_METRIC_ICE_CONNECTION_END:return ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case Dy.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=ev(ev({},i[n]),t.metric),ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{publish:[...i]})})):ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case Dy.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==n?(i[n]=ev(ev({},i[n]),t.metric),ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{subscribe:[...i]})})):ev(ev({},e),{},{keyMetrics:ev(ev({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case Dy.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case Dy.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=ev(ev({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case Dy.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case Dy.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case Dy.SET_USE_P2P:return ev(ev({},e),{},{useP2P:t.val});case Dy.SET_TRANSPORT_TYPE:return ev(ev({},e),{},{p2pTransport:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:Dy.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set codec(e){this.state.codec=e}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:Dy.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:Dy.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:Dy.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:Dy.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:Dy.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:Dy.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:Dy.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:Dy.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}clientCreated(){this.dispatch({type:Dy.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:Dy.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:Dy.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:Dy.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:Dy.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:Dy.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:Dy.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:Dy.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:Dy.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:Dy.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:Dy.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:Dy.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:Dy.KEY_METRIC_PUBLISH,metric:ev(ev({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:Dy.KEY_METRIC_SUBSCRIBE,metric:ev(ev(ev(ev(ev({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,i,n){e.forEach((e=>{this.dispatch({type:Dy.KEY_METRIC_SUBSCRIBE,metric:ev(ev(ev({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:Dy.RECORD_JOIN_CHANNEL_SERVICE,record:ev(ev({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:Dy.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:Dy.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:Dy.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:Dy.AVOID_JOIN_START,avoidJoinStart:e})}}let Ly=function(e){return e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1",e}({});!function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722"}({});const ky=128,My=96,Uy=1e3,xy=10;let Vy=0;function Fy(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function By(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function jy(e){for(var t=1;tthis.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};class Wy{constructor(e){Fy(this,"logger",void 0),Fy(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{for(const t in Yy)if(Object.prototype.hasOwnProperty.call(Yy,t)&&Yy[t]===e)return t;return"DEFAULT"};const Jy=new class{constructor(){Fy(this,"proxyServerURL",void 0),Fy(this,"logLevel",Yy.DEBUG),Fy(this,"uploadState","collecting"),Fy(this,"uploadLogWaitingList",[]),Fy(this,"uploadLogUploadingList",[]),Fy(this,"uploadErrorCount",0),Fy(this,"currentLogID",0),Fy(this,"url",void 0),Fy(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{this.log(...t)}),Date.now()-qy);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=Hy()+" Agora-SDK [".concat(zy(n),"]:"),this.appendLogToWaitingList(n,...t),n{this.uploadLog(...t)}),Date.now()-qy);const n=Math.max(0,Math.min(4,t[0]));t[0]=Hy()+" Agora-SDK [".concat(zy(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!Oy("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:Cy,process_id:Oy("PROCESS_ID"),payload:JSON.stringify(e)};return _y((async()=>{const e=await pI.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(Oy("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(Oy("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(t=>{const i={status:-1,message:t.message,errorRange:e.map((e=>e.log_item_id))};return t.response?(i.status=t.response.status,i.data=t.response.data,i.headers=t.response.headers):t.request&&(i.status=t.request.status),Gy.reportLogUploadError(i),!0}),{timeout:Oy("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:Oy("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,Oy("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),Oy("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),Oy("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),Oy("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var Xy;function Qy(e){return av(e.reportId,"params.reportId",0,100,!1),av(e.category,"params.category",0,100,!1),av(e.event,"params.event",0,100,!1),av(e.label,"params.label",0,100,!1),ov(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(Xy={}).FREE="free",Xy.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}({});const Zy={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let $y=function(e){return e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",e}({}),eA=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let tA=function(e){return e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",e}({});class iA{constructor(){Fy(this,"baseInfoMap",new Map),Fy(this,"proxyServer",void 0),Fy(this,"eventUploadTimer",void 0),Fy(this,"setSessionIdTimer",void 0),Fy(this,"url",void 0),Fy(this,"backupUrl",void 0),Fy(this,"_appId",void 0),Fy(this,"keyEventUploadPendingItems",[]),Fy(this,"normalEventUploadPendingItems",[]),Fy(this,"apiInvokeUploadPendingItems",[]),Fy(this,"apiInvokeCount",0),Fy(this,"ltsList",[]),Fy(this,"lastSendNormalEventTime",Date.now()),Fy(this,"customReportCounterTimer",void 0),Fy(this,"customReportCount",0),Fy(this,"extApiInvoke",(async e=>{for(const t of e){const e=jy(jy({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:Rv.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),Oy("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),Oy("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void Jy.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,Jy.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"ms")),this.baseInfoMap.set(e,t)}setAppId(e){this._appId=e}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),s=!!Oy("SHOW_REPORT_INVOKER_LOG");s&&Jy.info("".concat(t.name," start"),t.options);let a=!1;Qv(t.timeout).then((()=>{a||(this.sendApiInvoke(jy(jy({},o()),{},{error:tv.API_INVOKE_TIMEOUT,success:!1})),Jy.debug("".concat(t.name," timeout")))}));const c=new iv(tv.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke(jy(jy({},o()),{},{success:!0},t.reportResult&&{result:e})),s&&Jy.info("".concat(t.name," onSuccess")),e};return i?iy(n,t.name+"Success",i,(()=>a=!0)):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(jy(jy({},o()),{},{success:!1,error:e})),s&&Jy.info("".concat(t.name," onFailure"),e.toString())};return i?iy(n,t.name+"Error",i,(()=>a=!0)):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:Oy("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:Iy?"global":"oversea",areas:Oy("AREAS")&&Oy("AREAS").join(",")},t.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=jy(jy({},n),{},{eventType:$y.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:Ay,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:Oy("PROCESS_ID"),appType:Oy("APP_TYPE"),success:!0,version:Cy,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:Dn(p=window.navigator.userAgent).call(p,"AgoraWebView")?42:20,clientRole:l,serviceId:Oy("PROCESS_ID"),extensionID:Oy("PLUGIN_INFO").join(",")||""});var p;this.send({type:eA.SESSION,data:h},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:eA.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:eA.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:o,avoidJoinStartTime:s}=t,a=r-(o&&s?s:i.startTime),c=jy(jy({},n),{},{eventType:$y.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:a,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:t.preload?1:0});t.succ&&(i.lastJoinSuccessTime=r),this.send({type:eA.JOIN_GATEWAY,data:c},!0)}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=jy(jy({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:eA.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:eA.PUBLISH,data:o},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,o=Date.now(),s=jy(jy({},r),{},{eventType:$y.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:eA.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...d_(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const o=r.info,s=Date.now(),a=jy(jy({},o),{},{eventType:$y.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:eA.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=jy(jy(jy({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((n.firstFrame||s)-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=jy(jy(jy({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:i,data:a},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy(jy({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:$y.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:eA.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy(jy({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:$y.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:eA.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=jy(jy(jy({},o),n),{},{eventType:t,lts:s});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:eA.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:eA.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{eventType:$y.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:eA.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?Jy.debug("reportProxyServerurl: ".concat(e)):Jy.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:eA.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now();(function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return[e];e[t]="";const r=zv(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;cthis.send({type:eA.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy(jy({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:eA.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy(jy({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:eA.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=jy(jy(jy({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:eA.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>Oy("CUSTOM_REPORT_LIMIT"))throw new iv(tv.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:eA.USER_ANALYTICS,data:jy(jy({sid:e},t),{},{lts:i})})));try{Oy("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw Jy.error("send custom report message failed",e.toString()),new iv(tv.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=Oy("NOT_REPORT_EVENT");if(e.tag&&Dn(t)&&Dn(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:o}=i.info;let s;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof iv){const{code:t,message:i}=e.error;s=t||i||e.error.toString()}else s=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:o,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?s:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:eA.API_INVOKE,data:a},!1),!0}appendSessionId(){iA.__CLIENT_LIST__.forEach((e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;iOy("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),oE(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),Oy("ENABLE_EVENT_REPORT")?(i.length&&(Oy("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{Oy("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>Oy("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-Oy("NORMAL_EVENT_QUEUE_CAPACITY")),Jy.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){Uv.networkState===Nv.OFFLINE&&await Gh.race([Uv.onlineWaiter,Qv(2*hy.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=_v(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(eA).forEach((i=>{let[n,r]=i;r===e.type&&(t=tA[n])})),t})(e),o=new DataView(n);o.setUint16(0,i.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=Ev(t,new Uint8Array(n)),t=Ev(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(Oy("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(Oy("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(Oy("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(Oy("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await Sy(n,{timeout:1e4,data:t(e),headers:jy(jy({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};Uv.networkState===Nv.OFFLINE&&await Gh.race([Uv.onlineWaiter,Qv(2*hy.maxRetryTimeout)]);const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(Oy("EVENT_REPORT_DOMAIN"),"&p=").concat(Oy("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(Oy("EVENT_REPORT_DOMAIN"),":").concat(Oy("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(Oy("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(Oy("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(Oy("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(Oy("STATS_COLLECTOR_PORT")).concat(n)));try{t?await gy(r,{timeout:1e4,data:i}):await Sy(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},Zy);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:Rv.TRACER}).onSuccess()}}function nA(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),s=0;s(c.onSuccess(e.reportResult&&t),t))).catch((e=>{throw c.onError(e),e})):(c.onSuccess(e.reportResult&&t),t)}catch(e){throw c.onError(e),e}}}return n}}Fy(iA,"__CLIENT_LIST__",[]);const rA=new iA;Gy.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=Uv.networkState,rA.reportApiInvoke(null,{name:"logUploadError",options:e,tag:Rv.TRACER}).onSuccess("logUploadError")}));const oA=["CHINA","GLOBAL"],sA=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=n,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=sA,Iy||(by.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],by.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],by.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],by.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],by.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],by.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],by.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",by.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",by.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",by.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",by.AREAS=["NORTH_AMERICA","OVERSEA"]);const aA=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],cA=[];function dA(e,t){return!!t&&cA.some((i=>i.uid===e&&i.channelName===t))}iA.__CLIENT_LIST__=cA;var lA=Rm.forEach,uA=Bn("forEach")?[].forEach:function(e){return lA(this,e,arguments.length>1?arguments[1]:void 0)};wi({target:"Array",proto:!0,forced:[].forEach!=uA},{forEach:uA});var hA=Xi("Array").forEach,pA=pn,_A=Ze,EA=l,fA=hA,mA=Array.prototype,TA={DOMTokenList:!0,NodeList:!0},SA=function(e){var t=e.forEach;return e===mA||EA(mA,e)&&t===mA.forEach||_A(TA,pA(e))?fA:t},gA=i(SA),RA=Je,CA=eo;wi({target:"Object",stat:!0,forced:n((function(){CA(1)}))},{keys:function(e){return CA(RA(e))}});var IA=i(ie.Object.keys),vA=i(zn),yA=wi,AA=If,bA=d([].reverse),wA=[1,2];yA({target:"Array",proto:!0,forced:String(wA)===String(wA.reverse())},{reverse:function(){return AA(this)&&(this.length=this.length),bA(this)}});var OA=Xi("Array").reverse,NA=l,DA=OA,PA=Array.prototype,LA=function(e){var t=e.reverse;return e===PA||NA(PA,e)&&t===PA.reverse?DA:t},kA=LA,MA=i(kA),UA=wi,xA=If,VA=jc,FA=te,BA=xi,jA=Gi,GA=Z,WA=E_,HA=ht,KA=Xc,YA=Mf("slice"),qA=HA("species"),zA=Array,JA=Math.max;UA({target:"Array",proto:!0,forced:!YA},{slice:function(e,t){var i,n,r,o=GA(this),s=jA(o),a=BA(e,s),c=BA(void 0===t?s:t,s);if(xA(o)&&(i=o.constructor,(VA(i)&&(i===zA||xA(i.prototype))||FA(i)&&null===(i=i[qA]))&&(i=void 0),i===zA||void 0===i))return KA(o,a,c);for(n=new(void 0===i?zA:i)(JA(c-a,0)),r=0;a1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),ng(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,Jy)}throw(){super.throw(Jy)}}function Tb(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw Jy.error("Invalid Channel Name ".concat(e)),new mb(tv.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function Sb(e){if(!function(e){return"number"==typeof e&&Math.floor(e)===e&&0<=e&&e<=4294967295}(e)&&!lv(e,1,255))throw new mb(tv.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");"string"==typeof e&&Jy.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let gb=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const Rb={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},Cb={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Ib(e,t){av(e.url,"".concat(t,".url"),1,1e3,!1),dv(e.x)||ov(e.x,"".concat(t,".x"),0,1e4),dv(e.y)||ov(e.y,"".concat(t,".y"),0,1e4),dv(e.width)||ov(e.width,"".concat(t,".width"),0,1e4),dv(e.height)||ov(e.height,"".concat(t,".height"),0,1e4),dv(e.zOrder)||ov(e.zOrder,"".concat(t,".zOrder"),0,255),dv(e.alpha)||ov(e.alpha,"".concat(t,".alpha"),0,1,!1)}const vb={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let yb=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),Ab=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),bb=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});function wb(e){if(!e.channelName)throw new mb(tv.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new mb(tv.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&av(e.token,"info.token",1,2047),Sb(e.uid),Tb(e.channelName),!0}let Ob=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),Nb=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),Db=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),Pb=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),Lb=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),kb=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e}({}),Mb=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),Ub=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),xb=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const Vb=[xb.AFRICA,xb.ASIA,xb.CHINA,xb.EUROPE,xb.GLOBAL,xb.INDIA,xb.JAPAN,xb.NORTH_AMERICA,xb.OCEANIA,xb.OVERSEA,xb.SOUTH_AMERICA];let Fb=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const Bb={CHINA:{},ASIA:{CODE:Fb.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:Fb.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:Fb.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:Fb.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:Fb.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:Fb.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:Fb.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:Fb.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:Fb.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:Fb.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:Fb.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:Fb.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:Fb.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};Iy&&(Bb.CHINA={CODE:Fb.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let jb=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e}({});class Gb extends mv{constructor(e,t){super(),ng(this,"onICEConnectionStateChange",void 0),ng(this,"onConnectionStateChange",void 0),ng(this,"onDTLSTransportStateChange",void 0),ng(this,"onDTLSTransportError",void 0),ng(this,"onICETransportStateChange",void 0),ng(this,"onFirstAudioReceived",void 0),ng(this,"onFirstVideoReceived",void 0),ng(this,"onFirstAudioDecoded",void 0),ng(this,"onFirstVideoDecoded",void 0),ng(this,"onFirstVideoDecodedTimeout",void 0),ng(this,"onSelectedLocalCandidateChanged",void 0),ng(this,"onSelectedRemoteCandidateChanged",void 0),ng(this,"getLocalVideoStats",void 0)}}class Wb extends Gb{constructor(e,t){super(e,t),ng(this,"establishPromise",void 0)}}let Hb=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),Kb=function(e){return e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.RELAY=2]="RELAY",e}({}),Yb=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.TCP_RESTART=1]="TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({}),qb=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),zb=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),Jb=function(e){return e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e}({}),Xb=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),Qb=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),Zb=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),$b=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),ew=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),tw=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),iw=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),nw=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),rw=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),ow=function(e){return e.ABORT="abort",e}({}),sw=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({}),aw=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const cw={[ob.ACCESS_POINT]:{[cb.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[cb.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[cb.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[cb.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[cb.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[cb.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[cb.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[ob.UNILBS]:{[ab.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[ab.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[ab.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[ab.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[ab.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[ab.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[ab.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[ab.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[ab.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[ab.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[ab.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[ab.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[ob.STRING_UID_ALLOCATOR]:{[sb.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[sb.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[sb.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function dw(e){const t=cw[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===ob.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}const lw={[db.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[db.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[db.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[db.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[db.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[db.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[db.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[db.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[db.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[db.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[db.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[db.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[db.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[db.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[db.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[db.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[db.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[db.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[db.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[db.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[db.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[db.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[db.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[db.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[db.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[db.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[db.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[db.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[db.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[db.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[db.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[db.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[db.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[db.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[db.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[db.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[db.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[db.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[db.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[db.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[db.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[db.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[db.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[db.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[db.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[db.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[db.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[db.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[db.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[db.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[db.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[db.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[db.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[db.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[db.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[db.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[db.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[db.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[db.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[db.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[db.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[db.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[db.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function uw(e){const t=lw[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function hw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function pw(e){for(var t=1;te.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))}function Ew(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=Oy("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r)}const fw=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,mw=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,Tw=/wss:\/\/(.+):([0-9]+)\/?/,Sw=/wss:\/\/(.[^\/]+)\/?/;let gw=0;class Rw{constructor(e,t){ng(this,"id",0),ng(this,"store",void 0),ng(this,"recordIndex",void 0),ng(this,"websockets",[]),ng(this,"try443PortDuration",2e3),ng(this,"forceCloseWSDuration",5e3),ng(this,"try443PortTimeout",null),ng(this,"forceCloseTimeout",null),ng(this,"isTry443PortFailed",!1),ng(this,"isNormalPortFailed",!1),ng(this,"useDoubleDomain",!1),ng(this,"useProxy",!1),ng(this,"startTime",Date.now()),this.id=++gw,this.try443PortDuration=Oy("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout)}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r{var i;return Dn(i=e.host).call(i,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(Ew(pw(pw({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=pw({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}a.push(Ew(i,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new mb(tv.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=EI();this.store&&this.store.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},this.recordIndex),o.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState)),t?this.isTry443PortFailed=_w(o):this.isNormalPortFailed=_w(o),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:Mb.A_ROUND_WS_FAILED}))},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...o);return i||(()=>{const i=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))};if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{if(this.logger("2s timeout, isWebsocket created: ",c.isResolved),c.isResolved)return i();vI().os===SI.MAC_OS&&PI()&&i(),this.createWebSocket(e,!0,!0).then((e=>c.resolve(e))).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration)}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(fw)||[],t||([,i,n]=e.match(mw)||[]),i&&n||([,i,n]=e.match(Tw)||[]),i&&n||([,i]=e.match(Sw)||[]),i||Jy.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(Jy.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function Cw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class Iw extends mv{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Dn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(fb.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(fb.CONNECTED):"closed"===this._state?this.emit(fb.CLOSED):"failed"===this._state&&this.emit(fb.FAILED))}resetReconnectCount(e){Jy.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),ng(this,"connectionID",0),ng(this,"currentURLIndex",0),ng(this,"urls",[]),ng(this,"_reconnectMode","tryNext"),ng(this,"reconnectReason",void 0),ng(this,"_initMutex",new ly("websocket")),ng(this,"name",void 0),ng(this,"_state","closed"),ng(this,"reconnectInterrupter",void 0),ng(this,"websocket",void 0),ng(this,"retryConfig",void 0),ng(this,"reconnectCount",0),ng(this,"forceCloseTimeout",5e3),ng(this,"onlineReconnectListener",void 0),ng(this,"useCompress",void 0),ng(this,"tryDoubleDomain",!1),ng(this,"use443PortOnly",!1),ng(this,"wsInflateLength",0),ng(this,"wsDeflateLength",0),ng(this,"closeEstablishingWs",(()=>{})),ng(this,"store",void 0),ng(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===Nv.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=EI(),t=this.urls[this.currentURLIndex];Oy("ENABLE_PREALLOC_PC")&&this.emit($b.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(fb.CLOSED,(()=>{e.reject(new iv(tv.WS_DISCONNECT))})),this.once(fb.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void Jy.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),Jy.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new iv(tv.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new iv(tv.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=EI();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),Jy.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(Jy.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new iv(tv.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=kv(this,fb.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void Jy.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new iv(tv.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},o=e=>{this.emit(fb.ON_MESSAGE,e)},s=e=>{Jy.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),Oy("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=Oy("GATEWAY_WSS_ADDRESS")),Jy.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=o,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,n=e instanceof iv,o=n&&e.code===tv.WS_ABORT,s=n&&e.code===tv.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());Jy.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},a),t||s?(i.reject(t?new iv(tv.WS_DISCONNECT,"websocket is closed: ".concat(c)):new iv(tv.WS_ERR,"init websocket failed: ".concat(c))),s&&Jy.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;Jy.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||Uv.isOnline||!Uv.onlineWaiter||(this.onlineReconnectListener=Uv.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=py(this.reconnectCount,this.retryConfig);Jy.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Gh.race([Qv(t),this.onlineReconnectListener||new Gh((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(fb.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(fb.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);Jy.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(fb.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(Jy.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(fb.RECONNECT_WAITTING_FINISH,e),this.urls=await Pv(this,fb.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;Jy.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&Dn(n).call(n,"dynamic key expired")?(this.emit(fb.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class vw extends Iw{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=EI(),n=function(e,t){return new Rw(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{Jy.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new iv(tv.WS_ABORT,"choose best websocket aborted"))};const r=Oy("GATEWAY_DOMAINS");return Jy.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class yw extends Iw{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new Gh(((i,n)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{Jy.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new iv(tv.WS_ABORT,"choose best websocket aborted"))};const s=Oy("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=s.find((t=>-1!==c?Dn(e).call(e,t,c):Dn(e).call(e,t)));Jy.debug("[choose-best-ws] currentDomain: ",d,", domains: ",s);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{s.forEach((t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",o.push(n),Jy.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(Jy.debug("[choose-best-ws] ws create failed, fallback to single url"),o.forEach((e=>e.close()));o.length;)o.pop();l=!0}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},t),o.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;Jy.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{Jy.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,i(e)},e.onclose=e=>{if(a=e,r)return;o.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(Jy.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a))},e.onmessage=t=>{Jy.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),Qv(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;Jy.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),o.push(r),r.binaryType="arraybuffer"}catch(e){const t=new iv(tv.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return Jy.error("[".concat(this.name,"]").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{Jy.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},Qv(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class Aw extends mv{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===lb.CONNECTED?this.emit(ub.WS_CONNECTED):e===lb.RECONNECTING?this.emit(ub.WS_RECONNECTING,this._websocketReconnectReason):e===lb.CLOSED&&this.emit(ub.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),ng(this,"_disconnectedReason",void 0),ng(this,"_websocketReconnectReason",void 0),ng(this,"_connectionState",lb.CLOSED),ng(this,"reconnectToken",void 0),ng(this,"websocket",void 0),ng(this,"openConnectionTime",void 0),ng(this,"clientId",void 0),ng(this,"lastMsgTime",Date.now()),ng(this,"uploadCache",[]),ng(this,"uploadCacheInterval",void 0),ng(this,"rttRolling",new Ey(5)),ng(this,"pingpongTimer",void 0),ng(this,"wsInflateDataTimer",void 0),ng(this,"pingpongTimeoutCount",0),ng(this,"joinResponse",void 0),ng(this,"multiIpOption",void 0),ng(this,"initError",void 0),ng(this,"spec",void 0),ng(this,"store",void 0),ng(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(ub.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===_b.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===_b.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(vv.UID_BANNED);break;case 15:this.close(vv.IP_BANNED);break;case 16:this.close(vv.CHANNEL_BANNED)}if(t._type===_b.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case db.ERR_LICENSE_MISSING:this.close(vv.LICENSE_MISSING);break;case db.ERR_LICENSE_EXPIRED:this.close(vv.LICENSE_EXPIRED);break;case db.ERR_LICENSE_MINUTES_EXCEEDED:this.close(vv.LICENSE_MINUTES_EXCEEDED);break;case db.ERR_LICENSE_PERIOD_INVALID:this.close(vv.LICENSE_PERIOD_INVALID);break;case db.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(vv.LICENSE_MULTIPLE_SDK_SERVICE);break;case db.ERR_LICENSE_ILLEGAL:this.close(vv.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new vw("gateway-".concat(this.clientId),this.spec.retryConfig,!0,Oy("JOIN_GATEWAY_USE_DUAL_DOMAIN"),Oy("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===lb.CONNECTED&&this.reconnect("retry",Ov.OFFLINE)}))}async request(e,t,i,n){const r=Zv(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Gh(((t,i)=>{if(this.connectionState===lb.CONNECTED)return t();const n=()=>{this.off(ub.WS_CLOSED,r),t()},r=()=>{this.off(ub.WS_CONNECTED,n),i(new mb(tv.WS_ABORT))};this.once(ub.WS_CONNECTED,n),this.once(ub.WS_CLOSED,r),e!==hb.PUBLISH&&e!==hb.PUBLISH_DATASTREAM&&e!==hb.SUBSCRIBE&&e!==hb.SUBSCRIBE_DATASTREAM&&e!==hb.UNSUBSCRIBE&&e!==hb.UNSUBSCRIBE_DATASTREAM&&e!==hb.UNPUBLISH&&e!==hb.UNPUBLISH_DATASTREAM&&e!==hb.CONTROL&&e!==hb.RESTART_ICE||this.once(ub.DISCONNECT_P2P,(()=>{i(new mb(tv.DISCONNECT_P2P))})),e!==hb.PUBLISH&&e!==hb.RESTART_ICE||this.once(ub.ABORT_P2P_EXECUTION,(()=>{i(new mb(tv.DISCONNECT_P2P))}))}));if(this.connectionState!==lb.CONNECTING&&this.connectionState!==lb.RECONNECTING||e===hb.JOIN||e===hb.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Gh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(ub.WS_CLOSED,c),this.off(ub.WS_RECONNECTING,c),this.emit(ub.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new mb(tv.WS_ABORT,"type: ".concat(e))),this.off(ub.WS_CLOSED,c),this.off(ub.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(ub.WS_CLOSED,c),this.once(ub.WS_RECONNECTING,c),Qv(Oy("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(Jy.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(ub.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===lb.CLOSED||e===hb.LEAVE)throw new mb(tv.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===hb.JOIN||e===hb.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=uw(l),h=new mb(tv.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(Jy.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===db.ERR_TOO_MANY_BROADCASTERS?e===hb.JOIN||e===hb.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===db.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,Jy.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ov.MULTI_IP)):this.reconnect(u.action,Ov.SERVER_ERROR),e===hb.JOIN||e===hb.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Gh((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void Jy.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(pb.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=Oy("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==lb.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),Oy("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Gh(((t,i)=>{this.once(ub.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(ub.WS_CLOSED,(()=>i(this.initError||new mb(tv.WS_ABORT)))),this.connectionState=lb.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||vv.LEAVE,this.connectionState=lb.CLOSED,Jy.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(ub.ABORT_P2P_EXECUTION);const e=await Pv(this,ub.REQUEST_JOIN_INFO),t=await this.request(hb.JOIN,e);if(!t)return this.emit(ub.REPORT_JOIN_GATEWAY,Mb.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(ub.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=lb.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new mb(tv.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Mv(this,ub.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(hb.REJOIN,e);return!!t&&(this.connectionState=lb.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(_b.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(_b.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(_b.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(_b.MUTE_AUDIO,{uid:e.uid}):this.emit(_b.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(_b.MUTE_VIDEO,{uid:e.uid}):this.emit(_b.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(_b.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(_b.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(_b.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(_b.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(_b.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){Jy.debug("[".concat(this.clientId,"] receive notification: "),e);const t=uw(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(vv.UID_BANNED),void this.close()):void this.reconnect(t.action,Ov.SERVER_ERROR);Jy.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=Oy("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(Jy.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>Oy("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ov.TIMEOUT):this.request(hb.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),Oy("REPORT_STATS")&&this.send(hb.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(pb.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(fb.RECONNECT_WAITTING_FINISH,(e=>{this.emit(ub.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(fb.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(ub.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(fb.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(fb.CLOSED,(()=>{this.connectionState=lb.CLOSED})),this.websocket.on(fb.FAILED,(()=>{this._disconnectedReason=vv.NETWORK_ERROR,this.connectionState=lb.CLOSED})),this.websocket.on(fb.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===lb.CONNECTED?this.connectionState=lb.RECONNECTING:this.connectionState=lb.CONNECTING})),this.websocket.on(fb.WILL_RECONNECT,((e,t,i)=>{const n=Mv(this,ub.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(Jy.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=Mb.P2P_DISCONNECTED),r&&(Jy.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(ub.REPORT_JOIN_GATEWAY,t||Mb.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(ub.DISCONNECT_P2P)),i(e)})),this.websocket.on(fb.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{Jy.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Ov.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(ub.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof mb){if(e.code===tv.UNEXPECTED_RESPONSE&&e.data.code===db.ERR_NO_AUTHORIZED)return this.initError=new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,"AgoraRTCError CAN_NOT_GET_GATEWAY_SERVER: dynamic key expired"),Jy.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Ov.SERVER_ERROR);Jy.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ov.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(fb.REQUEST_NEW_URLS,((e,t)=>{Pv(this,ub.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(fb.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(_b.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on($b.PRE_CONNECT_PC,(()=>{this.emit(ub.PRE_CONNECT_PC)}))}}let bw=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}({});function ww(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ow(e){for(var t=1;t{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}}));const i=Oy("GATEWAY_DOMAINS");let n=i[1]&&Dn(t).call(t,i[1])?1:0;return e.map((e=>{let{domain_prefix:t,port:r,ip:o}=e;if(t)return{address:"".concat(t,".").concat(i[n++%i.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(r):"".concat(o,":").concat(r);return s||Jy.info("Unidentified as ip: ".concat(o,", use as host")),{ip:o,port:r,address:a}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function Mw(e,t){let i,n,r;switch(t){case bw.CHOOSE_SERVER:n=4096,r="choose server";break;case bw.CLOUD_PROXY:n=1048576,r="proxy";break;case bw.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case bw.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new mb(tv.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>Ow(Ow({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:Ow(Ow({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new mb(tv.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function Uw(e,t){return await Gh.all(e.addresses.map((async e=>({address:Nw(e.ip),tcpport:e.port,udpport:e.port,username:t&&Oy("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():sA.username,password:t&&Oy("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await fv(t.toString()):sA.password}))))}function xw(e,t){const i=t.getMediaStreamTrack(!0).getSettings(),n=t.videoHeight||i.height,r=t.videoWidth||i.width;return n&&r?Math.max(Math.min(n,r)/Math.min(Pw(e.height),Pw(e.width)),1):(Jy.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function Vw(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:o,protocol:s}=e;return"local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:s}:{candidateType:t,relayProtocol:i,address:r,port:o,protocol:s}}var Fw,Bw=i(kA),jw=Xi("Array").values,Gw=pn,Ww=Ze,Hw=l,Kw=jw,Yw=Array.prototype,qw={DOMTokenList:!0,NodeList:!0},zw=function(e){var t=e.values;return e===Yw||Hw(Yw,e)&&t===Yw.values||Ww(qw,Gw(e))?Kw:t},Jw=i(zw),Xw=N,Qw=d,Zw=L,$w=n,eO=eo,tO=Br,iO=k,nO=Je,rO=K,oO=Object.assign,sO=Object.defineProperty,aO=Qw([].concat),cO=!oO||$w((function(){if(Xw&&1!==oO({b:1},oO(sO({},"a",{enumerable:!0,get:function(){sO(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach((function(e){t[e]=e})),7!=oO({},e)[i]||eO(oO({},t)).join("")!=n}))?function(e,t){for(var i=nO(e),n=arguments.length,r=1,o=tO.f,s=iO.f;n>r;)for(var a,c=rO(arguments[r++]),d=o?aO(eO(c),o(c)):eO(c),l=d.length,u=0;l>u;)a=d[u++],Xw&&!Zw(s,c,a)||(i[a]=c[a]);return i}:oO,dO=ii,lO=rs,uO=Xt,hO=L,pO=Je,_O=function(e,t,i,n){try{return n?t(dO(i)[0],i[1]):t(i)}catch(t){lO(e,"throw",t)}},EO=jo,fO=jc,mO=Gi,TO=E_,SO=es,gO=qo,RO=Array,CO=d,IO=2147483647,vO=/[^\0-\u007E]/,yO=/[.\u3002\uFF0E\uFF61]/g,AO="Overflow: input needs wider integers to process",bO=RangeError,wO=CO(yO.exec),OO=Math.floor,NO=String.fromCharCode,DO=CO("".charCodeAt),PO=CO([].join),LO=CO([].push),kO=CO("".replace),MO=CO("".split),UO=CO("".toLowerCase),xO=function(e){return e+22+75*(e<26)},VO=function(e,t,i){var n=0;for(e=i?OO(e/700):e>>1,e+=OO(e/t);e>455;)e=OO(e/35),n+=36;return OO(n+36*e/(e+38))},FO=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=o&&nOO((IO-s)/u))throw bO(AO);for(s+=(l-o)*u,o=l,i=0;iIO)throw bO(AO);if(n==o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,f=36-_;LO(t,NO(xO(_+E%f))),h=OO(E/f),p+=36}LO(t,NO(xO(h))),a=VO(s,u,d==c),s=0,d++}}s++,o++}return PO(t,"")},BO=wi,jO=N,GO=sg,WO=h,HO=Xt,KO=d,YO=ha,qO=hc,zO=Sc,JO=Ze,XO=cO,QO=function(e){var t=pO(e),i=fO(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=uO(r,n>2?arguments[2]:void 0));var s,a,c,d,l,u,h=gO(t),p=0;if(!h||this===RO&&EO(h))for(s=mO(t),a=i?new this(s):RO(s);s>p;p++)u=o?r(t[p],p):t[p],TO(a,p,u);else for(l=(d=SO(t,h)).next,a=i?new this:[];!(c=hO(l,d)).done;p++)u=o?_O(d,r,[c.value,p],!0):c.value,TO(a,p,u);return a.length=p,a},ZO=R_,$O=Ch.codeAt,eN=function(e){var t,i,n=[],r=MO(kO(UO(e),yO,"."),".");for(t=0;t?@[\\\]^|]/,VN=/[\0\t\n\r #/:<>?@[\\\]^|]/,FN=/^[\u0000-\u0020]+/,BN=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,jN=/[\t\n\r]/g,GN=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)AN(t,e%256),e=pN(e/256);return mN(t,".")}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=TN(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},WN={},HN=XO({},WN,{" ":1,'"':1,"<":1,">":1,"`":1}),KN=XO({},HN,{"#":1,"?":1,"{":1,"}":1}),YN=XO({},KN,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),qN=function(e,t){var i=$O(e,0);return i>32&&i<127&&!JO(t,e)?e:encodeURIComponent(e)},zN={ftp:21,file:null,http:80,https:443,ws:80,wss:443},JN=function(e,t){var i;return 2==e.length&&fN(NN,EN(e,0))&&(":"==(i=EN(e,1))||!t&&"|"==i)},XN=function(e){var t;return e.length>1&&JN(vN(e,0,2))&&(2==e.length||"/"===(t=EN(e,2))||"\\"===t||"?"===t||"#"===t)},QN=function(e){return"."===e||"%2e"===yN(e)},ZN={},$N={},eD={},tD={},iD={},nD={},rD={},oD={},sD={},aD={},cD={},dD={},lD={},uD={},hD={},pD={},_D={},ED={},fD={},mD={},TD={},SD=function(e,t,i){var n,r,o,s=tN(e);if(t){if(r=this.parse(s))throw uN(r);this.searchParams=null}else{if(void 0!==i&&(n=new SD(i,!0)),r=this.parse(s,null,n))throw uN(r);(o=dN(new cN)).bindURL(this),this.searchParams=o}};SD.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,d=t||ZN,l=0,u="",h=!1,p=!1,_=!1;for(e=tN(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=RN(e,FN,""),e=RN(e,BN,"$1")),e=RN(e,jN,""),n=QO(e);l<=n.length;){switch(r=n[l],d){case ZN:if(!r||!fN(NN,r)){if(t)return bN;d=eD;continue}u+=yN(r),d=$N;break;case $N:if(r&&(fN(DN,r)||"+"==r||"-"==r||"."==r))u+=yN(r);else{if(":"!=r){if(t)return bN;u="",d=eD,l=0;continue}if(t&&(c.isSpecial()!=JO(zN,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&zN[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=uD:c.isSpecial()&&i&&i.scheme==c.scheme?d=tD:c.isSpecial()?d=oD:"/"==n[l+1]?(d=iD,l++):(c.cannotBeABaseURL=!0,gN(c.path,""),d=fD)}break;case eD:if(!i||i.cannotBeABaseURL&&"#"!=r)return bN;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=ZO(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=TD;break}d="file"==i.scheme?uD:nD;continue;case tD:if("/"!=r||"/"!=n[l+1]){d=nD;continue}d=sD,l++;break;case iD:if("/"==r){d=aD;break}d=ED;continue;case nD:if(c.scheme=i.scheme,r==Fw)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ZO(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=rD;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ZO(i.path),c.query="",d=mD;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ZO(i.path),c.path.length--,d=ED;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ZO(i.path),c.query=i.query,c.fragment="",d=TD}break;case rD:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=ED;continue}d=aD}else d=sD;break;case oD:if(d=sD,"/"!=r||"/"!=EN(u,l+1))continue;l++;break;case sD:if("/"!=r&&"\\"!=r){d=aD;continue}break;case aD:if("@"==r){h&&(u="%40"+u),h=!0,o=QO(u);for(var E=0;E65535)return ON;c.port=c.isSpecial()&&T===zN[c.scheme]?null:T,u=""}if(t)return;d=_D;continue}return ON}u+=r;break;case uD:if(c.scheme="file","/"==r||"\\"==r)d=hD;else{if(!i||"file"!=i.scheme){d=ED;continue}if(r==Fw)c.host=i.host,c.path=ZO(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=ZO(i.path),c.query="",d=mD;else{if("#"!=r){XN(mN(ZO(n,l),""))||(c.host=i.host,c.path=ZO(i.path),c.shortenPath()),d=ED;continue}c.host=i.host,c.path=ZO(i.path),c.query=i.query,c.fragment="",d=TD}}break;case hD:if("/"==r||"\\"==r){d=pD;break}i&&"file"==i.scheme&&!XN(mN(ZO(n,l),""))&&(JN(i.path[0],!0)?gN(c.path,i.path[0]):c.host=i.host),d=ED;continue;case pD:if(r==Fw||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&JN(u))d=ED;else if(""==u){if(c.host="",t)return;d=_D}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",d=_D}continue}u+=r;break;case _D:if(c.isSpecial()){if(d=ED,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=Fw&&(d=ED,"/"!=r))continue}else c.fragment="",d=TD;else c.query="",d=mD;break;case ED:if(r==Fw||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=yN(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||gN(c.path,"")):QN(u)?"/"==r||"\\"==r&&c.isSpecial()||gN(c.path,""):("file"==c.scheme&&!c.path.length&&JN(u)&&(c.host&&(c.host=""),u=EN(u,0)+":"),gN(c.path,u)),u="","file"==c.scheme&&(r==Fw||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)CN(c.path);"?"==r?(c.query="",d=mD):"#"==r&&(c.fragment="",d=TD)}else u+=qN(r,KN);break;case fD:"?"==r?(c.query="",d=mD):"#"==r?(c.fragment="",d=TD):r!=Fw&&(c.path[0]+=qN(r,WN));break;case mD:t||"#"!=r?r!=Fw&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":qN(r,WN)):(c.fragment="",d=TD);break;case TD:r!=Fw&&(c.fragment+=qN(r,HN))}l++}},parseHost:function(e){var t,i,n;if("["==EN(e,0)){if("]"!=EN(e,e.length-1))return wN;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return EN(e,u)};if(":"==h()){if(":"!=EN(e,1))return;u+=2,l=++d}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&fN(UN,h());)t=16*t+hN(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++}if(!fN(PN,h()))return;for(;fN(PN,h());){if(o=hN(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[d]=256*c[d]+r,2!=++n&&4!=n||d++}if(4!=n)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[d++]=t}else{if(null!==l)return;u++,l=++d}}if(null!==l)for(s=d-l,d=7;0!=d&&s>0;)a=c[d],c[d--]=c[l+s-1],c[l+--s]=a;else if(8!=d)return;return c}(vN(e,1,-1)),!t)return wN;this.host=t}else if(this.isSpecial()){if(e=eN(e),fN(xN,e))return wN;if(t=function(e){var t,i,n,r,o,s,a,c=IN(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&"0"==EN(r,0)&&(o=fN(LN,r)?16:8,r=vN(r,8==o?1:2)),""===r)s=0;else{if(!fN(10==o?MN:8==o?kN:UN,r))return e;s=hN(r,o)}gN(i,s)}for(n=0;n=_N(256,5-t))return null}else if(s>255)return null;for(a=SN(i),n=0;n1?arguments[1]:void 0,n=sN(t,new SD(e,!1,i));jO||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},RD=gD.prototype,CD=function(e,t){return{get:function(){return aN(this)[e]()},set:t&&function(e){return aN(this)[t](e)},configurable:!0,enumerable:!0}};if(jO&&(qO(RD,"href",CD("serialize","setHref")),qO(RD,"origin",CD("getOrigin")),qO(RD,"protocol",CD("getProtocol","setProtocol")),qO(RD,"username",CD("getUsername","setUsername")),qO(RD,"password",CD("getPassword","setPassword")),qO(RD,"host",CD("getHost","setHost")),qO(RD,"hostname",CD("getHostname","setHostname")),qO(RD,"port",CD("getPort","setPort")),qO(RD,"pathname",CD("getPathname","setPathname")),qO(RD,"search",CD("getSearch","setSearch")),qO(RD,"searchParams",CD("getSearchParams")),qO(RD,"hash",CD("getHash","setHash"))),YO(RD,"toJSON",(function(){return aN(this).serialize()}),{enumerable:!0}),YO(RD,"toString",(function(){return aN(this).serialize()}),{enumerable:!0}),lN){var ID=lN.createObjectURL,vD=lN.revokeObjectURL;ID&&YO(gD,"createObjectURL",HO(ID,lN)),vD&&YO(gD,"revokeObjectURL",HO(vD,lN))}iN(gD,"URL"),BO({global:!0,constructor:!0,forced:!GO,sham:!jO},{URL:gD});var yD=wi,AD=n,bD=Zc,wD=fn,OD=sg,ND=ae("URL");yD({target:"URL",stat:!0,forced:!(OD&&AD((function(){ND.canParse()})))},{canParse:function(e){var t=bD(arguments.length,1),i=wD(e),n=t<2||void 0===arguments[1]?void 0:wD(arguments[1]);try{return!!new ND(i,n)}catch(e){return!1}}});var DD=i(ie.URL);const PD={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function LD(){return PD}function kD(){return"setSinkId"in HTMLAudioElement.prototype&&(!Oy("RESTRICTION_SET_PLAYBACK_DEVICE")||(OI()||DI())&&!zI())}function MD(){return!PD.supportUnifiedPlan||Oy("CHROME_FORCE_PLAN_B")&&JI()}let UD=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function xD(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function VD(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function FD(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function BD(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const jD={"90p":VD(160,90),"90p_1":VD(160,90),"120p":VD(160,120,15,30,65),"120p_1":VD(160,120,15,30,65),"120p_3":VD(120,120,15,30,50),"120p_4":VD(212,120),"180p":VD(320,180,15,30,140),"180p_1":VD(320,180,15,30,140),"180p_3":VD(180,180,15,30,100),"180p_4":VD(240,180,15,30,120),"240p":VD(320,240,15,40,200),"240p_1":VD(320,240,15,40,200),"240p_3":VD(240,240,15,40,140),"240p_4":VD(424,240,15,40,220),"360p":VD(640,360,15,80,400),"360p_1":VD(640,360,15,80,400),"360p_3":VD(360,360,15,80,260),"360p_4":VD(640,360,30,80,600),"360p_6":VD(360,360,30,80,400),"360p_7":VD(480,360,15,80,320),"360p_8":VD(480,360,30,80,490),"360p_9":VD(640,360,15,80,800),"360p_10":VD(640,360,24,80,800),"360p_11":VD(640,360,24,80,1e3),"480p":VD(640,480,15,100,500),"480p_1":VD(640,480,15,100,500),"480p_2":VD(640,480,30,100,1e3),"480p_3":VD(480,480,15,100,400),"480p_4":VD(640,480,30,100,750),"480p_6":VD(480,480,30,100,600),"480p_8":VD(848,480,15,100,610),"480p_9":VD(848,480,30,100,930),"480p_10":VD(640,480,10,100,400),"720p":VD(1280,720,15,120,1130),"720p_auto":VD(1280,720,30,900,3e3),"720p_1":VD(1280,720,15,120,1130),"720p_2":VD(1280,720,30,120,2e3),"720p_3":VD(1280,720,30,120,1710),"720p_5":VD(960,720,15,120,910),"720p_6":VD(960,720,30,120,1380),"1080p":VD(1920,1080,15,120,2080),"1080p_1":VD(1920,1080,15,120,2080),"1080p_2":VD(1920,1080,30,120,3e3),"1080p_3":VD(1920,1080,30,120,3150),"1080p_5":VD(1920,1080,60,120,4780),"1440p":VD(2560,1440,30,120,4850),"1440p_1":VD(2560,1440,30,120,4850),"1440p_2":VD(2560,1440,60,120,7350),"4k":VD(3840,2160,30,120,8910),"4k_1":VD(3840,2160,30,120,8910),"4k_3":VD(3840,2160,60,120,13500)},GD={"480p":FD(640,480,5),"480p_1":FD(640,480,5),"480p_2":FD(640,480,30),"480p_3":FD(640,480,15),"720p":FD(1280,720,5),"720p_auto":VD(1280,720,30,900,3e3),"720p_1":FD(1280,720,5),"720p_2":FD(1280,720,30),"720p_3":FD(1280,720,15),"1080p":FD(1920,1080,5),"1080p_1":FD(1920,1080,5),"1080p_2":FD(1920,1080,30),"1080p_3":FD(1920,1080,15)},WD={"1SL1TL":BD(1,1),"3SL3TL":BD(3,3),"2SL3TL":BD(2,3)};function HD(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},jD[e]):e}function KD(e){return"string"==typeof e?Object.assign({},GD[e]):e}function YD(e){return"string"==typeof e?Object.assign({},WD[e]):e}const qD={speech_low_quality:xD(16e3,!1),speech_standard:xD(32e3,!1,18),music_standard:xD(48e3,!1),standard_stereo:xD(48e3,!0,56),high_quality:xD(48e3,!1,128),high_quality_stereo:xD(48e3,!0,192)};function zD(e){return"string"==typeof e?Object.assign({},qD[e]):e}const JD=[];function XD(e){return rv(e,"mediaSource",["screen","window","application"]),!0}let QD=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),ZD=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e}({});let $D=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),eP=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),tP=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e}({}),iP=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),nP=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),rP=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e}({}),oP=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),sP=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({});!function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}({});const aP={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},cP={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},dP={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},lP={uplinkNetworkQuality:0,downlinkNetworkQuality:0},uP={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let hP=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),pP=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),_P=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),EP=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),fP=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),mP=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const TP={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let SP=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function gP(e,t,i,n,r){var o,s,a={};return Object.keys(n).forEach((function(e){a[e]=n[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=Jn(o=Bw(s=i.slice()).call(s)).call(o,(function(i,n){return n(e,t,i)||i}),a),r&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}function RP(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function CP(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function IP(e){for(var t=1;t{var e;rA.reportApiInvoke(null,{name:gv.GET_MEDIA_STREAM_TRACK,options:[],tag:Rv.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===$D.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=JD.indexOf(e);-1!==t&&JD.splice(t,1)}(this),this.emit(nP.CLOSED),this.removeAllListeners(iP.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===$D.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(iP.TRANSCEIVER_UPDATED,e,t)}}class yP extends vP{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),RP(this,"_enabled",!0),RP(this,"_muted",!1),RP(this,"_isExternalTrack",!1),RP(this,"_isClosed",!1),RP(this,"_enabledMutex",void 0),RP(this,"processor",void 0),RP(this,"_processorContext",void 0),RP(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new ly("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,Jy.debug("[".concat(this.getTrackId(),"] close")),this.emit(QD.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Lv(this,QD.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){Jy.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(nP.TRACK_ENDED)}stateCheck(e,t){if(Jy.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),nv(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new iv(tv.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",Jy);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new iv(tv.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",Jy)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Gh.resolve([])}}const AP=window.AudioContext||window.webkitAudioContext;let bP=null;const wP=new class extends mv{constructor(){super(...arguments),RP(this,"prevState",void 0),RP(this,"curState",void 0),RP(this,"currentTime",void 0),RP(this,"currentTimeStuckAt",void 0),RP(this,"interruptDetectorTrack",void 0),RP(this,"onLocalAudioTrackMute",(()=>{Jy.info("ios15-interruption-start"),this.emit(UD.IOS_15_16_INTERRUPTION_START)})),RP(this,"onLocalAudioTrackUnmute",(async()=>{Jy.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?Jy.info("ios15-interruption-end-canceled"):(bP&&await bP.suspend(),this.emit(UD.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){Jy.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){Jy.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function OP(){if(!bP){if(function(){if(!AP)return void Jy.error("your browser is not support web audio");Jy.info("create audio context");const e=IP({},Oy("WEBAUDIO_INIT_OPTIONS"));Jy.debug("audio context init option:",JSON.stringify(e)),bP=new AP(e),wP.curState=bP.state,bP.onstatechange=()=>{wP.prevState=wP.curState,wP.curState=bP?bP.state:void 0;const{prevState:e,curState:t}=wP,i="running"===t,n="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=vI().osVersion;(LI()||KI())&&r&&n&&(Jy.info("ios".concat(a,"-interruption-start")),wP.emit(UD.IOS_INTERRUPTION_START)),(LI()||KI())&&(o||s)&&i&&(Jy.info("ios".concat(a,"-interruption-end")),wP.emit(UD.IOS_INTERRUPTION_END)),e!==t&&wP.emit(UD.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=bP)||void 0===e?void 0:e.currentTime;wP.currentTime!==t?(wP.currentTimeStuckAt&&(Jy.debug("AudioContext current time resume at ".concat(t)),wP.currentTimeStuckAt=void 0),wP.currentTime=t):(t!==wP.currentTimeStuckAt&&(rA.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:Rv.TRACER}).onSuccess(),Jy.warning("AudioContext current time stuck at ".concat(t))),wP.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,o=!1;function s(t){"running"===e.state?a(!1):LI()||KI()?"suspended"===e.state&&(a(!0),t&&e.resume().then(c,c)):"closed"!==e.state&&(a(!0),t&&e.resume().then(c,c))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,l(!0)}wP.on(UD.STATE_CHANGE,(function(){s(!0)})),s(!1)}(bP)}(),!bP)throw new iv(tv.NOT_SUPPORTED,"can not create audio context");return bP}return bP}function NP(e){if(function(){if(null!==DP)return DP;const e=OP(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),DP=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Dn(o=e._inputNodes).call(o,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,o)=>{i.call(e),n?xv(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let DP=null;function PP(e,t){let i=!1;const n=1/t;if(Oy("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=OP();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(i)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+n),e(t.currentTime)};o()}return()=>{i=!0}}class LP{constructor(){RP(this,"context",void 0),RP(this,"analyserNode",void 0),RP(this,"sourceNode",void 0),this.context=OP(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||LI()||KI()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;ie+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){Jy.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class kP extends mv{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),RP(this,"outputNode",void 0),RP(this,"outputTrack",void 0),RP(this,"isPlayed",!1),RP(this,"sourceNode",void 0),RP(this,"context",void 0),RP(this,"audioBufferNode",void 0),RP(this,"destNode",void 0),RP(this,"audioOutputLevel",0),RP(this,"volumeLevelAnalyser",void 0),RP(this,"_processedNode",void 0),RP(this,"playNode",void 0),RP(this,"isDestroyed",!1),RP(this,"onNoAudioInput",void 0),RP(this,"isNoAudioInput",!1),RP(this,"_noAudioInputCount",0),this.context=OP(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),NP(this.outputNode),this.volumeLevelAnalyser=new LP}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(sP.ON_AUDIO_BUFFER,function(e){for(let t=0;t{wP.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;LI()||KI()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e{if(Jy.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void Jy.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>Jy.info("resume success"))),Jy.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),NP(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),NP(this.outputNode),this.emit(sP.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new iv(tv.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),NP(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,Jy.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));NP(t),this.originVolumeLevelAnalyser=new LP,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=vI();t&&o.os===SI.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(wP.on(UD.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),NP(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(sP.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),wP.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),Jy.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));NP(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function UP(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function xP(e,t){const i=await VP(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Gh(((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e)};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(o),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='
'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await UP(n,e,r)}async function VP(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=Sv();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new iv(tv.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new Gh(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new iv(tv.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const FP=new ly("safari");let BP=!1,jP=!1;async function GP(e,t){let i=0,n=null;for(;i<2;)try{n=await WP(e,t,i>0);break}catch(e){if(e instanceof iv)throw Jy.error("[".concat(t,"] ").concat(e.toString())),e;const n=HP(e.name||e.code||e,e.message);if(n.code===tv.MEDIA_OPTION_INVALID){Jy.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await Qv(500);continue}throw Jy.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new iv(tv.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function WP(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new iv(tv.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=LD(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return Jy.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(Sv())e.screen.sourceId?KP(r,await UP(e.screen.sourceId,e.screen,e.screenAudio)):KP(r,await xP(e.screen,e.screenAudio));else if(OI()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new iv(tv.NOT_SUPPORTED,"This browser does not support screen sharing");Jy.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(s=e.screen.extensionId,a=t,new Gh(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(i=>{if(!i||!i.streamId)return Jy.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new iv(tv.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){Jy.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new iv(tv.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,KP(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&XD(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a};!n&&delete c.selfBrowserSurface,!s&&delete c.surfaceSwitching,!a&&delete c.systemAudio,Jy.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c})),KP(r,await navigator.mediaDevices.getDisplayMedia(IP({video:i,audio:!!e.screenAudio},c)))}else{if(!PI())throw Jy.error("[".concat(t,"] This browser does not support screenSharing")),new iv(tv.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&XD(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};Jy.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),KP(r,await navigator.mediaDevices.getUserMedia(i))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=Oy("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=ry(c,d)}catch(e){}Jy.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),vI();let l,u=null;(NI()||LI()||wI())&&(u=await FP.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(BP=!0),c.video&&(jP=!0),KP(r,l),u&&u(),r}function HP(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new iv(tv.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new iv(tv.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new iv(tv.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new iv(tv.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new iv(tv.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new iv(tv.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return Jy.error("getUserMedia unexpected error",e),new iv(tv.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function KP(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(n&&e.removeTrack(n),e.addTrack(o)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const YP=new class extends mv{get state(){return this._state}set state(e){e!==this._state&&(this.emit(EP.STATE_CHANGE,e),this._state=e)}constructor(){super(),RP(this,"_state",_P.IDLE),RP(this,"isAccessMicrophonePermission",!1),RP(this,"isAccessCameraPermission",!1),RP(this,"lastAccessMicrophonePermission",!1),RP(this,"lastAccessCameraPermission",!1),RP(this,"checkdeviceMatched",!1),RP(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(Oy("ENUMERATE_DEVICES_INTERVAL")||(XI()||AI()===SI.HARMONY_OS)&&JI())&&this.updateDevicesInfo()}),Oy("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>Jy.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new iv(tv.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!i&&(o||s)){if(FP.isLocked&&(Jy.debug("[device manager] wait GUM lock"),(await FP.lock())(),Jy.debug("[device manager] GUM unlock")),BP&&(o=!1,this.isAccessMicrophonePermission=!0),jP&&(s=!1,this.isAccessCameraPermission=!0),Jy.debug("[device manager] check media device permissions",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=HP(e.name||e.code||e,e.message);if(t.code===tv.PERMISSION_DENIED)throw t;Jy.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=HP(e.name||e.code||e,e.message);if(t.code===tv.PERMISSION_DENIED)throw t;Jy.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=HP(e.name||e.code||e,e.message);if(t.code===tv.PERMISSION_DENIED)throw t;Jy.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}Jy.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new iv(tv.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new iv(tv.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=_P.INITING;try{await this.updateDevicesInfo(),this.state=_P.INITEND}catch(e){throw Jy.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=_P.IDLE,("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)||new iv(tv.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?Jy.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):Jy.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):Jy.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==_P.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(EP.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(EP.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(EP.PLAYOUT_DEVICE_CHANGED,e)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let qP=!1;const zP=new class extends mv{constructor(){super(...arguments),RP(this,"onAutoplayFailed",void 0),RP(this,"onAudioAutoplayFailed",void 0)}};function JP(){if(vI(),!qP){const e=t=>{t.preventDefault(),qP=!1,QI()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};qP=!0,QI()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),Jy.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),zP.onAutoplayFailed?zP.onAutoplayFailed():zP.onAudioAutoplayFailed?Jy.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):Jy.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),zP.emit("autoplay-failed")}}function XP(e,t,i,n){if(!e)return;const r=rA.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=IP(IP({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:zP.onAutoplayFailed||zP.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});rA.send({type:eA.AUTOPLAY_FAILED,data:a},!0)}const QP=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ZP=new class{constructor(){RP(this,"onAutoplayFailed",void 0),RP(this,"elementMap",new Map),RP(this,"elementStateMap",new Map),RP(this,"elementsNeedToResume",[]),RP(this,"sinkIdMap",new Map),RP(this,"autoResumeAfterInterruption",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,n]=t;const r=this.elementStateMap.get(i),o=n.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(Jy.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(e)),"live"===s){if(e)return n.pause(),void n.play();if("running"===wP.curState)return GI()?(n.pause(),void n.play()):void(r&&"paused"===r&&n.play())}}))})),RP(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(Jy.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),wP.on(UD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wP.on(UD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),wP.on(UD.STATE_CHANGE,(()=>{LI()&&"suspended"===wP.prevState&&"running"===wP.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new iv(tv.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,fP.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{Jy.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){Jy.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{n&&XP(n,"audio",e.message,t),Jy.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(Jy.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),Fv((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),JP()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){QP.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(Jy.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&Jy.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{Jy.debug("Auto resume audio element success")})).catch((e=>{Jy.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new Gh((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{QI()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function $P(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new iv(tv.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",Jy);for(var e=arguments.length,t=new Array(e),i=0;i{r.then(e).catch(t)})):r}),i}}class eL extends mv{constructor(e){super(),RP(this,"name","VideoProcessorDestination"),RP(this,"ID","0"),RP(this,"_source",void 0),RP(this,"videoContext",void 0),RP(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new iv(tv.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new iv(tv.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(hP.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(hP.ON_TRACK,void 0)}}class tL extends mv{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),RP(this,"constraintsMap",new Map),RP(this,"statsRegistry",[]),RP(this,"usageRegistry",[]),RP(this,"trackId",void 0),RP(this,"direction",void 0),RP(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await Pv(this,pP.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return Jy.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),Lv(this,pP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Jw(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return Jy.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),Lv(this,pP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Jw(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){Jy.error(new iv(tv.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Gh&&(i=await i),e.push(IP(IP({},i),{},{direction:this.direction}))}catch(e){Jy.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class iL extends mv{constructor(e){super(),RP(this,"name","AudioProcessorDestination"),RP(this,"ID","0"),RP(this,"inputTrack",void 0),RP(this,"inputNode",void 0),RP(this,"audioProcessorContext",void 0),RP(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new iv(tv.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new iv(tv.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(hP.ON_TRACK,void 0),this.emit(hP.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(hP.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(hP.ON_NODE,this.inputNode))}}class nL extends mv{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),RP(this,"constraintsMap",new Map),RP(this,"statsRegistry",[]),RP(this,"audioContext",void 0),RP(this,"trackId",void 0),RP(this,"direction",void 0),RP(this,"usageRegistry",[]),RP(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return Pv(this,pP.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return Jy.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),Lv(this,pP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Jw(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),Lv(this,pP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Jw(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){Jy.error(new iv(tv.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Gh&&(i=await i),e.push(IP(IP({},i),{},{direction:this.direction}))}catch(e){Jy.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class rL extends mv{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),RP(this,"context",void 0),RP(this,"processSourceNode",void 0),RP(this,"outputTrack",void 0),RP(this,"processedNode",void 0),RP(this,"clonedTrack",void 0),RP(this,"outputNode",void 0),this.outputNode=new oL}setVolume(){}createOutputTrack(){throw new iv(tv.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class oL{disconnect(){}connect(){}}function sL(e){return new Gh(((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=LI()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&PI()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(ey),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function aL(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=HD(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!qI()&&i.frameRate&&(t.frameRate=i.frameRate),DI()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),PI()&&(t.frameRate={ideal:30,max:30}),t}function cL(e){const t={};if(qI()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,OI()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=zD(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),XI()&&(t.sampleRate=void 0),t}const dL=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:i,width:n,height:r}=e.getMediaStreamTrackSettings();let{frameRate:o=i,width:s=n,height:a=r}=t;if(!o||!s||!a)return;s=sy(s),a=sy(a),o=sy(o);const{max:c,min:d}=function(e,t,i){const n=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(n),max:Math.floor(4*n)}}(s,a,o),{bitrateMax:l,bitrateMin:u}=t||{};l||Jy.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(u,"]"));const{maxFramerate:h}=Oy("ENCODER_CONFIG_LIMIT");return h&&"number"==typeof h&&(o=Math.min(o,h)),{frameRate:o,bitrateMax:l||c,bitrateMin:u||d,scaleResolutionDownBy:1,scale:0}},lL=async(e,t,i)=>await(async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i{const t=document.createElement("canvas");return t.width=2,t.height=2,new Gh(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await hL(e);i({buffer:n,width:t.width,height:t.height})}else n(new iv(tv.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},hL=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var pL,_L,EL,fL,mL,TL,SL,gL,RL,CL,IL,vL,yL,AL,bL,wL,OL,NL,DL,PL,LL,kL,ML,UL,xL,VL,FL,BL,jL,GL,WL,HL,KL,YL,qL,zL,JL,XL,QL,ZL;let $L=(pL=nA({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),_L=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),EL=$P(),fL=uy("LocalAudioTrack","_enabledMutex"),mL=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),TL=$P(),SL=uy("LocalAudioTrack","_enabledMutex"),gL=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),RL=$P(),CL=$P(),IL=$P(),vL=nA({argsMap:e=>[e.getTrackId()]}),yL=$P(),AL=nA({argsMap:e=>[e.getTrackId()]}),bL=$P(),wL=nA({argsMap:e=>[e.getTrackId()]}),OL=nA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),NL=nA({argsMap:e=>[e.getTrackId()]}),gP((DL=class extends yP{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?ZP.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n){super(e,i),RP(this,"trackMediaType",oP.AUDIO),RP(this,"_encoderConfig",void 0),RP(this,"_trackSource",void 0),RP(this,"_enabled",!0),RP(this,"_volume",100),RP(this,"_useAudioElement",!0),RP(this,"_bypassWebAudio",!1),RP(this,"processor",void 0),RP(this,"_processorContext",void 0),RP(this,"_processorDestination",void 0),RP(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new rL,Oy("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),Oy("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),NI()&&!bP?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){ov(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&ZP.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void Jy.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,Lv(this,QD.NEED_REPLACE_TRACK,this).then((()=>{Jy.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{Jy.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!kD())throw new iv(tv.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ZP.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(Jy.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await Lv(this,QD.NEED_ENABLE_TRACK,this),Jy.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),Jy.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await Lv(this,QD.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),Jy.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,Jy.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await Lv(this,QD.NEED_MUTE_TRACK,this):await Lv(this,QD.NEED_UNMUTE_TRACK,this))}getStats(){Wv((()=>{Jy.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return kv(this,QD.GET_STATS)||IP({},aP)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(sP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(sP.ON_AUDIO_BUFFER),this._source.on(sP.ON_AUDIO_BUFFER,(t=>e(t)))}play(){Jy.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(Jy.debug("[".concat(this.getTrackId(),"] start audio playback in element")),ZP.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){Jy.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?ZP.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Jy.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ZP.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Lv(this,QD.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Gh.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new iv(tv.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new iv(tv.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(hP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await Lv(this,QD.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Lv(this,QD.NEED_REPLACE_TRACK,this))})),e.on(hP.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(hP.ON_TRACK),e.removeAllListeners(hP.ON_NODE)}bindProcessorContextEvents(e){e.on(pP.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(pP.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof rL&&(this._trackSource=new MP(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new nL(this._source.context,this.getTrackId(),"local"),t=new iL(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(sP.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(ZP.stop(this.getTrackId()),this._source.play()),Lv(this,QD.NEED_REPLACE_MIXING_TRACK,this).then((()=>{Jy.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{Jy.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[pL],Object.getOwnPropertyDescriptor(DL.prototype,"setVolume"),DL.prototype),gP(DL.prototype,"setPlaybackDevice",[_L,EL],Object.getOwnPropertyDescriptor(DL.prototype,"setPlaybackDevice"),DL.prototype),gP(DL.prototype,"setEnabled",[fL,mL,TL],Object.getOwnPropertyDescriptor(DL.prototype,"setEnabled"),DL.prototype),gP(DL.prototype,"setMuted",[SL,gL,RL],Object.getOwnPropertyDescriptor(DL.prototype,"setMuted"),DL.prototype),gP(DL.prototype,"getStats",[CL],Object.getOwnPropertyDescriptor(DL.prototype,"getStats"),DL.prototype),gP(DL.prototype,"setAudioFrameCallback",[IL],Object.getOwnPropertyDescriptor(DL.prototype,"setAudioFrameCallback"),DL.prototype),gP(DL.prototype,"play",[vL,yL],Object.getOwnPropertyDescriptor(DL.prototype,"play"),DL.prototype),gP(DL.prototype,"stop",[AL,bL],Object.getOwnPropertyDescriptor(DL.prototype,"stop"),DL.prototype),gP(DL.prototype,"close",[wL],Object.getOwnPropertyDescriptor(DL.prototype,"close"),DL.prototype),gP(DL.prototype,"pipe",[OL],Object.getOwnPropertyDescriptor(DL.prototype,"pipe"),DL.prototype),gP(DL.prototype,"unpipe",[NL],Object.getOwnPropertyDescriptor(DL.prototype,"unpipe"),DL.prototype),DL),ek=(PL=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),LL=$P(),kL=uy("MicrophoneAudioTrack","_enabledMutex"),ML=nA({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),UL=$P(),xL=nA({argsMap:e=>[e.getTrackId()]}),gP((VL=class extends $L{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?zD(t.encoderConfig):{},n,Oy("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),RP(this,"_config",void 0),RP(this,"_deviceName","default"),RP(this,"_constraints",void 0),RP(this,"_originalConstraints",void 0),RP(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(GI()||WI())&&wP.bindInterruptDetectorTrack(this)}async setDevice(e){if(Jy.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await YP.getDeviceById(e),i={};i.audio=IP({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await GP(i,this.getTrackId())}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await GP({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await YP.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}Jy.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return Jy.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(Jy.info("[".concat(this.getTrackId(),"] start setEnabled"),e),Oy("AUTO_RESET_AUDIO_ROUTE")&&(LI()||KI())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await Lv(this,QD.NEED_DISABLE_TRACK,this)}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=IP({},this._constraints),o=YP.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await GP({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await Lv(this,QD.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),Jy.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}Jy.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(GI()||WI())&&wP.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((LI()||KI())&&this._enabled&&!this._isClosed&&wP.duringInterruption){const e=async()=>{wP.off(UD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(Jy.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};wP.on(UD.IOS_INTERRUPTION_END,e)}else Jy.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(nP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=YP.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await GP({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(pP.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(pP.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[PL,LL],Object.getOwnPropertyDescriptor(VL.prototype,"setDevice"),VL.prototype),gP(VL.prototype,"setEnabled",[kL,ML,UL],Object.getOwnPropertyDescriptor(VL.prototype,"setEnabled"),VL.prototype),gP(VL.prototype,"close",[xL],Object.getOwnPropertyDescriptor(VL.prototype,"close"),VL.prototype),VL),tk=(FL=nA({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),BL=$P(),jL=nA({argsMap:e=>[e.getTrackId()]}),GL=$P(),WL=nA({argsMap:e=>[e.getTrackId()]}),HL=$P(),KL=nA({argsMap:e=>[e.getTrackId()]}),YL=$P(),qL=nA({argsMap:e=>[e.getTrackId()]}),zL=$P(),JL=nA({argsMap:e=>[e.getTrackId()]}),XL=nA({argsMap:e=>[e.getTrackId()]}),QL=$P(),gP((ZL=class extends $L{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),RP(this,"source",void 0),RP(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(sP.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(nP.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){ov(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[FL,BL],Object.getOwnPropertyDescriptor(ZL.prototype,"startProcessAudioBuffer"),ZL.prototype),gP(ZL.prototype,"pauseProcessAudioBuffer",[jL,GL],Object.getOwnPropertyDescriptor(ZL.prototype,"pauseProcessAudioBuffer"),ZL.prototype),gP(ZL.prototype,"seekAudioBuffer",[WL,HL],Object.getOwnPropertyDescriptor(ZL.prototype,"seekAudioBuffer"),ZL.prototype),gP(ZL.prototype,"resumeProcessAudioBuffer",[KL,YL],Object.getOwnPropertyDescriptor(ZL.prototype,"resumeProcessAudioBuffer"),ZL.prototype),gP(ZL.prototype,"stopProcessAudioBuffer",[qL,zL],Object.getOwnPropertyDescriptor(ZL.prototype,"stopProcessAudioBuffer"),ZL.prototype),gP(ZL.prototype,"close",[JL],Object.getOwnPropertyDescriptor(ZL.prototype,"close"),ZL.prototype),gP(ZL.prototype,"setAudioBufferPlaybackSpeed",[XL,QL],Object.getOwnPropertyDescriptor(ZL.prototype,"setAudioBufferPlaybackSpeed"),ZL.prototype),ZL);class ik extends $L{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=OP().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,Zv(8,"track-mix-")),RP(this,"trackList",void 0),RP(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(Jy.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):Jy.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){Jy.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}xv(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof ik?t.emit(iP.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class nk extends kP{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(sP.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),RP(this,"audioBuffer",void 0),RP(this,"sourceNode",void 0),RP(this,"startPlayTime",0),RP(this,"startPlayOffset",0),RP(this,"pausePlayTime",0),RP(this,"options",void 0),RP(this,"currentLoopCount",0),RP(this,"currentPlaybackSpeed",100),RP(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):Jy.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const rk=new Map;class ok{get rendFrameRate(){if(this.renderStats&&this.renderStats.curTs!==this.renderStats.lastTs){const e=this.renderStats.curTs-this.renderStats.lastTs,t=(this.renderStats.renderNum-this.renderStats.lastRenderNum)/e;return this.renderStats.lastRenderNum=this.renderStats.renderNum,this.renderStats.lastTs=this.renderStats.curTs,t}return 0}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(Jy.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){RP(this,"trackId",void 0),RP(this,"config",void 0),RP(this,"onFirstVideoFrameDecoded",void 0),RP(this,"onVideoStateChanged",void 0),RP(this,"freezeTimeCounterList",[]),RP(this,"renderFreezeAccTime",0),RP(this,"isKeepLastFrame",!1),RP(this,"timeUpdatedCount",0),RP(this,"freezeTime",0),RP(this,"playbackTime",0),RP(this,"lastTimeUpdatedTime",0),RP(this,"autoplayFailed",!1),RP(this,"videoTrack",void 0),RP(this,"videoElement",void 0),RP(this,"cacheVideoElement",void 0),RP(this,"renderStats",void 0),RP(this,"_videoState",mP.VideoStateStopped),RP(this,"videoElementCheckInterval",void 0),RP(this,"videoElementFreezeTimeout",void 0),RP(this,"_videoElementStatus",fP.NONE),RP(this,"isGettingVideoDimensions",!1),RP(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return Jy.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),RP(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===wP.curState&&(Jy.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(bI())),HI()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),RP(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=fP.PLAYING;break;case"loadeddata":if(this.videoState=mP.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=fP.CANPLAY;break;case"stalled":this.videoElementStatus=fP.STALLED;break;case"suspend":this.videoElementStatus=fP.SUSPEND;break;case"pause":this.videoElementStatus=fP.PAUSED,LI()||KI()||NI()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(Jy.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=fP.WAITING;break;case"abort":this.videoElementStatus=fP.ABORT;break;case"ended":this.videoElementStatus=fP.ENDED;break;case"emptied":this.videoElementStatus=fP.EMPTIED;break;case"error":{const e=this.videoElement.error;e?(this.videoElementStatus=fP.ERROR,Jy.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")"))):Jy.debug("[".concat(this.trackId,"] media not been an error."));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,sM.lastVisibleTimeOy("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),RP(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(Jy.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(bI())),HI()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),wP.on(UD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wP.on(UD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&XP(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(Jy.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):Jy.warning("[".concat(this.trackId,"] play warning: "),t)}));const i=vI();if(("Safari"===i.name&&15===Number(i.version)||GI())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return Jy.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new Gh(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await hL(e);n({buffer:t,width:i.width,height:i.height})}else r(new iv(tv.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await uL(e)}destroy(){this.renderStats=void 0,wP.off(UD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wP.off(UD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=mP.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=fP.INIT,!this.videoElementCheckInterval&&(sk.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=fP.DESTROYED)}),1e3),Oy("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,Oy("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===mP.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=mP.VideoStateFrozen:document.addEventListener("visibilitychange",n))},o=(e,t)=>{if(this.videoElementStatus===fP.PLAYING){if(this.renderStats?(this.renderStats.renderNum++,this.renderStats.curTs=t.mediaTime):this.renderStats={lastTs:t.mediaTime,curTs:t.mediaTime,lastRenderNum:0,renderNum:0},i){const e=t.presentationTime-i.presentationTime;this.videoState===mP.VideoStateStarting&&(this.videoState=mP.VideoStateDecoding),this.videoState===mP.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,Oy("VIDEO_FREEZE_DURATION"))),eOy("VIDEO_FREEZE_DURATION")&&sM.lastVisibleTime>=sM.lastHiddenTime&&i.timestamp>sM.lastVisibleTime&&i.timestamp>sM.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=IP(IP({},t),{},{timestamp:e})}var n,s;Oy("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(n=(s=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(s,o))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),XI()&&!Oy("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const i=vI();"Safari"===i.name&&15===Number(i.version)||GI()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,PI()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,PI()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{Jy.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){sk.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=fP.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{Jy.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{Jy.error(e)})),this.autoplayFailed=!1,QI()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};QI()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),JP()}}const sk=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class ak extends ok{constructor(e){super(e),RP(this,"container",void 0),RP(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await uL(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",Oy("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}var ck,dk,lk,uk,hk,pk,_k,Ek,fk,mk,Tk,Sk,gk,Rk,Ck,Ik,vk,yk,Ak,bk,wk,Ok,Nk,Dk,Pk,Lk,kk,Mk,Uk,xk,Vk,Fk,Bk,jk;let Gk=(ck=nA({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),dk=$P(),lk=nA({argsMap:e=>[e.getTrackId()]}),uk=uy("LocalVideoTrack","_enabledMutex"),hk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),pk=$P(),_k=uy("LocalVideoTrack","_enabledMutex"),Ek=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),fk=$P(),mk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),Tk=$P(),Sk=$P(),gk=nA({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Rk=$P(),Ck=$P(),Ik=$P(),vk=$P(),yk=$P(),Ak=$P(),bk=$P(),wk=nA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ok=nA({argsMap:e=>[e.getTrackId()]}),Nk=nA({argsMap:e=>[e.getTrackId()]}),Dk=nA({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),Pk=class e extends yP{get videoHeight(){if(NI()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(NI()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==fP.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,o){if(super(e,r),RP(this,"trackMediaType",oP.VIDEO),RP(this,"_player",void 0),RP(this,"isUseScaleResolutionDownBy",!1),RP(this,"_videoVisibleTimer",null),RP(this,"_previousVideoVisibleStatus",void 0),RP(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),RP(this,"_encoderConfig",void 0),RP(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),RP(this,"_optimizationMode",void 0),RP(this,"_videoHeight",void 0),RP(this,"_videoWidth",void 0),RP(this,"_forceBitrateLimit",void 0),RP(this,"_enabled",!0),RP(this,"_processorDestination",void 0),RP(this,"_processorContext",void 0),NI()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(ZD.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=vI();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}(gI.CHROME,115)&&-1!==AI().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&LD().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,o,s=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),o=void 0,n.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{"live"===n.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(Jy.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(ZD.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new tL(this.getTrackId(),"local"),this._processorDestination=new eL(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(Jy.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}Jy.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=IP(IP(IP({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new ok(i):this._player=new ak(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(nP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),Oy("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,Jy.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(Jy.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await Lv(this,QD.NEED_DISABLE_TRACK,this)}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void Jy.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await Lv(this,QD.NEED_ENABLE_TRACK,this)}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}Jy.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,Jy.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await Lv(this,QD.NEED_MUTE_TRACK,this):await Lv(this,QD.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new iv(tv.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=HD(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=aL({encoderConfig:e});(NI()||LI()||KI())&&(t.deviceId=void 0),Jy.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new iv(tv.UNEXPECTED_ERROR,e.toString());throw Jy.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(ZD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await Lv(this,QD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Jy)}}getStats(){Wv((()=>{Jy.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return kv(this,QD.GET_STATS)||IP({},cP)}async setBeautyEffect(e){Jy.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await uL(e)}async setBitrateLimit(e){if(Jy.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(ey)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new iv(tv.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");Jy.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=HD(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(ZD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await Lv(this,QD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Jy)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:o,min:s}=function(e,t,i,n,r){const o=Oy("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:n,max:r};if(void 0===r){var s;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*a:2*a,n=null!==(s=n)&&void 0!==s?s:a}else{var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10)}return{min:n,max:r}}(e,t,i,r,n);this._encoderConfig.bitrateMin=s,this._encoderConfig.bitrateMax=o,Jy.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(s,"]"))}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=pv.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new iv(tv.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new iv(tv.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=IP(IP({},n),HD(t))),n=jv(n);const r=Zv(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,jv(this._scalabilityMode),this._optimizationMode,r,jv(this._hints));return t&&n&&o.setEncoderConfiguration(n),Jy.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new iv(tv.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new iv(tv.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(Wv((()=>{rA.reportApiInvoke(null,{name:gv.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:Rv.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!Oy("ENABLE_VIDEO_SEI")||!Oy("ENABLE_ENCODED_TRANSFORM"))return void Jy.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new iv(tv.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void Jy.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===n?this.safeEmit("sei-to-send",e):Jy.warning("SEI is not supported by ".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(hP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await Lv(this,QD.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Lv(this,QD.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(hP.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(pP.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(pP.REQUEST_CONSTRAINTS)}},gP(Pk.prototype,"play",[ck,dk],Object.getOwnPropertyDescriptor(Pk.prototype,"play"),Pk.prototype),gP(Pk.prototype,"stop",[lk],Object.getOwnPropertyDescriptor(Pk.prototype,"stop"),Pk.prototype),gP(Pk.prototype,"setEnabled",[uk,hk,pk],Object.getOwnPropertyDescriptor(Pk.prototype,"setEnabled"),Pk.prototype),gP(Pk.prototype,"setMuted",[_k,Ek,fk],Object.getOwnPropertyDescriptor(Pk.prototype,"setMuted"),Pk.prototype),gP(Pk.prototype,"setEncoderConfiguration",[mk,Tk],Object.getOwnPropertyDescriptor(Pk.prototype,"setEncoderConfiguration"),Pk.prototype),gP(Pk.prototype,"getStats",[Sk],Object.getOwnPropertyDescriptor(Pk.prototype,"getStats"),Pk.prototype),gP(Pk.prototype,"setBeautyEffect",[gk,Rk],Object.getOwnPropertyDescriptor(Pk.prototype,"setBeautyEffect"),Pk.prototype),gP(Pk.prototype,"getCurrentFrameData",[Ck],Object.getOwnPropertyDescriptor(Pk.prototype,"getCurrentFrameData"),Pk.prototype),gP(Pk.prototype,"getCurrentFrameImage",[Ik],Object.getOwnPropertyDescriptor(Pk.prototype,"getCurrentFrameImage"),Pk.prototype),gP(Pk.prototype,"setBitrateLimit",[vk],Object.getOwnPropertyDescriptor(Pk.prototype,"setBitrateLimit"),Pk.prototype),gP(Pk.prototype,"setOptimizationMode",[yk],Object.getOwnPropertyDescriptor(Pk.prototype,"setOptimizationMode"),Pk.prototype),gP(Pk.prototype,"setScalabiltyMode",[Ak],Object.getOwnPropertyDescriptor(Pk.prototype,"setScalabiltyMode"),Pk.prototype),gP(Pk.prototype,"updateMediaStreamTrackResolution",[bk],Object.getOwnPropertyDescriptor(Pk.prototype,"updateMediaStreamTrackResolution"),Pk.prototype),gP(Pk.prototype,"pipe",[wk],Object.getOwnPropertyDescriptor(Pk.prototype,"pipe"),Pk.prototype),gP(Pk.prototype,"unpipe",[Ok],Object.getOwnPropertyDescriptor(Pk.prototype,"unpipe"),Pk.prototype),gP(Pk.prototype,"close",[Nk],Object.getOwnPropertyDescriptor(Pk.prototype,"close"),Pk.prototype),gP(Pk.prototype,"replaceTrack",[Dk],Object.getOwnPropertyDescriptor(Pk.prototype,"replaceTrack"),Pk.prototype),Pk),Wk=(Lk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),kk=$P(),Mk=uy("CameraVideoTrack","_enabledMutex"),Uk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),xk=$P(),Vk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),Fk=$P(),Bk=nA({argsMap:e=>[e.getTrackId()]}),jk=class e extends Gk{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,HD(t.encoderConfig),n,r,o),RP(this,"_config",void 0),RP(this,"_originalConstraints",void 0),RP(this,"_constraints",void 0),RP(this,"_enabled",!0),RP(this,"_deviceName","default"),RP(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(GI()||WI())&&!function(){const e=vI();if(e.os!==SI.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&YI()&&this._enabled&&!this._isClosed&&(Jy.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=HD(this._config.encoderConfig),wP.on(UD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),wP.on(UD.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(Jy.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await YP.getDeviceById(e),i={};i.video=IP({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await GP(i,this.getTrackId())}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await GP({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await YP.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}Jy.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){Jy.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:IP(IP({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await GP(t,this.getTrackId())}catch(t){throw Jy.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await GP({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=IP({},t.video),Jy.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(Jy.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await GP({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await Lv(this,QD.NEED_ENABLE_TRACK,this)}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),Jy.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await Lv(this,QD.NEED_DISABLE_TRACK,this)}catch(e){throw Jy.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}Jy.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new iv(tv.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=HD(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=Bv(this._config);i.encoderConfig=e;const n=aL(i);(NI()||LI()||KI())&&(n.deviceId=void 0),Jy.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new iv(tv.UNEXPECTED_ERROR,e.toString());throw Jy.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(ZD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await Lv(this,QD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Jy)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((LI()||KI())&&this._enabled&&!this._isClosed&&wP.duringInterruption){const e=async()=>{wP.off(UD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(Jy.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};wP.on(UD.IOS_INTERRUPTION_END,e)}else Jy.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(nP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=YP.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await GP({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),wP.off(UD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),wP.off(UD.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=IP(IP({},n),HD(t))),n=jv(n);const r=Zv(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,jv(IP(IP({},this._config),{},{encoderConfig:n})),jv(this._constraints),jv(this._scalabilityMode),this._optimizationMode,r);return t&&n&&o.setEncoderConfiguration(n),Jy.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(pP.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(pP.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},gP(jk.prototype,"setDevice",[Lk,kk],Object.getOwnPropertyDescriptor(jk.prototype,"setDevice"),jk.prototype),gP(jk.prototype,"setEnabled",[Mk,Uk,xk],Object.getOwnPropertyDescriptor(jk.prototype,"setEnabled"),jk.prototype),gP(jk.prototype,"setEncoderConfiguration",[Vk,Fk],Object.getOwnPropertyDescriptor(jk.prototype,"setEncoderConfiguration"),jk.prototype),gP(jk.prototype,"close",[Bk],Object.getOwnPropertyDescriptor(jk.prototype,"close"),jk.prototype),jk);function Hk(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=IP(IP({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?Jy.debug("[".concat(e,"] set content hint to"),i.optimizationMode):Jy.debug("[".concat(e,"] set content hint failed")))):Jy.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var Kk,Yk,qk,zk,Jk,Xk,Qk,Zk,$k,eM,tM,iM;class nM extends vP{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(Zv(5,""))),RP(this,"_userId",void 0),RP(this,"_uintId",void 0),RP(this,"_isDestroyed",!1),RP(this,"store",void 0),RP(this,"processor",void 0),RP(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=n}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,Jy.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let rM=(Kk=nA({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Yk=nA({argsMap:e=>[e.getTrackId()]}),qk=nA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),zk=nA({argsMap:e=>[e.getTrackId()]}),gP((Jk=class extends nM{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==fP.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),RP(this,"_videoVisibleTimer",null),RP(this,"_previousVideoVisibleStatus",void 0),RP(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),RP(this,"trackMediaType",oP.VIDEO),RP(this,"_videoWidth",void 0),RP(this,"_videoHeight",void 0),RP(this,"_player",void 0),RP(this,"processorDestination",void 0),RP(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new tL(this.getTrackId(),"remote"),this.processorDestination=new eL(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return Wv((()=>{Jy.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),kv(this,QD.GET_STATS)||IP({},uP)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(Jy.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}Jy.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=IP(IP({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new ok(i):this._player=new ak(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(rP.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(rP.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(rP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),Oy("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,Jy.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){sL(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(ey)}_updatePlayerSource(){Jy.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=pv.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new iv(tv.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new iv(tv.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(hP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(hP.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(iP.SEI_RECEIVED,e)}}).prototype,"play",[Kk],Object.getOwnPropertyDescriptor(Jk.prototype,"play"),Jk.prototype),gP(Jk.prototype,"stop",[Yk],Object.getOwnPropertyDescriptor(Jk.prototype,"stop"),Jk.prototype),gP(Jk.prototype,"pipe",[qk],Object.getOwnPropertyDescriptor(Jk.prototype,"pipe"),Jk.prototype),gP(Jk.prototype,"unpipe",[zk],Object.getOwnPropertyDescriptor(Jk.prototype,"unpipe"),Jk.prototype),Jk),oM=(Xk=nA({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Qk=nA({argsMap:(e,t)=>[e.getTrackId(),t]}),Zk=nA({argsMap:e=>[e.getTrackId()]}),$k=nA({argsMap:e=>[e.getTrackId()]}),eM=nA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),tM=nA({argsMap:e=>[e.getTrackId()]}),gP((iM=class extends nM{get isPlaying(){return this._useAudioElement?ZP.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),RP(this,"trackMediaType",oP.AUDIO),RP(this,"_source",void 0),RP(this,"_useAudioElement",!0),RP(this,"_volume",100),RP(this,"processorContext",void 0),RP(this,"processorDestination",void 0),RP(this,"_played",!1),RP(this,"_bypassWebAudio",!1),Oy("DISABLE_WEBAUDIO")?(this._source=new rL,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new MP(e,!0),Oy("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(sP.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(rP.FIRST_FRAME_DECODED)})),this.processorContext=new nL(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new iL(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(sP.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(sP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(sP.ON_AUDIO_BUFFER),this._source.on(sP.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?ZP.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!kD())throw new iv(tv.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ZP.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return Wv((()=>{Jy.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),kv(this,QD.GET_STATS)||IP({},dP)}play(){Jy.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(Jy.debug("[".concat(this.getTrackId(),"] use audio element to play")),ZP.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){Jy.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?ZP.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Jy.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ZP.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new iv(tv.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new iv(tv.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new iv(tv.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(hP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(hP.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(hP.ON_TRACK),this.processorDestination.removeAllListeners(hP.ON_NODE)}}).prototype,"setVolume",[Xk],Object.getOwnPropertyDescriptor(iM.prototype,"setVolume"),iM.prototype),gP(iM.prototype,"setPlaybackDevice",[Qk],Object.getOwnPropertyDescriptor(iM.prototype,"setPlaybackDevice"),iM.prototype),gP(iM.prototype,"play",[Zk],Object.getOwnPropertyDescriptor(iM.prototype,"play"),iM.prototype),gP(iM.prototype,"stop",[$k],Object.getOwnPropertyDescriptor(iM.prototype,"stop"),iM.prototype),gP(iM.prototype,"pipe",[eM],Object.getOwnPropertyDescriptor(iM.prototype,"pipe"),iM.prototype),gP(iM.prototype,"unpipe",[tM],Object.getOwnPropertyDescriptor(iM.prototype,"unpipe"),iM.prototype),iM);const sM=new class extends mv{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),RP(this,"_lastHiddenTime",0),RP(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),Jy.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};class aM extends mv{constructor(e,t){super(),RP(this,"trackMediaType",oP.DATA),RP(this,"_version",1),RP(this,"_type",3),RP(this,"_config",void 0),RP(this,"_originDataChannel",void 0),RP(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),RP(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),RP(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return Oy("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new Gh(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new iv(tv.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new iv(tv.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new iv(tv.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[SP.OPEN,SP.CLOSE,SP.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class cM extends aM{constructor(e){super(e),RP(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLengthDD.revokeObjectURL(e)),0),new Worker(DD.createObjectURL(e))}const uM=new Map;const hM=new Map;function pM(e,t,i){let n=new Uint8Array(e,t,i),r=[],o=0;for(;r.length{o.push(e)}));const s=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(Jy.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const s=o.shift();s&&(t.data=function(e,t){const i=function(e){const t=e.length;let i=[],n=0;for(;nr.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"tx",port:o.port2},[o.port2]);e.transform=s,await new Gh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(Jy.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n))},i.worker=r}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}const t=_M.get(e);if(t){_M.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){Jy.warning(e&&e.message)}}}_M.set(e,i),e.track.addEventListener("ended",n)}const fM=new Map;!function(){const e=vI();PD.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),PD.getStreamFromExtension=e.name===gI.CHROME&&Number(e.version)>34,PD.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),PD.supportMinBitrate=e.name===gI.CHROME||e.name===gI.EDGE,PD.supportSetRtpSenderParameters=function(){const e=vI();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!JI()||!(!NI()&&!wI())||e.name===gI.FIREFOX&&Number(e.version)>=64)}(),e.name===gI.SAFARI&&(Number(e.version)>=14?PD.supportDualStream=!0:PD.supportDualStream=!1),PD.webAudioMediaStreamDest=function(){const e=vI();return!(e.name===gI.SAFARI&&Number(e.version)<12)}(),PD.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,PD.supportWebGL="undefined"!=typeof WebGLRenderingContext,PD.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,JI()||(PD.webAudioWithAEC=!0),PD.supportShareAudio=function(){const e=vI();return(e.os===SI.WIN_10||e.os===SI.WIN_81||e.os===SI.WIN_7||e.os===SI.LINUX||e.os===SI.MAC_OS||e.os===SI.CHROMIUM_OS)&&e.name===gI.CHROME&&Number(e.version)>=74}(),PD.supportDataChannel=!!(kI(76)||function(e){const t=vI();return!(t.name!==gI.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||xI(14)),PD.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!PI()&&!!e&&e.prototype.setConfiguration instanceof Function}(),PD.supportWebRTCEncodedTransform=function(){const e=vI();return"Chrome"===e.name&&Number(e.version)>=86||"Safari"===e.name&&Number(e.version)>=15}(),PD.supportWebRTCInsertableStream=function(){const e=vI();return(e.name===gI.CHROME||e.name===gI.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),PD.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,PD.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,Fv((()=>{PD.supportDualStreamEncoding=function(){const e=vI();return!!Oy("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&Oy("CHROME_DUAL_STREAM_USE_ENCODING")))}(),Jy.info("browser compatibility",JSON.stringify(PD),JSON.stringify(e))}))}();class mM extends mv{constructor(e,t){super(),ng(this,"signal",void 0),ng(this,"token",void 0),ng(this,"tokenTimeout",void 0),ng(this,"tokenInterval",void 0),ng(this,"_sequence",0),ng(this,"userMap",new Map),ng(this,"encoder",new TextEncoder),this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===lb.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*Oy("P2P_TOKEN_INTERVAL"))};i()}async send(e,t,i,n,r){var o,s,a;if(0===this.userMap.size)return;const c=Array.from(Jw(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(s=n)&&void 0!==s?s:Zv(6,""),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:n,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(c)};Oy("SHOW_P2P_LOG")&&Jy.debug("send message",d,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(d)).forEach((e=>{this.signal.request(hb.DATA_STREAM,{payload:Kv(this.encoder.encode(e))})}));const l=new Gh(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),this.off(ow.ABORT,a),Jy.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?r(new iv(tv.INVALID_REMOTE_USER)):r(new iv(tv.TIMEOUT))}),Oy("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off(ow.ABORT,a),i&&t()},a=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),r(new iv(tv.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)))};this.once(ow.ABORT,a),this.once("res-@".concat(n,"_ack"),s);const c=(i,c)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),s),this.off(ow.ABORT,a),"success"===i?t(c):r(new iv(tv.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)))};let l=!1;i||(this.once("res-@".concat(n),c),Qv(Oy("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||Jy.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(d))})))}));try{return await l}catch(o){if(o.code===tv.TIMEOUT)return await this.send(e,t,i,n,r);throw o}}onMessage(e){var t;const{_uid:i}=e;let n,r=this.userMap.get(i);if(r)n=r.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==rw.CHECK)return;const{token:t}=e;n=new Map,r={uid:i,isStart:!0,token:t,splitMessageMap:n,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(i,r),this.signal.emit(_b.ON_USER_ONLINE,{uid:i}),this.handleUserOnline()}if("id"in e&&"total"in e){var o;const{id:t,total:r}=e,s=null!==(o=n.get(t))&&void 0!==o?o:[];if(s.push(e),n.has(t)||n.set(t,s),s.length!==r)return;{const r=oE(s).call(s,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");n.delete(t),(e=JSON.parse(r))._uid=i}}const{_type:s,token:a}=e;if(Dn(t=[rw.ACK,rw.CHECK]).call(t,s))return s===rw.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):Jy.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:Zv(6,""),token:this.token,_type:rw.CHECK};Oy("SHOW_P2P_LOG")&&Jy.debug("send message",e),this.signal.request(hb.DATA_STREAM,{payload:Kv(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:rw.ACK,token:this.token};Oy("SHOW_P2P_LOG")&&Jy.debug("send message",t),this.signal.request(hb.DATA_STREAM,{payload:Kv(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(rw.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this.userMap.get(i),{receivedMessagesMap:o,isStart:s,nextExpectedSequenceNumber:a}=r;if(n{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case rw.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case rw.RESPONSE:{const{success:e,message:i}=o;this.emit("res-@".concat(t),e?"success":"failed",i);break}}}}splitMessage(e){if(e.length0;){r++;const a={id:n,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(i)};JSON.stringify(a).length>mM.MAX_MESSAGE_SIZE?o-=50:(t.push(a),e=e.slice(o))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(Jy.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{Jy.debug("token timeout, ".concat(t)),this.reset(e.uid)}),Oy("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await Pv(this.signal,rw.CALL,void 0),t=await this.send(rw.CALL,e);this.signal.emit(ub.P2P_CONNECTION,t,!0)}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(ow.ABORT),this.signal.emit(_b.ON_USER_OFFLINE,{uid:i.uid,reason:aw.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(Jy.debug("change local token from ".concat(t," to ").concat(t)),this.token=Zv(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(ow.ABORT)}}ng(mM,"MAX_SIZE",1),ng(mM,"MAX_MESSAGE_SIZE",1024);class TM extends mv{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===lb.CONNECTED?this.emit(ub.WS_CONNECTED):e===lb.RECONNECTING?this.emit(ub.WS_RECONNECTING,this._websocketReconnectReason):e===lb.CLOSED&&this.emit(ub.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),ng(this,"_disconnectedReason",void 0),ng(this,"_websocketReconnectReason",void 0),ng(this,"_connectionState",lb.CLOSED),ng(this,"reconnectToken",void 0),ng(this,"p2pToken",void 0),ng(this,"websocket",void 0),ng(this,"openConnectionTime",void 0),ng(this,"clientId",void 0),ng(this,"lastMsgTime",Date.now()),ng(this,"uploadCache",[]),ng(this,"uploadCacheInterval",void 0),ng(this,"rttRolling",new Ey(5)),ng(this,"pingpongTimer",void 0),ng(this,"pingpongTimeoutCount",0),ng(this,"joinResponse",void 0),ng(this,"multiIpOption",void 0),ng(this,"initError",void 0),ng(this,"spec",void 0),ng(this,"store",void 0),ng(this,"_external_signal",void 0),ng(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(ub.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case _b.ON_DATA_STREAM:return void this.handleDataStream(t._message);case _b.MUTE_AUDIO:case _b.MUTE_VIDEO:case _b.ON_P2P_LOST:case _b.ON_USER_ONLINE:return;case _b.ON_USER_OFFLINE:const{uid:e}=t._message;return Jy.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===_b.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===_b.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(vv.UID_BANNED);break;case 15:this.close(vv.IP_BANNED);break;case 16:this.close(vv.CHANNEL_BANNED)}if(t._type===_b.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case db.ERR_LICENSE_MISSING:this.close(vv.LICENSE_MISSING);break;case db.ERR_LICENSE_EXPIRED:this.close(vv.LICENSE_EXPIRED);break;case db.ERR_LICENSE_MINUTES_EXCEEDED:this.close(vv.LICENSE_MINUTES_EXCEEDED);break;case db.ERR_LICENSE_PERIOD_INVALID:this.close(vv.LICENSE_PERIOD_INVALID);break;case db.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(vv.LICENSE_MULTIPLE_SDK_SERVICE);break;case db.ERR_LICENSE_ILLEGAL:this.close(vv.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new vw("gateway-".concat(this.clientId),this.spec.retryConfig,!0,Oy("JOIN_GATEWAY_USE_DUAL_DOMAIN"),Oy("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===lb.CONNECTED&&this.reconnect("retry",Ov.OFFLINE)})),this.p2pToken=Zv(6,""),this._external_signal=new mM(this,this.p2pToken)}async request(e,t,i,n){const r=Zv(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Gh(((e,t)=>{if(this.connectionState===lb.CONNECTED)return e();const i=()=>{this.off(ub.WS_CLOSED,n),e()},n=()=>{this.off(ub.WS_CONNECTED,i),t(new iv(tv.WS_ABORT))};this.once(ub.WS_CONNECTED,i),this.once(ub.WS_CLOSED,n)}));if(this.connectionState!==lb.CONNECTING&&this.connectionState!==lb.RECONNECTING||e===hb.JOIN||e===hb.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Gh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(ub.WS_CLOSED,c),this.off(ub.WS_RECONNECTING,c),this.emit(ub.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new iv(tv.WS_ABORT,"type: ".concat(e))),this.off(ub.WS_CLOSED,c),this.off(ub.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(ub.WS_CLOSED,c),this.once(ub.WS_RECONNECTING,c),Qv(Oy("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(Jy.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(ub.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===lb.CLOSED||e===hb.LEAVE)throw new iv(tv.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===hb.JOIN||e===hb.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=uw(l),h=new iv(tv.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(Jy.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===db.ERR_TOO_MANY_BROADCASTERS?e===hb.JOIN||e===hb.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===db.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,Jy.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ov.MULTI_IP)):this.reconnect(u.action,Ov.SERVER_ERROR),e===hb.JOIN||e===hb.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Gh((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void Jy.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(pb.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=Oy("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==lb.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),Oy("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Gh(((t,i)=>{this.once(ub.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(ub.WS_CLOSED,(()=>i(this.initError||new iv(tv.WS_ABORT)))),this.connectionState=lb.CONNECTING,this.websocket.init(e).catch(i)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||vv.LEAVE,this.connectionState=lb.CLOSED,Jy.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=Zv(6,""),this._external_signal.clear(),this._external_signal=new mM(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(ub.ABORT_P2P_EXECUTION);const e=await Pv(this,ub.REQUEST_JOIN_INFO),t=await this.request(hb.JOIN,e);if(!t)return this.emit(ub.REPORT_JOIN_GATEWAY,tv.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(ub.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=lb.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleDataStream(e){try{var t;const i=Hv(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);"total"in r&&"id"in r||Dn(t=Object.values(rw)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(_b.ON_DATA_STREAM,e)}catch(t){this.emit(_b.ON_DATA_STREAM,e)}}handleNotification(e){Jy.debug("[".concat(this.clientId,"] receive notification: "),e);const t=uw(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(vv.UID_BANNED),void this.close()):void this.reconnect(t.action,Ov.SERVER_ERROR);Jy.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=Oy("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(Jy.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>Oy("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ov.TIMEOUT):this.request(hb.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),Oy("REPORT_STATS")&&this.send(hb.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(fb.RECONNECT_WAITTING_FINISH,(e=>{this.emit(ub.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(fb.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(ub.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(fb.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(fb.CLOSED,(()=>{this.connectionState=lb.CLOSED})),this.websocket.on(fb.FAILED,(()=>{this._disconnectedReason=vv.NETWORK_ERROR,this.connectionState=lb.CLOSED})),this.websocket.on(fb.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===lb.CONNECTED?this.connectionState=lb.RECONNECTING:this.connectionState=lb.CONNECTING})),this.websocket.on(fb.WILL_RECONNECT,((e,t,i)=>{"retry"!==e?(Jy.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):Jy.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e)})),this.websocket.on(fb.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(ub.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof iv&&e.code===tv.UNEXPECTED_RESPONSE&&e.data.code===db.ERR_NO_AUTHORIZED)return Jy.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Ov.SERVER_ERROR);Jy.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ov.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(fb.REQUEST_NEW_URLS,((e,t)=>{Pv(this,ub.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(fb.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(_b.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}var SM={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),o=" ";let s;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>="€"&&e<="ÿ"}function l(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function u(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return h(e)||a(e)||"+"===e||"/"===e}function f(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function m(e){return h(e)||a(e)||"+"===e||"/"===e}function T(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function S(e){for(var t=1;t=0&&n<=255)return i;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i)}return"/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n!!jp(e).call(e))).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:n,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t=.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new v;for(;this.currentLinel(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLinel(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine2?i-2:0),r=2;rs)throw new Error("error in length, should be less or equal than ".concat(s," characters."));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error("Nothing to extract from attValue.");for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;ie!==o&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,o);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends I{constructor(e){super(),g(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach((e=>{let[t,i]=e.split("=");t=jp(t).call(t);const r="string"==typeof i?jp(i).call(i):null;"string"==typeof t&&t.length>0&&(n[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),n=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,"eol",r)}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){A(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map((e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map((e=>"".concat(o).concat(e))).join("")).concat(this.eol))).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map((e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map((e=>"".concat(o).concat(e.name).concat(e.value?"=".concat(e.value):"")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(o,"*"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>"".concat(o).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(o).concat(t).concat(o).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return i}printFmtp(e,t){if(!t)return"";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(o).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(o).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(o),n=t;return"trr-int"===n.type?i+="ttr-int".concat(o).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(o).concat(n.parameter),n.additional&&(i+="".concat(o).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(o).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new C).parse(e)}function P(e,t){return(new b).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(8)})()}(SM);var gM=SM.exports;function RM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Oy("SVC_MODE");if(Oy("ENABLE_SVC"))return function(e){return e in nb}(e)?e:nb.L1T3}function CM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function IM(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(gM.parse(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0))})),!p||0===u.length)throw new Error("Cannot get video capabilities from SDP.");if(!h||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");if(u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(l=l.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),u=u.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),s&&(l=l.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(l=l.filter((e=>{var t;return Dn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=u.filter((e=>{var t;return Dn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));u=e.concat(r?[]:GM(e,u))}const f=Oy("UNSUPPORTED_VIDEO_CODEC");return f&&f.length>0&&(u=u.filter((e=>!(e.rtpMap&&Dn(f).call(f,e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p}}function yM(e){const t=gM.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function AM(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function bM(e,t,i){const{cname:n}=e;let r;t?r=wM(t):(r=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}))),Jy.debug("Using candidates from gateway."));const o={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let a;switch(e.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}const c=FM(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach((e=>{d.push({kind:Hb.VIDEO,ssrcId:e.v,rtx:e.v_rtx,mslabel:"".concat(e.v,"_").concat(e.a)},{kind:Hb.AUDIO,ssrcId:e.a,mslabel:"".concat(e.v,"_").concat(e.a)})})),{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:c,setup:a,cname:n,preSSRCs:d}}function wM(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],Jy.debug("Using remote candidate from AP ".concat(e.ip,":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),Jy.debug("Using IPV6 remote candidate from AP ".concat(e.ip6,":").concat(e.port)))),t}function OM(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=Zv(8,"track-"),c={ssrcId:o,attributes:IM({label:a,mslabel:i=i||Zv(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:IM({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:r}}function NM(e,t){t instanceof $L&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!PI()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))}))}function DM(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function PM(e,t){var i;if(!(t instanceof Gk&&t._encoderConfig&&-1===t._hints.indexOf(ZD.SCREEN_TRACK)))return;const n=t._encoderConfig;LD().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin))})),LD().supportMinBitrate&&!Dn(i=t._hints).call(i,ZD.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(Oy("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))}))}function LM(e){if("video"!==e.media.mediaType)return;const t=vI();if(t.name!==gI.SAFARI&&t.os!==SI.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function kM(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));if(t){e.attributes.extmaps.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName));if(t){e.attributes.extmaps.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function MM(e,t,i){if(PI())return;if("video"!==e.media.mediaType)return;if(!(t instanceof Gk))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!Oy("SIMULCAST"))return;if("vp9"===i&&Oy("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(await i.createOffer()).sdp,{send:r,recv:o,sendrecv:s}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=vM(i,e,t,"sendonly"),r=vM(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(VM(n,r,"videoExtensions",o,s,a),VM(n,r,"videoCodecs",o,s,a),VM(n,r,"audioExtensions",o,s,a),VM(n,r,"audioCodecs",o,s,a),Oy("RAISE_H264_BASELINE_PRIORITY")){const e=a.videoCodecs.findIndex((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])}));if(-1!==e){const t=a.videoCodecs.findIndex((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())}));if(t{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))}))),-1!==t&&Oy("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))})))}}return{send:o,recv:s,sendrecv:a}}(e,t,n);try{i.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function xM(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=vM(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(VM(e,t,"videoExtensions",i,n,r),VM(e,t,"videoCodecs",i,n,r),VM(e,t,"audioExtensions",i,n,r),VM(e,t,"audioCodecs",i,n,r),Oy("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:r}}function VM(e,t,i,n,r,o){if("videoExtensions"===i||"audioExtensions"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}if("videoCodecs"===i||"audioCodecs"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}}function FM(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=n,{send:r,recv:o}}function BM(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function jM(e,t,i,n){let r=[];if(e===Hb.VIDEO){if(Oy("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===Oy("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Dn(i).call(i,n)?e.push(t):Dn(i).call(i,"vp9")?o.push(t):Dn(i).call(i,"vp8")?s.push(t):Dn(i).call(i,"h264")&&a.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==a.length&&(e=a,t="h264"),Jy.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===r.length&&(Jy.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),Oy("USE_PUB_RTX")||Oy("USE_SUB_RTX")){const e=GM(r,t.videoCodecs);r=[...r,...e]}}else r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)})),0===r.length&&(Jy.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")})));return r}function GM(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Dn(i).call(i,e.fmtp&&e.fmtp.parameters.apt)))}async function WM(e,t,i){const n=t.toString(),r=KM(n,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:n});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=HM(s,i||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function HM(e,t,i){const n=gM.parse(e),{useXR:r}=t;return n.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(i)&&!Dn(i).call(i,e.attributes.mid)||("audio"===e.media.mediaType&&BM(e),r&&Dn(t=["audio","video"]).call(t,e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),gM.print(n)}function KM(e,t,i,n){if(Oy("SDP_LOGGING"))return Jy.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{KM(e,"answer","local"===i?"remote":"local",n)}:void 0}function YM(e,t){return typeof Oy(e)===t?Oy(e):void 0}function qM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function zM(e){for(var t=1;t{let{address:i}=t;const[n,r]=i.split(":"),o={host:n,port:r};return e.proxyServer&&(o.proxy=e.proxyServer),o}));o=(await this.signal.init(t,i)).uid,Jy.debug("[".concat(this.store.clientId,"] websocket join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var a;throw Jy.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),rA.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(a=t.data)||void 0===a?void 0:a.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!s,signalChannel:"0",preload:e.preload}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),Jy.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{Jy.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(kb.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(kb.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(kb.NETWORK_QUALITY,{uplinkNetworkQuality:kw(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:kw(this._statsCollector.trafficStats.B_dnq)}):this.emit(kb.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),o}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==vv.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==lb.CONNECTED||await function(e,t){return t===1/0?e:Gh.race([e,Xv(t)])}(this.signal.request(hb.LEAVE,void 0,!0),3e3)}catch(e){Jy.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==vv.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:Oy("PUB_EXTEND"),twcc:!!Oy("PUBLISH_TWCC"),rtx:!!Oy("USE_PUB_RTX")};try{return(await this.signal.request(hb.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===db.ERR_PUBLISH_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(hb.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===db.ERR_PUBLISH_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(hb.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){Jy.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Gh.all(e.map((e=>this.signal.request(hb.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){Jy.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!Oy("SUBSCRIBE_TWCC"),rtx:!!Oy("USE_SUB_RTX")||void 0,extend:Oy("SUB_EXTEND"),svc:Array.isArray(Oy("SVC"))&&0!==Oy("SVC").length?Oy("SVC"):void 0};try{return await this.signal.request(hb.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===db.ERR_SUBSCRIBE_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!Oy("SUBSCRIBE_TWCC"),rtx:!!Oy("USE_SUB_RTX"),extend:Oy("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(Oy("SVC"))&&0!==Oy("SVC").length?Oy("SVC"):void 0};try{return(await this.signal.request(hb.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===db.ERR_SUBSCRIBE_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(hb.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===db.ERR_SUBSCRIBE_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!Oy("USE_SUB_RTX"),twcc:!!Oy("SUBSCRIBE_TWCC"),svc:Array.isArray(Oy("SVC"))&&0!==Oy("SVC").length?Oy("SVC"):void 0};try{return await this.signal.request(hb.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===db.ERR_SUBSCRIBE_REQUEST_INVALID)return Jy.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(hb.SET_VIDEO_PROFILE,t);Jy.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(hb.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){Jy.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new mb(tv.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Gh.all(e.map((e=>this.signal.request(hb.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){Jy.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(hb.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){Jy.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(hb.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(hb.GATEWAY_INFO)}async renewToken(e){await this.signal.request(hb.RENEW_TOKEN,e),this.key=e.token}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(hb.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(hb.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(hb.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(hb.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(hb.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(hb.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.signal instanceof TM)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),zM({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(hb.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=JM.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:sA.username,password:sA.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(zM(zM({},sA),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(hb.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&Fv((()=>{this.emit(kb.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new mb(tv.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=Oy("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);const n=!(PI()||MI(87)||MD())&&("boolean"==typeof Oy("ENABLE_PRE_SUB")&&Oy("ENABLE_PRE_SUB")),r=!MD()&&YM("ENABLE_PREALLOC_PC","boolean"),o=zM({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:Cy,browser:navigator.userAgent,process_id:Oy("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:Oy("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:Oy("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:Oy("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof Oy("SUBSCRIBE_AUDIO_FILTER_TOPN")?Oy("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof Oy("ENABLE_PUBLISH_AUDIO_FILTER")?Oy("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof Oy("ENABLE_USER_LICENSE_CHECK")?Oy("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:!0===Oy("USE_PUB_RTX")||!0===Oy("USE_SUB_RTX")||void 0,disableFEC:Oy("DISABLE_FEC"),enableNTPReport:!!Oy("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!Oy("ENABLE_INSTANT_VIDEO")||void 0,enableFulllinkAvSync:!!Oy("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:YM("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!Oy("ENABLE_AUT_FEEDBACK")||void 0,rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!Oy("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:YM("USE_XR","boolean"),enableLossbasedBwe:YM("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!Oy("ENABLE_AUT_CC")||void 0,enableCCFallback:YM("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:r,preSubNum:n?YM("PRE_SUB_NUM","number"):void 0,enablePubTWCC:YM("PUBLISH_TWCC","boolean"),enableSubTWCC:YM("SUBSCRIBE_TWCC","boolean"),enablePubRTX:YM("USE_PUB_RTX","boolean"),enableSubRTX:YM("USE_SUB_RTX","boolean"),enableSubSVC:Oy("ENABLE_SVC")?Oy("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(Oy("SVC"))&&0!==Oy("SVC").length?Oy("SVC"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(o.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(o.aes_mode=this.joinInfo.aesmode,Oy("ENCRYPT_AES")?(o.aes_secret=this.joinInfo.aespassword,o.aes_encrypt=!0):o.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(o.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(o.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(o.default_video_stream=this.joinInfo.defaultVideoStream),o}getRejoinMessage(){if(!this.joinInfo)throw new mb(tv.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(ub.WS_RECONNECT_WAITTING_FINISH,(e=>{var t;Dn(t=["tryNext","recover"]).call(t,e)&&this.joinInfo&&rA.adjustSessionStartTime(this.joinInfo.sid)})),this.signal.on(ub.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(ub.WS_RECONNECTING,(e=>{this.joinInfo&&rA.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Ov.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",rA.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(ub.WS_CLOSED,(e=>{let t;switch(e){case vv.LEAVE:t=Ov.LEAVE;break;case vv.UID_BANNED:case vv.IP_BANNED:case vv.CHANNEL_BANNED:case vv.SERVER_ERROR:t=Ov.SERVER_ERROR;break;case vv.FALLBACK:t=Ov.FALLBACK;break;case vv.LICENSE_MISSING:case vv.LICENSE_EXPIRED:case vv.LICENSE_MINUTES_EXCEEDED:case vv.LICENSE_PERIOD_INVALID:case vv.LICENSE_MULTIPLE_SDK_SERVICE:case vv.LICENSE_ILLEGAL:case vv.TOKEN_EXPIRE:t=e;break;default:t=Ov.NETWORK_ERROR}Jy.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+Ov.NETWORK_ERROR)),this.joinInfo&&rA.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===vv.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==vv.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(ub.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(Jy.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),rA.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void Jy.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));wy("EVENT_REPORT_DOMAIN",e[1]),wy("EVENT_REPORT_BACKUP_DOMAIN",e[1]),wy("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}})),this.signal.on(_b.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(ub.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new mb(tv.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,Pv(this,kb.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(ub.REQUEST_JOIN_INFO,(async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await Pv(this,kb.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}))})),this.signal.on(ub.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(ub.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var r;e instanceof mb?(i=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,n=e.message):i=e;rA.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload}),this._isProactiveJoin=!1})),this.signal.on(ub.IS_P2P_DISCONNECTED,(e=>{e(Mv(this,kb.IS_P2P_DISCONNECTED))})),this.signal.on(ub.DISCONNECT_P2P,(()=>{this.emit(kb.DISCONNECT_P2P)})),this.signal.on(ub.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(ub.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(ub.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(kb.JOIN_RESPONSE,e,t)})),this.signal.on(ub.PRE_CONNECT_PC,(async()=>{if(this.joinInfo){this.updateTurnConfigFromSignal();const e=this.getCurrentGatewayAddress(),t=Oy("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(e&&t){const i=wM(e);this.emit(kb.PRE_CONNECT_PC,{candidates:i,fingerprint:t})}}}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(hb.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(hb.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw Jy.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(hb.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(hb.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw Jy.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(hb.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Lb.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(hb.CONTROL,i,!0,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Lb.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(hb.CONTROL,i,!0,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===Hb.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(hb.CONTROL,i,!0,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===Hb.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(hb.CONTROL,i,!0,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(hb.RESTART_ICE,t,!0)}catch(e){throw Jy.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,Ov.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!Oy("GATEWAY_WSS_ADDRESS"))return Oy("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(Jy.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(hb.SET_PARAMETER,{enablePublishAudioFilter:e})}}let QM=0,ZM=0;function $M(e,t,i,n){return new Gh(((r,o)=>{t.timeout=t.timeout||Oy("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),QM+=zv(t.data)):i&&(t.data.size?QM+=t.data.size:t.data instanceof FormData?QM+=Jv(t.data):QM+=zv(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,pI.request(t).then((e=>{"string"==typeof e.data?ZM+=zv(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ZM+=e.data.byteLength:ZM+=zv(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{pI.isCancel(e)?o(new mb(tv.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new mb(tv.NETWORK_TIMEOUT,e.message)):e.response?o(new mb(tv.NETWORK_RESPONSE_ERROR,e.response.status)):o(new mb(tv.NETWORK_ERROR,e.message))}))}))} /*! formdata-polyfill. MIT License. Jimmy W?rting */!function(){var e;function i(e){var t=0;return function(){return t>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r{const e=Oy("AREAS");0===e.length&&e.push(xb.GLOBAL);return Jn(e).call(e,((e,t,i)=>{const n=tU(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},tU=e=>e===xb.OVERSEA?"".concat(Fb.ASIA,",").concat(Fb.EUROPE,",").concat(Fb.AFRICA,",").concat(Fb.NORTH_AMERICA,",").concat(Fb.SOUTH_AMERICA,",").concat(Fb.OCEANIA):Fb[e],iU=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=Bb[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},nU={GLOBAL:{ASIA:[xb.CHINA,xb.JAPAN,xb.INDIA,xb.KOREA,xb.HKMC],EUROPE:[],NORTH_AMERICA:[xb.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},rU=Object.keys(nU[xb.GLOBAL]),oU=[xb.CHINA,xb.NORTH_AMERICA,xb.EUROPE,xb.ASIA,xb.JAPAN,xb.INDIA,xb.OCEANIA,xb.SOUTH_AMERICA,xb.AFRICA,xb.KOREA,xb.HKMC,xb.US],sU=function(e,t){let i=[];if(Dn(e).call(e,xb.GLOBAL)){const o=[xb.GLOBAL,xb.OVERSEA],s=Object.keys(Bb);if(t===xb.GLOBAL)throw new mb(tv.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===xb.CHINA)i=[xb.OVERSEA];else if(r=t,Dn(rU).call(rU,r)){const e=(n=t,nU[xb.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter((e=>!Dn(r).call(r,e)))}else if(function(e){let t=!1;return rU.forEach((i=>{var n;Dn(n=nU[xb.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return rU.forEach((i=>{var n;Dn(n=nU[xb.GLOBAL][i]).call(n,e)&&(t=i)})),t}(t),n=[...o,e,t];i=s.filter((e=>!Dn(n).call(n,e)))}else i=e;i=function(e){const t=[];return oU.forEach((i=>{Dn(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!Dn(oU).call(oU,e))))}(i)}else i=e;var n,r;return i};function aU(e){var t,i;if(!e&&Dn(t=Oy("AREAS")).call(t,xb.EXTENSIONS))return Jy.debug("update area from ap : reset"),void cU(oA,!0);if(!Dn(i=Oy("AREAS")).call(i,xb.GLOBAL)||!e)return;let n=Bb.EXTENSIONS;n&&(n={CODE:tU(xb.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},Jy.debug("update area from ap success: ".concat(e,",config is "),n),wy("AREAS",[xb.EXTENSIONS],!0),Object.keys(n).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){wy(e,n[e][0])}else wy(e,n[e])})))}function cU(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=rA.reportApiInvoke(null,{name:gv.SET_AREA,options:e,tag:Rv.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Dn(Vb).call(Vb,e))throw new mb(tv.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new mb(tv.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?sU(r,i):r}if(!t){if(Ny.AREAS){const e=new mb(tv.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void Jy.warning("setArea is prohibited because of config-distribute")}if(Dn(n).call(n,xb.GLOBAL)&&Oy("AREAS")===xb.EXTENSIONS){const e=new mb(tv.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void Jy.warning("setArea is prohibited because of ap extensions")}}wy("AREAS",n,t);const r=iU(n);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){wy(e,r[e][0])}else wy(e,r[e])})),Jy.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function dU(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function lU(e){for(var t=1;t{a=Date.now();const e=await $M(d,{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new mb(tv.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw Jy.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new mb(tv.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw Jy.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new mb(tv.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw Jy.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(Oy("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return Oy("LIVE_STREAMING_ADDRESS")&&(r.addressList=Oy("LIVE_STREAMING_ADDRESS")instanceof Array?Oy("LIVE_STREAMING_ADDRESS"):[Oy("LIVE_STREAMING_ADDRESS")]),lU(lU({},r),{},{responseTime:c})}),((n,r)=>(rA.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((n,r)=>(rA.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==tv.OPERATION_ABORTED&&n.code!==tv.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let pU=1;function _U(e,t,i,n){let{url:r,areaCode:o}=e;const{clientId:s,sid:a}=t,c=Date.now();let d;const[l,u]=SU(t,o,[bw.CHOOSE_SERVER]);let h=Uv.networkState;return _y((async()=>{h&&Uv.networkState===Nv.OFFLINE&&Uv.onlineWaiter&&await Gh.race([Uv.onlineWaiter,Qv(n&&n.maxRetryTimeout||hy.maxRetryTimeout)]),h=Uv.networkState;const{data:e,headers:o}=await $M(r,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===o.http3?1:-1,rA.reportResourceTiming(r,a),fU(e,r,t,c,[bw.CHOOSE_SERVER],d);const s=Mw(e,bw.CHOOSE_SERVER);return mU(s),Dw(s,r)}),(e=>(e&&rA.joinChooseServer(a,{lts:c,succ:!0,csAddr:r,opid:u,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[bw.CHOOSE_SERVER].toString(),isHttp3:d}),!1)),(e=>e.code!==tv.OPERATION_ABORTED&&(e.code===tv.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(rA.joinChooseServer(a,{lts:c,succ:!1,csAddr:r,serverList:null,opid:u,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[bw.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:h}),isHttp3:d}),Jy.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function EU(e,t,i,n){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),[d,l]=SU(t,s,a);let u;return _y((async()=>{u&&Uv.networkState===Nv.OFFLINE&&Uv.onlineWaiter&&await Gh.race([Uv.onlineWaiter,Qv(n&&n.maxRetryTimeout||hy.maxRetryTimeout)]),u=Uv.networkState;const{data:e,headers:s}=await $M(o,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,rA.reportResourceTiming(o,t.sid),fU(e,o,t,c,a,r);const l=Mw(e,bw.CHOOSE_SERVER),h=Mw(e,"proxy5"===t.cloudProxyServer?bw.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?bw.CLOUD_PROXY:bw.CLOUD_PROXY_FALLBACK);return mU(l),{gatewayInfo:Dw(l,o),proxyInfo:h,url:o}}),(e=>(e.gatewayInfo&&rA.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:l,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&rA.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1)),(e=>e.code!==tv.OPERATION_ABORTED&&(e.code===tv.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(rA.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:u})}),Jy.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const fU=(e,t,i,n,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=i,d=[],l=i=>{4096===i.flag?rA.joinChooseServer(s,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:i.error.message,csIp:i.error.data&&i.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o}):1048576!==i.flag&&4194304!==i.flag&&4194310!==i.flag||rA.joinWebProxyAP(s,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:i.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)Jy.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=dw(i),r={error:new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?Jy.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw Jy.warning("[".concat(a||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!d.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(d.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},mU=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});Oy("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?aU(e.detail[23].toLowerCase()):aU());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t0){Jy.debug("assign gateway address to",Oy("GATEWAY_ADDRESS"));const t=Oy("GATEWAY_ADDRESS").map((t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r}}));e.addresses=t}},TU=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=dw(t.buffer.code);throw new mb(tv.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw Jy.debug("update ticket request received ap response without response body:",t),new mb(tv.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},SU=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:lU({6:e.stringUid,11:t,12:Oy("USE_NEW_TOKEN")?"1":void 0,22:t},e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};r.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const o=new FormData;return o.append("request",JSON.stringify(r)),[o,n]},gU=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};let RU=0;function CU(e){return Gh.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const IU=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:o}=e,s=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*a,t=e+a;return i.slice(e,t).map(n)})();o&&o.push(...e);try{c=await CU(e)}catch(e){if(d+=a,s++,!(d>=i.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c},vU=async e=>{let{referenceList:t,asyncMapHandler:i,closeFn:n}=e;const r=t.length;let o=0;const s=async()=>{const e=i(t.shift());try{return await e}catch(e){if(o++,o>=r||null!=n&&n(e))throw e;return s()}};return s()};async function yU(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=Oy("WEBCS_DOMAIN").slice(0,Oy("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:eU()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await IU({fragementLength:Oy("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(Jy.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),_U(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await Qv(1e3),null!==r)return r;const s=Oy("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:eU()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await IU({fragementLength:Oy("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(Jy.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),_U(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await CU([s(),a()]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await r}}async function AU(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await yU(e,t,i,r);if(Oy("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:o}=await DU(e,t,i,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:n};const a=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||sA.tcpport,udpport:e.udpport||sA.udpport,username:e.username||sA.username,password:e.password||sA.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:n.uid,i="glb:".concat(t.toString()),r=await fv(i),c=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||sA.tcpport,udpport:e.udpport||sA.udpport,username:i,password:r,forceturn:!1,security:!0})));a.push(...c)}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:n}}return await yU(e,t,i,r)}const{proxyInfo:a,gatewayInfo:c}=await DU(e,t,i,r),d={gatewayInfo:c},l=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:sA.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:sA.udpport,username:e.username||sA.username,password:e.password||sA.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i="glb:".concat(t.toString()),n=await fv(i),r=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||sA.tcpport,udpport:"proxy4"===o?void 0:e.udpport||sA.udpport,username:i,password:n,forceturn:"proxy4"!==o,security:"proxy5"===o})));l.push(...r)}return e.turnServer={mode:"manual",servers:l},Jy.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),d}async function bU(e,t,i,n,r){const o=Oy("ACCOUNT_REGISTER").slice(0,Oy("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):o.map((e=>"https://".concat(e,"/api/v1")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const o=await async function(e,t,i,n,r){const o=Date.now(),s={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await _y((()=>$M(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw Jy.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),rA.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:tv.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new mb(tv.INVALID_UINT_UID_FROM_STRING_UID);return rA.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=dw(i.code);return r.retry&&(a=e[(n+1)%e.length]),rA.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:r.desc,extend:s}),r.retry}),((t,i)=>t.code!==tv.OPERATION_ABORTED&&(rA.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(i+1)%e.length],!0)),r);if(0!==c.code){const e=dw(c.code);throw new mb(tv.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),o.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function wU(e,t,i){const n=Oy("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?n.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):n.map((e=>"https://".concat(e,"/api/v1")));try{const n=await vU({referenceList:r,asyncMapHandler:n=>async function(e,t,i,n){const r=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};try{const t=await $M(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=dw(t.code);throw new mb(tv.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new mb(tv.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:r,url:e,req:o,uid:t.uid,elapse:Date.now()-r}}catch(e){throw e}}(n,e,t,i),closeFn:e=>e.code===tv.OPERATION_ABORTED||e.code===tv.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function OU(e,t,i){const n=Oy("CDS_AP").slice(0,Oy("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))),r=n.map((n=>function(e,t,i,n){const r=vI(),o={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:Cy,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return _y((()=>$M(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==tv.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,s=null,a={};try{o=await CU(r)}catch(e){if(e.code===tv.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(rA.reportApiInvoke(e.sid,{name:gv.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{var i;const r=jp(i=e.slice(4)).call(i),o=JSON.parse(t[e])[1];n[r]=o})),n}(o)}catch(e){}return a}async function NU(e,t){const i=Oy("WEBCS_DOMAIN").concat(Oy("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:eU(),serviceIds:[bw.CHOOSE_SERVER,bw.CLOUD_PROXY_FALLBACK]})));try{const n=await vU({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,{url:r,areaCode:o,serviceIds:s}=e;const a=Date.now(),[c,d]=SU(t,o,s);let l=Uv.networkState;try{l&&Uv.networkState===Nv.OFFLINE&&Uv.onlineWaiter&&await Gh.race([Uv.onlineWaiter,Qv(hy.maxRetryTimeout)]),l=Uv.networkState;const{data:e,headers:t}=await $M(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);n="1"===t.http3?1:-1;const o=e=>{const t=[];if(e.response_body.forEach((i=>{const n=i.buffer.code;if(23===i.uri&&0===n&&!i.buffer.edges_services)if(4194310===i.buffer.flag)i.buffer.edges_services=[];else{const n={error:new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:i.buffer.flag};t.push(n)}if(0!==n){const r=dw(n),o={error:new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:i.buffer.flag};4194310===i.buffer.flag?Jy.warning(o.error.toString()):t.push(o)}})),t.length)throw new mb(tv.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})};o(e);const s=Mw(e,bw.CHOOSE_SERVER),u=Mw(e,bw.CLOUD_PROXY_FALLBACK);return mU(s),{gatewayInfo:Dw(s,r),proxyInfo:u,opid:d,requestTime:a,url:r,isHttp3:n,elapse:Date.now()-a}}catch(e){throw e}}(i,e,t),closeFn:e=>e.code===tv.OPERATION_ABORTED||e.code===tv.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function DU(e,t,i,n){const r=Oy("PROXY_SERVER_TYPE3"),o=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),"https://".concat(n,"/ap/?url=").concat(e)};let s=null;const a=[],c=async()=>{const r=Oy("WEBCS_DOMAIN").slice(0,Oy("AJAX_REQUEST_CONCURRENT")).map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:eU(),serviceIds:[bw.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?bw.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?bw.CLOUD_PROXY:bw.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await IU({fragementLength:Oy("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(Jy.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),EU(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c},d=async()=>{if(await Qv(1e3),null!==s)return s;const r=Oy("WEBCS_DOMAIN_BACKUP_LIST").map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:eU(),serviceIds:[bw.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?bw.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?bw.CLOUD_PROXY:bw.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await IU({fragementLength:Oy("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(Jy.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),EU(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await CU([c(),d()]))}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!u)throw new mb(tv.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];Dn(r).call(r,t)&&(e.proxyServer=t,Jy.setProxyServer(t),rA.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await Uw(u,l.uid)},s}async function PU(e,t,i){const n=Oy("UAP_AP").slice(0,Oy("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))),r=n.map((n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:Cy,cname:t.cname,uid:t.uid.toString(),requestId:pU,seq:pU};pU+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return _y((async()=>{const t=await $M(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new mb(tv.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw Jy.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new mb(tv.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw Jy.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new mb(tv.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw Jy.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(Oy("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(Oy("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==tv.OPERATION_ABORTED&&e.code!==tv.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),n)}(n,e,t,i)));try{const e=await CU(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function LU(e,t,i){let n=null;const r=[],o=async o=>{const s=Oy(o?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return o&&(await Qv(1e3),null!==n)?n:await IU({fragementLength:Oy("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(Jy.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=gU(t,[bw.CHOOSE_SERVER]);let o=Uv.networkState;return _y((async()=>{o&&Uv.networkState===Nv.OFFLINE&&Uv.onlineWaiter&&await Gh.race([Uv.onlineWaiter,Qv(n&&n.maxRetryTimeout||hy.maxRetryTimeout)]),o=Uv.networkState;const t=await $M(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return TU(t,e)}),(()=>!1),(e=>e.code!==tv.OPERATION_ABORTED&&(e.code===tv.UPDATE_TICKET_FAILED?e.data.retry:(Jy.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return n=await CU([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}function kU(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function MU(e){for(var t=1;t{this.updateConfigDistribute()}),Oy("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;rA.reportApiInvoke(null,{options:void 0,name:gv.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:Rv.TRACER}).onSuccess(JSON.stringify(Ny))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void Jy.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await OU(this.joinInfo,this.cancelToken,this.retryConfig),Jy.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e}catch(e){const t=new mb(tv.NETWORK_RESPONSE_ERROR,e);Jy.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(jb.UPDATE_BITRATE_LIMIT,e):this.emit(jb.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&MU({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;const i=oE(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;tt;n--){const t=i[n];if("number"==typeof e[t].__priority){const r=e[t].__priority,o=i[n-1];if("number"==typeof e[o].__priority){if(!(r>e[o].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e}}else{const e=t;i[n]=i[n-1],i[n-1]=e}}}const n={};i.forEach((t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach((e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=MU({value:i[e]},r&&{expires:r}))}))}));try{!function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case"ENABLE_EVENT_REPORT":case"UPLOAD_LOG":case"ENABLE_AG_ADAPTATION":case"FORCE_AG_HIGH_FRAMERATE":case"FORCE_SUPPORT_AG_ADAPTATION":case"ENCODER_CONFIG_LIMIT":case"CAMERA_CAPTURE_CONFIG":case"ENABLE_PRELOAD":if(Object.prototype.hasOwnProperty.call(by,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;Ny[i]=n,by[i]=n,Jy.debug("Update global parameters from config distribute",i,n)}}}))}catch(t){Jy.error("Error update config immediately: ".concat(e),t.message)}}(n);const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),Jy.debug("Caching global parameters ".concat(e))}catch(e){Jy.error("Error caching global parameters:",e.message)}}}class xU extends mv{constructor(){super(...arguments),ng(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(Oy("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=Dn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",VU[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",VU[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof ik&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Pw(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof ik&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const VU={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const FU=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function BU(e,t){this.v=e,this.k=t}function jU(e){return new BU(e,0)}var GU=jh,WU=Sl;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=WU.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var HU=Sl,KU=el;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=HU.f(this),i=KU(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var YU=i(GU),qU=im.f("asyncIterator"),zU=i(qU);function JU(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof BU;YU.resolve(a?s.v:s).then((function(i){if(a){var c="return"===t?"return":"next";if(!s.k||i.done)return n(c,i);i=e[c](i).value}r(o.done?"return":"normal",i)}),(function(e){n("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new YU((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function XU(e){return function(){return new JU(e.apply(this,arguments))}}JU.prototype["function"==typeof ZS&&zU||"@@asyncIterator"]=function(){return this},JU.prototype.next=function(e){return this._invoke("next",e)},JU.prototype.throw=function(e){return this._invoke("throw",e)},JU.prototype.return=function(e){return this._invoke("return",e)};var QU=i(ie.Object.getOwnPropertySymbols),ZU=wi,$U=qi.indexOf,ex=Bn,tx=v([].indexOf),ix=!!tx&&1/tx([1],1,-0)<0;ZU({target:"Array",proto:!0,forced:ix||!ex("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return ix?tx(this,e,t)||0:$U(this,e,t)}});var nx=Xi("Array").indexOf,rx=l,ox=nx,sx=Array.prototype,ax=function(e){var t=e.indexOf;return e===sx||rx(sx,e)&&t===sx.indexOf?ox:t},cx=i(ax);function dx(e,t){if(null==e)return{};var i,n,r=function(e,t){if(null==e)return{};var i,n,r={},o=IA(e);for(n=0;n=0||(r[i]=e[i]);return r}(e,t);if(QU){var o=QU(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}function lx(e){if(Array.isArray(e))return e.map((e=>e));if(!ux(e))return e;const t={};for(const i in e){const n=e[i];ux(n)||Array.isArray(n)?t[i]=lx(n):t[i]=n}return t}function ux(e){return!("object"!=typeof e||Array.isArray(e)||!e)}class hx{constructor(e){ng(this,"input",[]),ng(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}}const px={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},_x={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:px,remoteCandidate:px}},Ex={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0},fx={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},mx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},Tx={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function Sx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function gx(e){for(var t=1;t{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new Gh((e=>{e({local:gx({},px),remote:gx({},px)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,o=0,s=0;for(const a of i)e[a].forEach(((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=n<=0||o<=0?0:o/(n+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}}function Cx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ix(e){for(var t=1;t"ssrc"===e.type));this.processSSRCStats(i);const n=t.find((e=>"VideoBwe"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=Dn(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=lx(fx);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{const t=lx(Ex),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case"audio_send":{const t=lx(mx);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new Gh(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}}function yx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ax(e){for(var t=1;t{switch(e.type){case rb.OUTBOUND:case rb.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===rb.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===rb.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case rb.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case rb.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:Ax({},px),remote:Ax({},px)};return e.forEach((i=>{let n;if(i.type===rb.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===rb.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r)}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===rb.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===rb.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===rb.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(Ax({},t),Ax({},this.stats.selectedCandidatePair.localCandidate)),e.type===rb.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(Ax({},t),Ax({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=lx(Tx),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples)}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=lx(Ex),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,r=o-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCounte.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}n&&o-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:Ax({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=lx(fx),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new hx(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new hx(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new hx(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,rb.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=lx(mx),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,rb.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(Jw(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,i){var n,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,o,s,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(o=null==l?void 0:l.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,_=null!==(s=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,f=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,m=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(u&&h&&(i.accelerateRate=u/h),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=E;let T=1920;f&&h&&(T=h/f/50,i.receivedFrames=Math.round(h/T)),m&&(i.droppedFrames=Math.round(m/T))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}}class wx extends Rx{updateStats(){return Gh.resolve()}}function Ox(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return o?o<76?new vx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new bx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof Gh||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new bx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new wx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}let Nx=class{get localCapabilities(){return Bv(this._localCapabilities)}get rtpCapabilities(){return Bv(this._rtpCapabilities)}get candidates(){return Bv(this._candidates)}get iceParameters(){return Bv(this._iceParameters)}get dtlsParameters(){return Bv(this._dtlsParameters)}constructor(e){ng(this,"sessionDesc",void 0),ng(this,"_localCapabilities",void 0),ng(this,"_rtpCapabilities",void 0),ng(this,"_candidates",void 0),ng(this,"_iceParameters",void 0),ng(this,"_dtlsParameters",void 0),ng(this,"setup",void 0),ng(this,"currentMidIndex",void 0),ng(this,"cname","o/i14u9pJrxRKAsu"),ng(this,"firefoxSsrcMidMap",new Map),e=Bv(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=s===Eb.RECEIVE_ONLY?gM.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):gM.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o;const u=s===Eb.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=s===Eb.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===Eb.RECEIVE_ONLY?r.send.videoCodecs:jM(Hb.VIDEO,u,h,c),_=s===Eb.RECEIVE_ONLY?r.send.audioCodecs:jM(Hb.AUDIO,u,h,d);for(const e of l.mediaDescriptions)e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=p.map((e=>e.payloadType.toString(10))),e.attributes.payloads=p,e.attributes.extmaps=u.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,BM(e));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return gM.print(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=OM(t,this.cname,Oy("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(PI()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o,n);let i;return-1===t?(i=this.createOrRecycleSendMedia(e,o,s,"sendonly",n,r),this.updateBundleMids()):(i=Bv(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),PI()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,i){const n=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(r);let s,a=!1;-1===o?(a=!0,s=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(s=Bv(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction="recvonly"),n.push({mid:s.attributes.mid,needCreateTransceiver:a})})),n}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=i?i:"",priority:c?c+"":"",connectionAddress:null!=n?n:"",port:r?r+"":"",type:o?o+"":"",relAddr:null!=s?s:"",relPort:a?a+"":"",extension:{}};this.candidates.some((e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port))||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,n,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=jM(o,s,this.localCapabilities.send,o===Hb.AUDIO?r:n),c=o===Hb.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(o);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const r=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(PI()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i}))}predictReceivingMids(e){const t=[];for(let i=0;i{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,r,o){const s=this.rtpCapabilities.send,a=e===Hb.VIDEO?s.videoCodecs:s.audioCodecs,c=e===Hb.VIDEO?s.videoExtensions:s.audioExtensions;PI()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){const n=Bv(e);return DM(n),NM(n,t),PM(n,t),LM(n),kM(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=Bv(e);return kM(i,t,this.localCapabilities.recv),BM(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>PI()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const Dx=["sdp"];var Px;function Lx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function kx(e){for(var t=1;t2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(VM(t,e,"videoExtensions",i,n,r),VM(t,e,"videoCodecs",i,n,r),VM(t,e,"audioExtensions",i,n,r),VM(t,e,"audioCodecs",i,n,r),Oy("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:r}}({},{},t);this.remoteSDP=new Nx({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const o=yM(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await xM({},{},r.sdp);this.localCapabilities=FM(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),kx(kx({},o),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=yM(e.sdp);return this.initialOffer=e,kx(kx({},t),{},{sdp:e.sdp})}}catch(e){throw new iv(tv.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await xM({},{},t);this.remoteSDP=new Nx({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new iv(tv.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return XU((function*(){const r=yield jU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=n.remoteSDP.receive(e,t,i);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const i=n.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(s[t].mid));o.push(i),e._updateRtpTransceiver(i)}})),PI()&&!0===Oy("SIMULCAST")&&(yield jU(n.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield jU(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=gM.parse(d),u=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return AM(t,Oy("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}));yield jU(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=n.remoteSDP.toString();throw yield jU(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield jU(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield jU(n.stopSending(a,!0)),e}yield jU(n.applySimulcastEncodings(o,e)),yield jU(n.applySendEncodings(o,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield jU(n.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}))}catch(e){throw e instanceof iv?e:new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s||null===s.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,mid:s.mid,transceiver:s}}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===vy.Auto&&(this.store.p2pTransport=vy.SdRtn,LD().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,LD().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:t}=yM(e.sdp);return this.store.descriptionStart(),this.direction===Eb.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===Eb.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:t}=yM(e.sdp);return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?PI()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:kx(kx({},px),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:kx(kx({},px),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Dn(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else Jy.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var o;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(yv(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),Oy("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),Dn(o=[vy.Relay,vy.SdRtn]).call(o,i)&&(r.iceTransportPolicy="relay"),Oy("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return Oy("ENABLE_ENCODED_TRANSFORM")&&LD().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),Jy.debug("P2PConnection p2pTransport is ".concat(i)),r}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter((e=>e.tcpport));Jy.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const o=r.length>i?r[i]:r[0];switch(t){case vy.SdRtn:const t=e.filter((e=>{var t;return Dn(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL})),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(Nw(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(Nw(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case vy.Relay:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Nw(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Nw(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return n}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();Jy.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})," )"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return Jy.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return Jy.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!LD().supportSetRtpSenderParameters)return Jy.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(e._encoderConfig){var o;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Dn(o=e._hints).call(o,ZD.LOW_STREAM)&&(i&&(r.maxFramerate=Pw(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(Oy("DSCP_TYPE")&&JI()){var s;const e=Oy("DSCP_TYPE");Dn(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];PI()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),Jy.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!LD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(NM(o,e),MM(o,e,this.store.codec))})),gM.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!PI()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Oy("SDP_LOGGING"))return Jy.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async e=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=gM.parse(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Dn(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){const n=gM.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===Hb.AUDIO&&"audio"===r.media.mediaType&&BM(r),gM.print(n)}},ib(Px.prototype,"establish",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"establish"),Px.prototype),ib(Px.prototype,"connect",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"connect"),Px.prototype),ib(Px.prototype,"receive",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"receive"),Px.prototype),ib(Px.prototype,"mockReceive",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"mockReceive"),Px.prototype),ib(Px.prototype,"stopReceiving",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"stopReceiving"),Px.prototype),ib(Px.prototype,"restartICE",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"restartICE"),Px.prototype),ib(Px.prototype,"close",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"close"),Px.prototype),ib(Px.prototype,"updateEncoderConfig",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"updateEncoderConfig"),Px.prototype),ib(Px.prototype,"updateSendParameters",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"updateSendParameters"),Px.prototype),ib(Px.prototype,"replaceTrack",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"replaceTrack"),Px.prototype),ib(Px.prototype,"muteLocal",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"muteLocal"),Px.prototype),ib(Px.prototype,"unmuteLocal",[Ux],Object.getOwnPropertyDescriptor(Px.prototype,"unmuteLocal"),Px.prototype),Px);function Ux(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(Jy.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r)}s.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,i.srcObject=new MediaStream([o]))},n.stopCapture=PP((()=>n.startCapture&&n.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),Jy.debug("clean low stream renderer")},c}var Vx=function(e){return e[e.HEIGHT=2033]="HEIGHT",e[e.FRAME_RATE=2034]="FRAME_RATE",e[e.WIDTH=2035]="WIDTH",e}(Vx||{}),Fx=function(e){return e[e.FRAME_RATE=2002]="FRAME_RATE",e[e.WIDTH=2003]="WIDTH",e[e.HEIGHT=2004]="HEIGHT",e[e.PACKAGE_LOST=2005]="PACKAGE_LOST",e[e.AVG_ENCODE=2007]="AVG_ENCODE",e[e.NACKS=2009]="NACKS",e[e.PLIS=2010]="PLIS",e[e.FIRS=2011]="FIRS",e[e.BITRATE=2012]="BITRATE",e[e.PACKAGE_RATE=2031]="PACKAGE_RATE",e[e.ADAPTATION=2032]="ADAPTATION",e[e.ACTUAL_ENCODED=2060]="ACTUAL_ENCODED",e[e.BANDWIDTH=2061]="BANDWIDTH",e[e.RETRANSMIT=2062]="RETRANSMIT",e[e.TARGET_ENCODED=2064]="TARGET_ENCODED",e[e.TRANSMIT=2066]="TRANSMIT",e[e.FREEZE=2082]="FREEZE",e[e.DISABLED=2095]="DISABLED",e[e.PLAYER_STATUS=2128]="PLAYER_STATUS",e[e.QP_SUM=2143]="QP_SUM",e}(Fx||{}),Bx=function(e){return e[e.BITRATE=2069]="BITRATE",e[e.PACKAGE_LOST=2070]="PACKAGE_LOST",e[e.PACKAGE_RATE=2071]="PACKAGE_RATE",e[e.HEIGHT=2073]="HEIGHT",e[e.FRAME_RATE=2075]="FRAME_RATE",e[e.WIDTH=2077]="WIDTH",e}(Bx||{}),jx=function(e){return e[e.JITTER=-1]="JITTER",e[e.PACKAGE_LOST=2014]="PACKAGE_LOST",e[e.WIDTH=2018]="WIDTH",e[e.HEIGHT=2019]="HEIGHT",e[e.FRAME_RATE=2020]="FRAME_RATE",e[e.JITTER_BUFFER=2023]="JITTER_BUFFER",e[e.CURRENT_DELAY=2024]="CURRENT_DELAY",e[e.NACKS=2026]="NACKS",e[e.PLIS=2027]="PLIS",e[e.FIRS=2028]="FIRS",e[e.BITRATE=2029]="BITRATE",e[e.PACKAGE_RATE=2078]="PACKAGE_RATE",e[e.FREEZE=2084]="FREEZE",e[e.DISABLED=2101]="DISABLED",e[e.PLAYER_STATUS=2129]="PLAYER_STATUS",e[e.QP_SUM=2144]="QP_SUM",e[e.I_FRAME_DELAY=2149]="I_FRAME_DELAY",e}(jx||{}),Gx=function(e){return e[e.FRAME_RATE_DECODE=2021]="FRAME_RATE_DECODE",e[e.FRAME_RATE_RENDER=2022]="FRAME_RATE_RENDER",e[e.FRAME_RATE_OUTPUT=2155]="FRAME_RATE_OUTPUT",e[e.FREEZE_TIME=2109]="FREEZE_TIME",e[e.FREEZE_TIME_RENDER=2147]="FREEZE_TIME_RENDER",e[e.FREEZE_DURATION=2156]="FREEZE_DURATION",e}(Gx||{}),Wx=function(e){return e[e.PCM_LEVEL=2104]="PCM_LEVEL",e}(Wx||{}),Hx=function(e){return e[e.PACKAGE_LOST=-1]="PACKAGE_LOST",e[e.LEVEL=2038]="LEVEL",e[e.BITRATE=2039]="BITRATE",e[e.PACKAGE_RATE=2040]="PACKAGE_RATE",e[e.AEC_RETURN_LOSS=2041]="AEC_RETURN_LOSS",e[e.AEC_RETURN_LOSS_ENH=2042]="AEC_RETURN_LOSS_ENH",e[e.FREEZE=2081]="FREEZE",e[e.DISABLED=2096]="DISABLED",e}(Hx||{}),Kx=function(e){return e[e.BITRATE=2044]="BITRATE",e[e.PACKAGE_LOST=2045]="PACKAGE_LOST",e[e.PACKAGE_RATE=2046]="PACKAGE_RATE",e[e.CURRENT_DELAY=2047]="CURRENT_DELAY",e[e.JITTER_BUFFER=2054]="JITTER_BUFFER",e[e.JITTER=2055]="JITTER",e[e.FREEZE=2083]="FREEZE",e[e.DISABLED=2102]="DISABLED",e[e.PCM_LEVEL=2105]="PCM_LEVEL",e[e.PLAYER_STATUS=2130]="PLAYER_STATUS",e[e.CONCEALED_SAMPLES=2148]="CONCEALED_SAMPLES",e}(Kx||{}),Yx=function(e){return e[e.FREEZE_TIME=-1]="FREEZE_TIME",e[e.LEVEL=2043]="LEVEL",e}(Yx||{}),qx=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e}(qx||{});const zx=1e3,Jx=3;function Xx(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function Qx(e){const t={[qx.CONN_TYPE]:0,[qx.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[qx.CONN_TYPE]=1),"tcp"===i&&(t[qx.CONN_TYPE]=3),"tls"===i&&(t[qx.CONN_TYPE]=4);break}case"srflx":t[qx.CONN_TYPE]=2}return t}function Zx(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class $x extends mv{constructor(e){super(),ng(this,"store",void 0),ng(this,"uploadWRTCStatsTimer",void 0),ng(this,"uploadOutboundDenoiserStatsTimer",void 0),ng(this,"uploadExtStatsTimer",void 0),ng(this,"uploadExtUsageStatsTimer",void 0),ng(this,"uploadInboundExtStatsTimer",void 0),ng(this,"requestStats",void 0),ng(this,"requestTransportStats",void 0),ng(this,"requestLocalMedia",void 0),ng(this,"requestRemoteMedia",void 0),ng(this,"requestAllTracks",void 0),ng(this,"requestVideoIsReady",void 0),ng(this,"requestUploadStats",void 0),ng(this,"requestUpload",void 0),ng(this,"uploadOutboundStarted",!1),ng(this,"uploadInboundStarted",!1),ng(this,"uploadTransportStarted",!1),ng(this,"uploadExtensionUsageStarted",!1),ng(this,"lastRecvStats",void 0),ng(this,"lastSendStats",void 0),ng(this,"lastFullRecvStats",void 0),ng(this,"lastFullSendStats",void 0),ng(this,"needUploadRenderFreezeTime",!0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;let t,i;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){const n={};if(this.uploadTransportStarted&&t){const r=this.getTransportStats(t,i,e);r&&(n.misc=[r])}if(this.uploadOutboundStarted&&t){const i=this.getOutboundStats(t,e?this.lastSendStats:this.lastFullSendStats,e);i&&(n.outbound=[i])}if(this.uploadInboundStarted&&i){const t=this.getInboundStats(i,e?this.lastRecvStats:this.lastFullRecvStats,e);t&&(n.inbound=t)}this.requestUploadStats(n)}this.lastRecvStats=i,this.lastSendStats=t,e||(this.lastFullRecvStats=i,this.lastFullSendStats=t)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted)return this.stopUploadWRTCStats();this.uploadWRTCStats(e!==Jx),++e===Jx+1&&(e=1)}),zx)}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0)}getTransportStats(e,t,i){if(!this.requestStats)return;if(i)return null==e.rtt?void 0:{addition:{[qx.RTT]:e.rtt,[qx.CONN_TYPE]:void 0}};const n=Qx(e);if(this.store.useP2P){if(t){const e=Qx(t);n[qx.CONN_TYPE]+=e[qx.CONN_TYPE]<<3}n[qx.CONN_TYPE]+=110}else n[qx.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i){if(!this.requestUploadStats||!this.requestLocalMedia)return;const n=this.requestLocalMedia();if(!n||0===n.length)return;let r,o,s;return n.forEach((n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case qb.LocalVideoLowTrack:case qb.LocalVideoTrack:if(a===qb.LocalVideoTrack){const n=function(e,t,i,n,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={},{sentFrame:a,inputFrame:c}=o;if(c&&a){const e=c.frameRate,t=a.frameRate;s[Fx.FREEZE]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(Xx(s,Fx.QP_SUM,o.qpSumPerFrame),r)return s;switch(a&&(Xx(s,Fx.HEIGHT,a.height),Xx(s,Fx.WIDTH,a.width),Xx(s,Fx.FRAME_RATE,a.frameRate)),s[Fx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,o.adaptionChangeReason){case"none":s[Fx.ADAPTATION]=0;break;case"cpu":s[Fx.ADAPTATION]=1;break;case"bandwidth":s[Fx.ADAPTATION]=2;break;case"other":s[Fx.ADAPTATION]=3}let d=0;o.adaptionChangeReason&&(d+=Zx(o.adaptionChangeReason)),t.qualityLimitationReason&&(d+=Zx(t.qualityLimitationReason)<<3),s[Fx.ADAPTATION]=d,s[Fx.PLAYER_STATUS]=TP[n._player?n._player.videoElementStatus:"uninit"],Xx(s,Fx.NACKS,o.nacksCount),Xx(s,Fx.PLIS,o.plisCount),Xx(s,Fx.FIRS,o.firsCount),Xx(s,Fx.AVG_ENCODE,o.avgEncodeMs);const l=i&&i.videoSend.find((t=>t.ssrc===e));if(l){let e=r?zx:zx*Jx;l.timestamp&&o.timestamp&&(e=o.timestamp-l.timestamp),null!=l.packets&&null!=o.packets&&Xx(s,Fx.PACKAGE_RATE,1e3*(o.packets-l.packets)/e),null!=o.packetsLost&&null!=l.packetsLost&&Xx(s,Fx.PACKAGE_LOST,o.packetsLost-l.packetsLost),null!=l.bytes&&null!=o.bytes&&Xx(s,Fx.BITRATE,8*(o.bytes-l.bytes)/e)}return s}(d[0].ssrcId,e,t,c,i),r=i?null:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return null;const r={},o=n.inputFrame,s=o&&o.height||i&&i.videoHeight||0,a=o&&o.width||i&&i.videoWidth||0,c=o&&o.frameRate||0;return Xx(r,Vx.HEIGHT,s),Xx(r,Vx.WIDTH,a),Xx(r,Vx.FRAME_RATE,c),r}(d[0].ssrcId,e,c),s=i?null:function(e){const t={};return Xx(t,Fx.RETRANSMIT,e.bitrate.retransmit),Xx(t,Fx.TARGET_ENCODED,e.bitrate.targetEncoded),Xx(t,Fx.ACTUAL_ENCODED,e.bitrate.actualEncoded),Xx(t,Fx.TRANSMIT,e.bitrate.transmit),Xx(t,Fx.BANDWIDTH,e.sendBandwidth),t}(e);o=Object.assign({},n,r,s)}else s=i?void 0:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return;const r={},o=n.sentFrame;if(o&&(Xx(r,Bx.HEIGHT,o.height),Xx(r,Bx.WIDTH,o.width),Xx(r,Bx.FRAME_RATE,o.frameRate)),i){const t=i.videoSend.find((t=>t.ssrc===e));if(t){let e=zx*Jx;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&Xx(r,Bx.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&Xx(r,Bx.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&Xx(r,Bx.BITRATE,8*(n.bytes-t.bytes)/e)}}return r}(d[0].ssrcId,e,t);break;case qb.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find((t=>t.ssrc===e));if(!r)return;const o={};o[Hx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const s=100*n._source.getAccurateVolumeLevel(),a=r.inputLevel;if(null!=a){const e=Math.ceil(50*Math.log10(100*a+1));Xx(o,Hx.LEVEL,e)}Xx(o,Wx.PCM_LEVEL,s),Xx(o,Hx.AEC_RETURN_LOSS,r.aecReturnLoss),Xx(o,Hx.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),o[Hx.FREEZE]=0;const c=i&&i.audioSend.find((t=>t.ssrc===e));if(c){let e=zx*Jx;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&Xx(o,Hx.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&Xx(o,Hx.PACKAGE_RATE,1e3*(r.packets-c.packets)/e)}return o}(d[0].ssrcId,e,t,c)}})),{high:o,low:s,audio:r}}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach((n=>{let[o,s]=n;const a={peer:o.uid};if(s.has(Hb.VIDEO)&&o.videoTrack){const n=o._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(o._videoSSRC)||!1,r=o.videoTrack?function(e,t,i,n,r,o,s){var a;const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},{receivedFrame:l,outputFrame:u,decodeFrameRate:h}=c,p=i&&i.videoRecv.find((t=>t.ssrc===e));if(d[jx.FREEZE]=r&&IV.isRemoteVideoFreeze(n,c,p)?1:0,Xx(d,Gx.FRAME_RATE_DECODE,h),Xx(d,jx.QP_SUM,c.qpSumPerFrame),c.framesRateFirefox&&Xx(d,jx.FRAME_RATE,c.framesRateFirefox),l&&Xx(d,jx.FRAME_RATE,l.frameRate),p){const e=t.timestamp-i.timestamp||(s?zx:Jx*zx);null!=c.packetsLost&&null!=p.packetsLost&&Xx(d,jx.PACKAGE_LOST,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&Xx(d,jx.BITRATE,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&Xx(d,jx.PACKAGE_RATE,1e3*(c.packets-p.packets)/e)}if(s)return d;l?(Xx(d,jx.HEIGHT,l.height),Xx(d,jx.WIDTH,l.width)):n&&(Xx(d,jx.HEIGHT,n._videoHeight||0),Xx(d,jx.WIDTH,n._videoWidth||0)),u&&Xx(d,Gx.FRAME_RATE_OUTPUT,u.frameRate);const _=null===(a=n._player)||void 0===a?void 0:a.rendFrameRate.toFixed(0);if(_&&Xx(d,Gx.FRAME_RATE_RENDER,+_),Xx(d,jx.JITTER_BUFFER,c.jitterBufferMs),Xx(d,jx.CURRENT_DELAY,c.currentDelayMs),Xx(d,jx.FIRS,c.firsCount),Xx(d,jx.NACKS,c.nacksCount),Xx(d,jx.PLIS,c.plisCount),n){d[jx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i,videoElementStatus:n}=e;if(t&&t.length>0&&Xx(d,Gx.FREEZE_TIME,t.splice(0,1)[0]),o&&"visible"===sM.visibility&&n===fP.PLAYING&&LD().supportRequestVideoFrameCallback){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),Xx(d,Gx.FREEZE_TIME_RENDER,t)}if("number"==typeof c.totalFreezesDuration){const e=p&&p.totalFreezesDuration?c.totalFreezesDuration-p.totalFreezesDuration:c.totalFreezesDuration;Xx(d,Gx.FREEZE_DURATION,1e3*e)}}}if(d[jx.PLAYER_STATUS]=TP[n._player?n._player.videoElementStatus:"uninit"],p&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==p.totalInterFrameDelay&&void 0!==p.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-p.totalInterFrameDelay,t=c.totalSquaredInterFrameDelay-p.totalSquaredInterFrameDelay,i=c.framesDecodeCount-p.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(d[jx.I_FRAME_DELAY]=r)}return d}(o._videoSSRC,e,t,o.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r)}if(s.has(Hb.AUDIO)&&o.audioTrack){const n=o.audioTrack?function(e,t,i,n,r){const o=t.audioRecv.find((t=>t.ssrc===e));if(!o)return;const s={},a=i&&i.audioRecv.find((t=>t.ssrc===e)),{receivedFrames:c,droppedFrames:d}=o;var l,u;if(Xx(s,Kx.JITTER,o.jitterMs),null!=c&&null!=d&&(s[Kx.FREEZE]=(u=d,0===(l=c)||100*u/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?zx:zx*Jx);null!=o.packets&&null!=a.packets&&Xx(s,Kx.PACKAGE_RATE,1e3*(o.packets-a.packets)/e),null!=a.bytes&&null!=o.bytes&&Xx(s,Kx.BITRATE,8*(o.bytes-a.bytes)/e),null!=o.packetsLost&&null!=a.packetsLost&&Xx(s,Kx.PACKAGE_LOST,o.packetsLost-a.packetsLost)}if(r)return s;const h=100*n._source.getAccurateVolumeLevel(),p=o.outputLevel;if(null!=p){const e=Math.ceil(50*Math.log10(100*p+1));Xx(s,Yx.LEVEL,e)}if(Xx(s,Kx.PCM_LEVEL,h),n&&(s[Kx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),Xx(s,Kx.JITTER_BUFFER,o.jitterBufferMs),Xx(s,Kx.CURRENT_DELAY,o.jitterBufferMs),s[Kx.PLAYER_STATUS]=TP[ZP.getPlayerState(n.getTrackId())],a){const e=o.concealedSamples-a.concealedSamples;e>0&&Xx(s,Kx.CONCEALED_SAMPLES,e)}return s}(o._audioSSRC,e,t,o.audioTrack,i):void 0;n&&(a.audio=n)}(a.video||a.audio)&&r.push(a)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,r}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof ek));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(pb.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let[t,i]=e;if(i.has(Hb.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(Hb.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:Oy("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of o)t.has(Hb.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(Hb.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:s,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(s))&&void 0!==n?n:0,l=2===a?e+Oy("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,o;t.set(s,l),i[s]?(2===a&&(i[s].value=a),c>i[s].level&&(i[s].level=c),"remote"===d&&(i[s].remoteUidCount+=1),i[s].totalTs=null!==(r=t.get(s))&&void 0!==r?r:0):i[s]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(s))&&void 0!==o?o:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}}))}(n,e);const s=Date.now(),a=s>t?s:t+1;this.requestUpload&&this.requestUpload(pb.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a})}),Oy("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}}class eV{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){ng(this,"uid",void 0),ng(this,"_uintid",void 0),ng(this,"_trust_in_room_",!0),ng(this,"_trust_audio_enabled_state_",!0),ng(this,"_trust_video_enabled_state_",!0),ng(this,"_trust_audio_mute_state_",!0),ng(this,"_trust_video_mute_state_",!0),ng(this,"_audio_muted_",!1),ng(this,"_video_muted_",!1),ng(this,"_audio_enabled_",!0),ng(this,"_video_enabled_",!0),ng(this,"_audio_added_",!1),ng(this,"_video_added_",!1),ng(this,"_is_pre_created",!1),ng(this,"_video_pre_subscribed",!1),ng(this,"_audio_pre_subscribed",!1),ng(this,"_trust_video_stream_added_state_",!0),ng(this,"_trust_audio_stream_added_state_",!0),ng(this,"_audioTrack",void 0),ng(this,"_videoTrack",void 0),ng(this,"_dataChannels",[]),ng(this,"_audioSSRC",void 0),ng(this,"_videoSSRC",void 0),ng(this,"_audioOrtc",void 0),ng(this,"_videoOrtc",void 0),ng(this,"_cname",void 0),ng(this,"_rtxSsrcId",void 0),ng(this,"_videoMid",void 0),ng(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}let tV=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});function iV(e,t){var i;let n;switch(t){case qb.LocalAudioTrack:n=Lb.Audio;break;case qb.LocalVideoTrack:n=Dn(i=e._hints).call(i,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:n=Lb.Low}return n}function nV(e){const t=LD();if(e.some((e=>e._bypassWebAudio)))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function rV(e,t){nV(e);const i=t||new ik;return e.forEach((e=>i.addAudioTrack(e))),i}var oV,sV,aV,cV,dV,lV,uV,hV,pV,_V,EV,fV;function mV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function TV(e){for(var t=1;t{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==zb.Connected)return void i(new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const s=this.filterTobeMutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>"videoLowTrack"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(s.map((e=>{let[,{id:t}]=e;return t})));let c=!1;var r,o;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(qb.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(qb.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await Lv(this,Jb.RequestMuteLocal,d);const l="video"===e.trackMediaType?sw.MUTE_LOCAL_VIDEO:sw.MUTE_LOCAL_AUDIO;await Lv(this,Jb.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==zb.Connected)return void i(new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnmuteMessage(r),s="video"===e.trackMediaType?sw.UNMUTE_LOCAL_VIDEO:sw.UNMUTE_LOCAL_AUDIO;await Lv(this,Jb.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUpdateVideoEncoder",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const i=this.localTrackMap.get(qb.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==zb.Connected)return void t();const{id:r,track:o}=i;r&&(await this.sendConnection.updateSendParameters(r,o),await this.sendConnection.updateEncoderConfig(r,o),this.emit(Jb.UpdateVideoEncoder,o)),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(qb.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==zb.Connected)return void t();const{id:r,track:o}=i;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;Jy.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==zb.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),i[0]===qb.LocalVideoTrack&&LD().supportDualStreamEncoding){const t=this.localTrackMap.get(qb.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),ng(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),ng(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),ng(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),ng(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new $x(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),Oy("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(Jy.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Mx(e,this.store,Eb.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=zb.New,this.sendConnection&&(Jy.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Mx(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new iv(tv.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=zb.Connected}async addRemoteCandidate(e,t){if(t===Eb.RECEIVE_ONLY){if(!this.sendConnection)throw new iv(tv.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new iv(tv.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return XU((function*(){const r=yield jU(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==zb.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,FU.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield jU(n.tryToUnmuteAudio(e)));o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===qb.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(o);const s=yield jU(n.sendConnection.send(o.map((e=>{let{track:t}=e;return t})),n.store.codec,n.store.audioCodec)),a=(yield jU(s.next())).value,c=n.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===tv.WS_ABORT&&o.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(o),e}yield jU(s.next()),o.forEach((e=>{let{type:t}=e;n.statsCollector.addLocalStats(t)})),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(o,a),o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===qb.LocalAudioTrack?"audio":"video",void 0,r)})),n.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==zb.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Dn(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===zb.Connected){if(i){i[1].track.close()}return n}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((i=>{let[n,{track:r,ssrcs:o}]=i;const s={stream_type:iV(r,n),ssrcs:o};r._muted||!r._enabled?e.push(s):t.push(s)})),e.length>0&&e.forEach((e=>{Lv(this,Jb.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{Lv(this,Jb.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return XU((function*(){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(Jy.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Pv(this,Jb.RequestRePublish,this.pendingLocalTracks),this.emit(Jb.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new iv(tv.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:o,mid:s,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===Hb.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new oM(o,e.uid,e._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new rM(o,e.uid,e._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,s):this.remoteUserMap.set(e,new Map([[t,s]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(Jb.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new iv(tv.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n)}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===Hb.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===Hb.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===Hb.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===Hb.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===Hb.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),r.forEach((e=>{let[,{kind:t}]=e;Lv(this,Jb.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[Hb.VIDEO,Hb.AUDIO].forEach((e=>{t.has(e)?Lv(this,Jb.RequestP2PUnmuteRemote,e):Lv(this,Jb.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new iv(tv.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===Hb.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||Jy.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(qb.LocalAudioTrack);if((null==t?void 0:t.track)instanceof ik){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==qb.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===qb.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===qb.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(qb.LocalAudioTrack),o=n?this.localTrackMap.get(qb.LocalVideoLowTrack):this.localTrackMap.get(qb.LocalVideoTrack);rA.publish(this.store.sessionId,{eventElapse:FU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(ZD.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find((e=>e instanceof $L)),a=n?null===(o=this.localTrackMap.get(qb.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof Gk));rA.publish(this.store.sessionId,{eventElapse:FU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(ZD.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===Hb.VIDEO?i._videoSSRC:i._audioSSRC;r&&rA.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===Hb.VIDEO,audio:n===Hb.AUDIO,peerid:i.uid,subscribeRequestid:n===Hb.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:FU.measureFromSubscribeStart(this.store.clientId,r)})}reset(){Jy.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new ly("P2PChannel2-send-mutex"),this.sendMutex=new ly("P2PChannel2-recv-mutex"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(qb.LocalAudioTrack);if((null==e?void 0:e.track)instanceof ik){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=zb.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(qb.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(qb.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Gk||t&&t.track instanceof $L?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(qb.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=oE(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(Jy.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=zb.Reconnecting,Oy("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case qb.LocalVideoTrack:Dn(t=n._hints).call(t,ZD.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case qb.LocalAudioTrack:n instanceof ik?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case qb.LocalVideoLowTrack:}})),this.emit(Jb.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(Jb.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),Jy.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof eV?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,n;if(e===Eb.SEND_ONLY){if(!this.sendConnection)throw new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection}else{if(!this.recvConnection)throw new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e}{const e=await n.restartICE();if(e){const t=await Pv(this,Jb.RequestP2PRestartICE,{direction:Eb.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(qb.LocalVideoTrack),i=this.localTrackMap.get(qb.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!r)return 1;const o=kv(this,Jb.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(ZD.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return aA[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=kv(this,Jb.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Gh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=LD(),o=this.getAllTracks();e=Vv(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof Gk&&(this.localTrackMap.has(qb.LocalVideoTrack)||s?new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:qb.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:qb.LocalVideoLowTrack})}if(o instanceof $L){const e=this.localTrackMap.get(qb.LocalAudioTrack);if(e){if(!(e.track instanceof ik))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===qb.LocalAudioTrack}));if(!(e.track instanceof ik))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof ik||o._bypassWebAudio)n.push({track:o,type:qb.LocalAudioTrack});else{const e=new ik;e.addAudioTrack(o),n.push({track:e,type:qb.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=Vv(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof $L){const e=this.localTrackMap.get(qb.LocalAudioTrack);if(!e)continue;e.track instanceof ik?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([qb.LocalAudioTrack,e]),e.track.close())):t.push([qb.LocalAudioTrack,e])}if(i instanceof Gk){const e=this.localTrackMap.get(qb.LocalVideoTrack);if(!e)continue;t.push([qb.LocalVideoTrack,e]);const i=this.localTrackMap.get(qb.LocalVideoLowTrack);i&&t.push([qb.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case qb.LocalVideoTrack:t.addListener(QD.GET_STATS,this.handleGetLocalVideoStats),t.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(QD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(QD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case qb.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case qb.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof ik?e.trackList.forEach((e=>{e.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(QD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(QD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case qb.LocalVideoTrack:t.off(QD.GET_STATS,this.handleGetLocalVideoStats),t.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(QD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(QD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case qb.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case qb.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof ik?e.trackList.forEach((e=>{e.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(QD.GET_STATS,this.handleGetLocalAudioStats),e.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(QD.GET_STATS,this.handleGetLocalAudioStats),e.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof rM&&t.addListener(QD.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof oM&&t.addListener(QD.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(QD.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(Hb.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(Hb.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,{track:o,type:s}=e;switch(s){case qb.LocalAudioTrack:r=Lb.Audio;break;case qb.LocalVideoTrack:r=Dn(n=o._hints).call(n,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:r=Lb.Low}return{kind:s===qb.LocalAudioTrack?Hb.AUDIO:Hb.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(Jb.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),Dn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&await Qv(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),rA.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Rv.TRACER}).onSuccess(),this.emit(Jb.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(rP.FIRST_FRAME_DECODED),rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_AUDIO_DECODE,eA.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_AUDIO_RECEIVED,eA.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_VIDEO_RECEIVED,eA.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(Jb.ConnectionTypeChange,i),Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Vw(t))," -> ").concat(JSON.stringify(Vw(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Vw(t))," -> ").concat(JSON.stringify(Vw(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(Jb.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===Eb.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,Jy.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===Eb.SEND_ONLY?this.restartICE(e):Pv(this,Jb.RequestP2PRestartICE,{direction:Eb.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(qb.LocalAudioTrack);if(e instanceof $L&&(null==i?void 0:i.track)instanceof ik)return i.track.isActive||t.push([qb.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===qb.LocalVideoTrack)){const e=this.localTrackMap.get(qb.LocalVideoLowTrack);e&&t.push([qb.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(qb.LocalAudioTrack);if(e instanceof $L&&(null==i?void 0:i.track)instanceof ik)return i.track.isActive&&t.push([qb.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===qb.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(qb.LocalVideoLowTrack);e&&t.push([qb.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case Hb.VIDEO:return void(i._videoSSRC&&t.push({stream_type:Hb.VIDEO,ssrcId:i._videoSSRC}));case Hb.AUDIO:return void(i._audioSSRC&&t.push({stream_type:Hb.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(qb.LocalVideoTrack),i=this.localTrackMap.get(qb.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;tthis.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>{let[,{ssrcs:t}]=e;return!!t})),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(Jb.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(Jb.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await Qv(py(this.dtlsFailedCount,hy)),this.emit(Jb.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(qb.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof Gk))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof Gk)).length>1)throw new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof $L)).length>1&&(e.some((e=>e instanceof $L&&e._bypassWebAudio))||!LD().webAudioMediaStreamDest))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Gk&&this.pendingLocalTracks.some((e=>e instanceof Gk)))throw new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof $L&&this.pendingLocalTracks.some((e=>e instanceof $L))&&(!LD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof $L&&e._bypassWebAudio))))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding,n=TV(TV({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():xx(e,n);const o=Zv(8,"track-low-"),s=new Gk(r,TV(TV({},i&&{scaleResolutionDownBy:xw(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(iP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,$D.LOW_STREAM)})),s._hints.push(ZD.LOW_STREAM),e.addListener(QD.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(d_(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));rA.firstRemoteVideoDecode(this.store.sessionId,$y.FIRST_VIDEO_DECODE,eA.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==i}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new iv(tv.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new iv(tv.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new iv(tv.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new iv(tv.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new iv(tv.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new iv(tv.NOT_SUPPORTED)}async preConnect(e){throw new iv(tv.NOT_SUPPORTED)}getEstablishParams(){throw new iv(tv.NOT_SUPPORTED)}async reSubscribe(e){throw new iv(tv.NOT_SUPPORTED)}async updateVideoStreamParameter(e,t){throw new iv(tv.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===qb.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,$D.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},ib(fV.prototype,"p2pConnect",[oV],Object.getOwnPropertyDescriptor(fV.prototype,"p2pConnect"),fV.prototype),ib(fV.prototype,"unpublish",[sV],Object.getOwnPropertyDescriptor(fV.prototype,"unpublish"),fV.prototype),ib(fV.prototype,"unpublishLowStream",[aV],Object.getOwnPropertyDescriptor(fV.prototype,"unpublishLowStream"),fV.prototype),ib(fV.prototype,"subscribe",[cV],Object.getOwnPropertyDescriptor(fV.prototype,"subscribe"),fV.prototype),ib(fV.prototype,"mockSubscribe",[dV],Object.getOwnPropertyDescriptor(fV.prototype,"mockSubscribe"),fV.prototype),ib(fV.prototype,"unsubscribe",[lV],Object.getOwnPropertyDescriptor(fV.prototype,"unsubscribe"),fV.prototype),ib(fV.prototype,"muteRemote",[uV],Object.getOwnPropertyDescriptor(fV.prototype,"muteRemote"),fV.prototype),ib(fV.prototype,"unmuteRemote",[hV],Object.getOwnPropertyDescriptor(fV.prototype,"unmuteRemote"),fV.prototype),ib(fV.prototype,"hasRemoteMediaWithLock",[pV],Object.getOwnPropertyDescriptor(fV.prototype,"hasRemoteMediaWithLock"),fV.prototype),ib(fV.prototype,"disconnectForReconnect",[_V],Object.getOwnPropertyDescriptor(fV.prototype,"disconnectForReconnect"),fV.prototype),ib(fV.prototype,"remoteMediaSsrcChanged",[EV],Object.getOwnPropertyDescriptor(fV.prototype,"remoteMediaSsrcChanged"),fV.prototype),fV);function gV(e){return function(t,i,n){const r=t[i];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),o=0;o{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new xU,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(qb.LocalAudioTrack)||CV({},aP)}getLocalVideoTrackStats(){return this.localStats.get(qb.LocalVideoTrack)||CV({},cP)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(qb.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(qb.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(qb.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?FU.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?FU.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&Jy.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case qb.LocalVideoTrack:case qb.LocalVideoLowTrack:{const t=n,o=CV({},cP),s=e.getStats(),a=e.getLocalMedia(i);if(s){const i=s.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(qb.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(o.codecType=i.codec),o.sendBytes=i.bytes,o.sendBitrate=t?8*Math.max(0,o.sendBytes-t.sendBytes):0,i.inputFrame?(o.captureFrameRate=i.inputFrame.frameRate,o.captureResolutionHeight=i.inputFrame.height,o.captureResolutionWidth=i.inputFrame.width):n&&(o.captureResolutionWidth=n.width,o.captureResolutionHeight=n.height),i.sentFrame?(o.sendFrameRate=i.sentFrame.frameRate,o.sendResolutionHeight=i.sentFrame.height,o.sendResolutionWidth=i.sentFrame.width):n&&(o.sendResolutionWidth=n.width,o.sendResolutionHeight=n.height),i.avgEncodeMs&&(o.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(o.targetSendBitrate=1e3*r.bitrateMax),o.sendPackets=i.packets,o.sendPacketsLost=i.packetsLost,o.sendJitterMs=i.jitterMs,o.sendRttMs=i.rttMs,o.totalDuration=t?t.totalDuration+1:1,o.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(o.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(Jy.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(o.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;if(this.localStats.set(i,o),(null==t?void 0:t.sendResolutionWidth)!==o.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==o.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:o.sendResolutionWidth,height:o.sendResolutionHeight});o&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,o);break}case qb.LocalAudioTrack:{const t=n,r=CV({},aP),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(qb.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let[r,{videoStats:o,audioStats:s,videoPcStats:a}]=t;const c=s,d=o,l=a,u=CV({},dP),h=CV({},uP),p=CV({},lP),{audioTrack:_,videoTrack:E,audioSSRC:f,videoSSRC:m}=e.getRemoteMedia(r);let T;T=e instanceof SV?e.getStats(!0):e.getStats();const S=null===(i=T)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===f)),g=null===(n=T)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===m)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(S&&("opus"!==S.codec&&"aac"!==S.codec&&"PCMU"!==S.codec&&"PCMA"!==S.codec&&"G722"!==S.codec||(u.codecType=S.codec),S.outputLevel?u.receiveLevel=Math.round(32767*S.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=S.bytes,u.receivePackets=S.packets,u.receivePacketsLost=S.packetsLost,u.receivePacketsDiscarded=S.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=S.jitterBufferMs,u.totalDuration>10&&IV.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),g){"H264"!==g.codec&&"H265"!==g.codec&&"VP8"!==g.codec&&"VP9"!==g.codec&&"AV1X"!==g.codec&&"AV1"!==g.codec||(h.codecType=g.codec),h.receiveBytes=g.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,h.renderFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,g.outputFrame&&(h.renderFrameRate=g.outputFrame.frameRate),g.receivedFrame?(h.receiveFrameRate=g.receivedFrame.frameRate,h.receiveResolutionHeight=g.receivedFrame.height,h.receiveResolutionWidth=g.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==g.framesRateFirefox&&(h.receiveFrameRate=Math.round(g.framesRateFirefox)),h.receivePackets=g.packets,h.receivePacketsLost=g.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.receiveDelay=g.jitterBufferMs||0;const t=!!m&&e.getRemoteVideoIsReady(m);E&&t&&IV.isRemoteVideoFreeze(E,g,l)&&(h.totalFreezeTime+=1),h.freezeRate=h.totalFreezeTime/h.totalDuration}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:u,videoStats:h,videoPcStats:g,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h)}))}}class vV{constructor(){ng(this,"destChannelMediaInfos",new Map),ng(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){wb(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){wb(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Tb(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function yV(e){if(!(e instanceof vV)){return new mb(tv.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new mb(tv.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new mb(tv.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}function AV(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new BU(n=new YU((function(i){i(e[t](n))})),1)}}return t[void 0!==ZS&&$S||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e)}),t}var bV=i(qU);function wV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function OV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(Ly)).call(t,e)})))]}constructor(t,i){super(t,i),ng(this,"store",void 0),ng(this,"peerConnection",void 0),ng(this,"remoteSDP",void 0),ng(this,"initialOffer",void 0),ng(this,"statsFilter",void 0),ng(this,"useRTX",!1),ng(this,"localCapabilities",void 0),ng(this,"localCandidateCount",0),ng(this,"allCandidatesReceived",!1),ng(this,"establishPromise",void 0),ng(this,"mutex",new ly("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=Ox(this.peerConnection,Oy("STATS_UPDATE_INTERVAL"),void 0,PI()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=yM(e.sdp),i=vM(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:Oy("FILTER_VIDEO_FEC"),filterAudioFec:Oy("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,PV(PV({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new iv(tv.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{constructor(e){ng(this,"sessionDesc",void 0),ng(this,"localCapabilities",void 0),ng(this,"rtpCapabilities",void 0),ng(this,"candidates",void 0),ng(this,"iceParameters",void 0),ng(this,"dtlsParameters",void 0),ng(this,"setup",void 0),ng(this,"currentMidIndex",void 0),ng(this,"cname",void 0),e=Bv(e);const{iceParameters:t,dtlsParameters:i,candidates:n,rtpCapabilities:r,setup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=gM.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=s,this.cname=c;for(let e=0;ee.payloadType.toString(10)));let e=r.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,a)}));0===e.length&&(e=r.videoCodecs),s.attributes.payloads=e,s.attributes.extmaps=r.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),s.attributes.payloads=r.audioCodecs,s.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return gM.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=OM(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===Hb.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(r),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{Dn(e).call(e,t.attributes.label||"")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Dn(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){e===Kb.TCP?this.candidates.forEach((e=>{-1===this.candidates.findIndex((t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this.candidates.push(OV(OV({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})):this.candidates=this.candidates.filter((e=>"tcp"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=Bv(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;it.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===Hb.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i))}}mungMediaDesc(e){const t=Bv(e);return DM(t),function(e){const t=e.attributes.extmaps.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}(PV(PV({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new iv(tv.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var i=this;return XU((function*(){const n=yield jU(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map((e=>i.peerConnection.addTrack(e._mediaStreamTrack))),o=yield jU(i.peerConnection.createOffer()),s=gM.parse(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{NI()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)})),e}const d=i.mungSendOfferSDP(o.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield jU(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield jU(i.applySendEncodings(r,e)),yield jU(i.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:a[t],id:i}}))}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{NI()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),o=new Gh(((t,n)=>{const o=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=n=>{const a=vI();if(("Safari"===a.name&&11===Number(a.version)||LI())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener("track",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:i}}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(NI()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(NI()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return XU((function*(){const i=yield jU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(LD().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===Kb.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(Jy.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===Kb.RELAY)return;e!==Kb.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield jU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=yM(n.sdp),{remoteIceParameters:o}=yield r.iceParameters;t.remoteSDP.restartICE(o);const s=t.remoteSDP.toString();yield jU(t.peerConnection.setLocalDescription(n)),yield jU(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){Jy.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e}));1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find((e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t}));i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new iv(tv.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new iv(tv.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Jy.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Jy.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),Oy("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(yv(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Oy("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id}))}if(!t)return Jy.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!LD().supportSetRtpSenderParameters)return Jy.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof Gk)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(Oy("DSCP_TYPE")&&JI()){var o;const e=Oy("DSCP_TYPE");Dn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(s,n),Jy.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!LD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&NM(r,e)})),gM.print(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let{id:n,mslabel:r}=t;const{kind:o}=e[i];return new Gh(((e,t)=>{const i=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=vI();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Gh.all(t)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(LD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},ib(NV.prototype,"connect",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"connect"),NV.prototype),ib(NV.prototype,"stopSending",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"stopSending"),NV.prototype),ib(NV.prototype,"receive",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"receive"),NV.prototype),ib(NV.prototype,"stopReceiving",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"stopReceiving"),NV.prototype),ib(NV.prototype,"muteRemote",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"muteRemote"),NV.prototype),ib(NV.prototype,"unmuteRemote",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"unmuteRemote"),NV.prototype),ib(NV.prototype,"muteLocal",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"muteLocal"),NV.prototype),ib(NV.prototype,"unmuteLocal",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"unmuteLocal"),NV.prototype),ib(NV.prototype,"close",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"close"),NV.prototype),ib(NV.prototype,"updateEncoderConfig",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"updateEncoderConfig"),NV.prototype),ib(NV.prototype,"updateSendParameters",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"updateSendParameters"),NV.prototype),ib(NV.prototype,"replaceTrack",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"replaceTrack"),NV.prototype),ib(NV.prototype,"getRemoteSSRC",[kV],Object.getOwnPropertyDescriptor(NV.prototype,"getRemoteSSRC"),NV.prototype),NV);function kV(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;se.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:l,ssrcGroups:u,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++o)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:c,ssrcGroups:d,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++o)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return gM.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=OM(t,this.cname,Oy("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(PI()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(NI()||function(){const e=vI();return!(e.name!==gI.CHROME||!e.osVersion)&&Number(e.version)<=90}())||0===t&&Oy("USE_SUB_RTX")||jI()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=Bv(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),PI()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||PI()||jI()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||gM.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n");this._rtpCapabilities=e;const i=this.rtpCapabilities.send,n=this.localCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(0===i.videoCodecs.length){const t=n.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"vp8")}))||[n.videoCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,Oy("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=OM([{ssrcId:VV,rtx:Oy("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType)if(0===i.audioCodecs.length){const t=n.audioCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"opus")}))||[n.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,BM(e),Oy("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=OM([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,this.sessionDesc}updateCandidates(e){const t=this._candidates.filter((e=>"udp"===e.transport));if(e===Kb.TCP){if(0===t.length)return;if(Oy("TCP_CANDIDATE_ONLY")){const e=this._candidates.filter((e=>"tcp"===e.transport));t.forEach((t=>{-1===e.findIndex((e=>e.connectionAddress===t.connectionAddress))&&e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}))})),this._candidates=e}else{const e=[];t.forEach((t=>{e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}))})),this._candidates=[...t,...e]}}else if(e===Kb.RELAY){if(0!==t.length)return;{const e=this._candidates.filter((e=>"tcp"===e.transport));e.forEach((e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}))})),this._candidates=[...t,...e]}}else if(0===t.length){this._candidates.filter((e=>"tcp"===e.transport)).forEach((e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}))})),this._candidates=t}else this._candidates=this._candidates.filter((e=>"tcp"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=Bv(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(PI()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:xV,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=jM(s,a,this.localCapabilities.send,s===Hb.VIDEO?n:r),d=s===Hb.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(Ly)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return Jy.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return Dn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t)}))));if(0===o.length)return Jy.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let a;if(Jy.debug("updateRemoteCodec, from ".concat(n," to ").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&Dn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return Jy.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(Oy("USE_PUB_RTX")||Oy("USE_SUB_RTX")){const e=GM(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=jM(Hb.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));Jy.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from ").concat(e.attributes.payloads," to ").concat(l)),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===Hb.VIDEO?o.videoCodecs:o.audioCodecs,a=e===Hb.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=Bv(e);return DM(n),NM(n,t),PM(n,t),LM(n),kM(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=Bv(e);return kM(i,t,this.localCapabilities.recv),BM(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>PI()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}function BV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function jV(e){for(var t=1;t=t.length-1&&n===WV.DOWN)return e;let o=jV(jV({},e),{},{scale:n===WV.DOWN?++r:--r});switch(i){case"maintain-framerate":o=jV(jV({},o),t[r].motion);break;case"maintain-resolution":o=jV(jV({},o),t[r].detail);break;case"balanced":o=jV(jV({},o),t[r].balanced)}return o}function YV(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:qV(t)};HV.set(e,i)}else HV.delete(e)}function qV(e){const t=jV({},e),{bitrateMax:i,frameRate:n,scaleResolutionDownBy:r,bitrateMin:o}=t,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:a,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:u,BWE_SCALE_DOWN_THRESHOLD:h,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:_,BALANCE_BITRATE_FACTOR:E,BALANCE_FRAMERATE_FACTOR:f,BALANCE_RESOLUTION_FACTOR:m,MOTION_RESOLUTION_FACTOR:T,MOTION_BITRATE_FACTOR:S,DETAIL_FRAMERATE_FACTOR:g,DETAIL_BITRATE_FACTOR:R}=yy,C=Math.min(t.frameRate,a),I=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(p,1)*C),fps_up:n},balanced:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(u,e)*i),bwe_down:Math.round(Math.pow(h,e+1)*i),fps_up:Math.round(Math.pow(_,e)*C),fps_down:Math.round(Math.pow(p,e+1)*C)},a={scaleResolutionDownBy:r/Math.pow(m,e),frameRate:Math.max(Math.round(Math.pow(f,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:r/Math.pow(T,e),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(S,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(S,e)*o),d)},v={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(g,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(R,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};I.push({scale:e,threshold:t,balanced:a,motion:c,detail:v})}return I}function zV(e,t,i,n,r,o){const s=HV.get(e)||{overUse:0,underUse:0,adaptationList:qV(r)},{adaptationList:a}=s;HV.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=yy,{scale:l}=n;let u,h;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let{threshold:{fps_down:r}}=i[t];return Oy("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[0].threshold.fps_down),ec)||"number"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;const{threshold:{bwe_down:n}}=i[t];return ec)?(s.overUse=0,s.underUse=0,u=KV(n,a,o,WV.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let{threshold:{fps_up:r}}=i[t];return Oy("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,i){if(0===t)return;const{threshold:{bwe_up:n}}=i[t];return e>n}(i,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=KV(n,a,o,WV.UP),0===u.scale&&(h=GV.NONE))),[u,h])}function JV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function XV(e){for(var t=1;t=e}(14)&&VI(17,4,!0)||xI(14)&&FI(17,4,!0))))}const ZV=new Map;function $V(e,t){const i=ZV.get(e);if(i){const{timer:t}=i;window.clearTimeout(t),ZV.delete(e)}t.qualityLimitationReason=GV.NONE,YV(e)}var eF;function tF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function iF(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(Ly)).call(t,e)})))]}constructor(t,i){super(t,i),ng(this,"store",void 0),ng(this,"peerConnection",void 0),ng(this,"id",Zv(5,"connection-")),ng(this,"remoteSDP",void 0),ng(this,"initialOffer",void 0),ng(this,"transportEventReceiver",void 0),ng(this,"statsFilter",void 0),ng(this,"extension",{useXR:Oy("USE_XR")}),ng(this,"localCapabilities",void 0),ng(this,"remoteCodecs",void 0),ng(this,"localCandidateCount",0),ng(this,"allCandidatesReceived",!1),ng(this,"isPreallocation",!1),ng(this,"preSSRCMap",new Map),ng(this,"dataStreamChannelMap",new Map),ng(this,"establishPromise",void 0),ng(this,"recoveredDataChannelIds",[]),ng(this,"currentDataChannelId",1),ng(this,"mutex",new ly("P2PConnection-mutex")),ng(this,"qualityLimitationReason",GV.NONE),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=Ox(this.peerConnection,Oy("STATS_UPDATE_INTERVAL"),void 0,PI()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}getPreMedia(e){const t=this.preSSRCMap.get(e);if(void 0!==t){const e=this.peerConnection.getTransceivers().find((e=>e.mid===t));if(e)return{transceiver:e,track:e.receiver.track,id:t}}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void Jy.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else Jy.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=yM(e.sdp),i=await UM({filterRTX:!Oy("USE_PUB_RTX")&&!Oy("USE_SUB_RTX"),filterVideoFec:Oy("FILTER_VIDEO_FEC"),filterAudioFec:Oy("FILTER_AUDIO_FEC"),filterVideoCodec:Oy("FILTER_VIDEO_CODEC")},this.extension);return this.localCapabilities=FM(i),this.initialOffer=e,iF(iF({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new iv(tv.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new FV(iF(iF({},e),{},{localCapabilities:this.localCapabilities})),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const t=this.remoteSDP.toString(),i=HM(this.initialOffer.sdp,this.extension),n=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==n||n(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const r=this.peerConnection.getTransceivers()[0];if(null!=r&&r.receiver&&this.tryBindTransportEvents(r.receiver),Oy("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia(Oy("PRELOAD_MEDIA_COUNT"));const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}const{preSSRCs:o}=e;if(Array.isArray(o)&&o.length>0){const{mids:e}=this.remoteSDP.batchSend(o.map((e=>({kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(o[t].ssrcId,e)})),await WM(this.peerConnection,this.remoteSDP,this.extension),Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] pre-batchReceive exchange SDP."))}}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");const{rtpCapabilities:t}=e;this.remoteSDP.updateRemoteRTPCapabilities(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const{preSSRCs:i}=e;if(Array.isArray(i)&&i.length>0){const{mids:e}=this.remoteSDP.batchSend(i.map((e=>Object.assign({},{kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(i[t].ssrcId,e)}))}await WM(this.peerConnection,this.remoteSDP,this.extension),Jy.debug("[P2PConnection] updateRemoteRTPCapabilities by exchanging SDP.")}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return XU((function*(){const r=yield jU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)})),PI()&&!0===Oy("SIMULCAST")&&(yield jU(n.applySimulcastForFirefox(o,e)));const s=yield jU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=gM.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return AM(t,Oy("USE_PUB_RTX"))}));let u;try{u=yield l}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const o=n.remoteSDP.toString();throw yield jU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield jU(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield jU(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield jU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield jU(n.applySimulcastEncodings(o,e)),yield jU(n.applySendEncodings(o,e)),null==p||p(h),yield jU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),o.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof iv?e:new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)Jy.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:Oy("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),Jy.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else Jy.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof iv?e:new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof iv?e:new iv(tv.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;$V(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);o&&(await WM(this.peerConnection,this.remoteSDP,this.extension),Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:r,transceiver:s}}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await WM(this.peerConnection,this.remoteSDP,this.extension),Jy.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preSSRCMap.entries()).some((t=>{let[i,n]=t;if(n===e)return this.preSSRCMap.delete(i),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return XU((function*(){const i=yield jU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(LD().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===Kb.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(Jy.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===Kb.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield jU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=yM(n.sdp),{remoteIceParameters:o}=yield r.iceParameters;t.remoteSDP.restartICE(o);const s=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield jU(t.peerConnection.setLocalDescription(n)),null==a||a(s),yield jU(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){Jy.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{$V(this.id+e.mid,this)})),this.preSSRCMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return iF(iF({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new iv(tv.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?PI()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:iF(iF({},px),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:iF(iF({},px),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Jy.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Jy.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),Oy("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(yv(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Oy("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Oy("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),Oy("ENABLE_ENCODED_TRANSFORM")&&LD().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Nw(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!Oy("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();Jy.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,n;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return Jy.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return Jy.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!LD().supportSetRtpSenderParameters)return Jy.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;case"balanced":r.degradationPreference="balanced"}const s=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack),a=dL(e);if(QV(e)&&s&&t&&a&&this.getLocalVideoStats&&Dn(i=["vp8","vp9"]).call(i,this.store.codec)){var c;const i=r.degradationPreference||(Dn(c=e._hints).call(c,ZD.CUSTOM_TRACK)?Oy("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");!function(e,t,i,n,r,o){if($V(e,i),r(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;YV(e,t);const a=window.setInterval((()=>{const a=ZV.get(e);if(!Oy("ENABLE_AG_ADAPTATION")||!a)return $V(e,i),void r(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,[l,u]=zV(e,o,d,a.adaptationConfig,t,n);u&&(i.qualityLimitationReason=u),l&&a.adaptationConfig.scale!==l.scale&&(Jy.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(l.scale," ")),a.adaptationConfig=XV(XV({},a.adaptationConfig),l),r(l))}}),Oy("CHECK_LOCAL_STATS_INTERVAL")),c=XV({},t);ZV.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),Jy.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}(this.id+s.mid,a,this,i,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(o.maxBitrate=1e3*t),(Dn(d=e._hints).call(d,ZD.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=Pw(i)),n&&n>=1&&(o.scaleResolutionDownBy=n))}const{maxFramerate:l}=Oy("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),Oy("DSCP_TYPE")&&JI()){var u;const e=Oy("DSCP_TYPE");Dn(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(n=h.encodings)||void 0===n?void 0:n[0];PI()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),Jy.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await async function(e,t,i){try{var n;if(!LD().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e}(e)||!Oy("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];o.scalabilityMode=RM(i),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),Jy.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){Jy.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,Oy("SVC_MODE"))}async updateAdaptation(e,t){var i,n;if(!e)return Jy.debug("[updateAdaptation] no rtpSender found");if(!LD().supportSetRtpSenderParameters)return Jy.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},{bitrateMax:o,frameRate:s,scaleResolutionDownBy:a}=t;o&&(r.maxBitrate=1e3*o),s&&(r.maxFramerate=Pw(s)),a&&a>=1&&Dn(i=["vp8","vp9"]).call(i,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(n=c.encodings)||void 0===n?void 0:n[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),Jy.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?Jy.debug("[updateAdaptation] peerConnection not connected}"):Jy.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):Jy.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!LD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(NM(o,e),MM(o,e,this.store.codec))})),gM.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!PI()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Oy("SDP_LOGGING"))return Jy.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(LD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},ib(eF.prototype,"updateRemoteRTPCapabilities",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"updateRemoteRTPCapabilities"),eF.prototype),ib(eF.prototype,"connect",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"connect"),eF.prototype),ib(eF.prototype,"updateRemoteConnect",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"updateRemoteConnect"),eF.prototype),ib(eF.prototype,"createDataChannels",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"createDataChannels"),eF.prototype),ib(eF.prototype,"receive",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"receive"),eF.prototype),ib(eF.prototype,"batchReceive",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"batchReceive"),eF.prototype),ib(eF.prototype,"stopReceiving",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"stopReceiving"),eF.prototype),ib(eF.prototype,"muteRemote",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"muteRemote"),eF.prototype),ib(eF.prototype,"unmuteRemote",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"unmuteRemote"),eF.prototype),ib(eF.prototype,"muteLocal",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"muteLocal"),eF.prototype),ib(eF.prototype,"unmuteLocal",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"unmuteLocal"),eF.prototype),ib(eF.prototype,"close",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"close"),eF.prototype),ib(eF.prototype,"updateEncoderConfig",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"updateEncoderConfig"),eF.prototype),ib(eF.prototype,"updateSendParameters",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"updateSendParameters"),eF.prototype),ib(eF.prototype,"replaceTrack",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"replaceTrack"),eF.prototype),ib(eF.prototype,"updateAdaptation",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"updateAdaptation"),eF.prototype),ib(eF.prototype,"getRemoteSSRC",[rF],Object.getOwnPropertyDescriptor(eF.prototype,"getRemoteSSRC"),eF.prototype),eF);function rF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==zb.Connected)return void i(new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){o[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(r);await Lv(this,Jb.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==zb.Connected)return void i(new iv(tv.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const t=o[1];if(t.track._originMediaStreamTrack.stop(),!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=xx(e,Mv(this,Jb.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Gh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r);await Lv(this,Jb.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUpdateVideoEncoder",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(qb.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==zb.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),await this.connection.updateEncoderConfig(r,o),this.emit(Jb.UpdateVideoEncoder,o),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(qb.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==zb.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),ng(this,"handleReplaceMixingTrack",(async(e,t,i,n)=>{if(!this.connection||this.state!==zb.Connected)return void t();const r=rV([e]);let o;Jy.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof n&&n||(o=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t()}catch(e){i(e)}finally{var s;null===(s=o)||void 0===s||s()}})),ng(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;Jy.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==zb.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===qb.LocalVideoTrack&&!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding){const t=this.localTrackMap.get(qb.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),ng(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),ng(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),ng(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),ng(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),ng(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new $x(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!LD().supportUnifiedPlan||Oy("CHROME_FORCE_PLAN_B")&&JI(),this.shouldForwardP2PCreation=Oy("FORWARD_P2P_CREATION")&&LD().supportPCSetConfiguration&&zI(),this.shouldForwardP2PCreation&&(this.connection=this.isPlanB?new LV({},this.store):new nF({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e){var t;this.state=zb.New;const i=this.shouldForwardP2PCreation&&"closed"===(null===(t=this.connection)||void 0===t?void 0:t.peerConnectionState);if(this.shouldForwardP2PCreation&&!i||(i&&this.connection&&(Jy.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.isPlanB?new LV(e,this.store):new nF(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new iv(tv.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=Oy("NEW_ICE_RESTART")?Yb.FIRST_CONNECTION:Yb.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e){if(!this.connection)throw new iv(tv.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");Oy("ENABLE_PREALLOC_PC")&&this.state===zb.Connected?await this.connection.updateRemoteConnect(e):(this.store.peerConnectionStart(),await this.connection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=zb.Connected)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[i]=e;return Dn(t=[qb.LocalVideoLowTrack,qb.LocalVideoTrack]).call(t,i)})),i=t.map((e=>{let[,{id:t}]=e;return t})),n=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof nF){if(rA.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Dn(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Dn(e).call(e,t)));t&&(this.store.codec=t,Jy.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){var e;if(this.connection instanceof nF&&"closed"!==this.connection.peerConnectionState&&Dn(e=[zb.New,zb.Connected]).call(e,this.state))return this.connection.establishPromise}async publishDataChannel(e){if(!this.connection||this.state!==zb.Connected){if(this.state===zb.Disconnected)throw new iv(tv.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Dn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,i){var n=this;return XU((function*(){const r=yield jU(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==zb.Connected){if(n.state===zb.Disconnected)throw new iv(tv.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,FU.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield jU(n.tryToUnmuteAudio(e)));yield*AV(cF(n.doPublish(n.connection,o)))}finally{r()}}))()}doPublish(e,t){var i=this;return XU((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===qb.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),r=yield jU(e.send(t.map((e=>{let{track:t}=e;return t})),i.store.codec,i.store.audioCodec)),o=(yield jU(r.next())).value,s=i.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===tv.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(s,a),d=(yield jU(r.next(c))).value,l=Oy("ENABLE_VIDEO_SEI");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===Hb.VIDEO?await EM(t.sender,e):e.trackMediaType===Hb.AUDIO&&await async function(e){if(!LD().supportWebRTCEncodedTransform)return void Jy.warning("browser not support audio encoded transform");if(uM.has(e))return;if(!e.track)return;const t={track:e.track};if(OI()){if(!e.createEncodedStreams)return void Jy.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}catch(e){return void Jy.error("create audio-encoded-streams error",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(Jy.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(NI()){if("undefined"==typeof RTCRtpScriptTransform)return void Jy.warning("browser not support RTCRtpScriptTransform");const n=lM(),r=new MessageChannel;await new Gh((e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(n,{name:"tx",port:r.port2},[r.port2]);e.transform=o,await new Gh((e=>n.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(Jy.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i))},t.worker=n}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=uM.get(e);if(t){uM.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){Jy.warning(e&&e.message)}}}uM.set(e,t),e.track.addEventListener("ended",i)}(t.sender))})),t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===qb.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof Gk))return Jy.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof nF||this.connection instanceof LV))return Jy.warn("[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=xw(e,t)),i.maxFramerate=e.framerate?Pw(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==qb.LocalVideoLowTrack||!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return Jy.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Pw(t.width)),t.height&&(i.height=Pw(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=PP((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),Pw(t.framerate)))}(t,e)}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&"object"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),Jy.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return XU((function*(){if(!t.connection||t.state!==zb.Connected)return;const i=yield jU(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(qb.LocalVideoTrack);if(!r)throw new iv(tv.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(qb.LocalVideoLowTrack))throw new iv(tv.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:qb.LocalVideoLowTrack}];if(yield*AV(cF(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(qb.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield jU(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(Jy.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Pv(this,Jb.RequestRePublish,this.pendingLocalTracks),this.emit(Jb.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(Jy.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await Pv(this,Jb.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==Hb.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==Hb.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await Pv(this,Jb.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===Hb.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(Jb.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==zb.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==zb.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==zb.Connected)return;const e=this.localTrackMap.get(qb.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[qb.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==zb.Connected)throw new iv(tv.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var o;if(!this.connection||this.state!==zb.Connected)throw new iv(tv.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c;const d=this.connection.getPreMedia(i);if(d)Jy.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=d.transceiver,s=d.track,a=d.id;else if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new iv(tv.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof nF&&(c=n.transceiver),s=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof nF&&(c=r.transceiver),s=r.track,a=r.id}t===Hb.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new oM(s,e.uid,e._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new rM(s,e.uid,e._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),Oy("ENABLE_VIDEO_SEI")&&c&&(t==Hb.VIDEO?await async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!LD().supportWebRTCEncodedTransform)return void Jy.warning("browser not support video encoded transform");if(!e.track)return;if(fM.has(e)){const i=fM.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(OI()){if(!e.createEncodedStreams)return void Jy.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams()}catch(e){return void Jy.error("create video-encoded-streams error",e&&e.message)}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(Jy.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const o=function(e){const t=new DataView(e.data);let i=0;for(;i+4t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"rx",port:r.port2},[r.port2]);e.transform=o,await new Gh((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(Jy.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}!function(e){const t=fM.get(e);if(t){fM.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){Jy.warning(e&&e.message)}}}(e)}fM.set(e,i),e.track.addEventListener("ended",n)}(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t)}}):t==Hb.AUDIO&&await async function(e){if(!LD().supportWebRTCEncodedTransform)return void Jy.warning("browser not support audio encoded transform");if(hM.has(e))return;const t={track:e.track};if(OI()){if(!e.createEncodedStreams)return void Jy.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}catch(e){return void Jy.error("create audio-encoded-streams error",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(Jy.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(NI()){if("undefined"==typeof RTCRtpScriptTransform)return void Jy.warning("browser not support RTCRtpScriptTransform");const n=lM(),r=new MessageChannel;await new Gh((e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(n,{name:"rx",port:r.port2},[r.port2]);e.transform=o,await new Gh((e=>n.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(Jy.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i))},t.worker=n}function i(){e.track.removeEventListener("ended",i),function(e){const t=hM.get(e);if(t){hM.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){Jy.warning(e&&e.message)}}}(e)}hM.set(e,t),e.track.addEventListener("ended",i)}(c.receiver));const l=this.remoteUserMap.get(e);l?l.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==u&&(this.pendingRemoteTracks.splice(u,1),this.emit(Jb.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==zb.Connected)throw new iv(tv.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=[],i=new Map;e.forEach((e=>{if(!this.connection)return;const n=this.connection.getPreMedia(e.ssrcId);n?i.set(e.ssrcId,n):t.push(e)}));const n=await this.connection.batchReceive(t.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{i.set(e.ssrcId,n[t])})),e.forEach((e=>{let{user:t,mediaType:n,ssrcId:r}=e;const o=i.get(r);if(!o)return void Jy.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(t.uid," subscribe data,").concat(n,", ").concat(r));const{track:s,id:a,transceiver:c}=o;n===Hb.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(s):(t._audioTrack=new oM(s,t.uid,t._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),c&&t._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(s):(t._videoTrack=new rM(s,t.uid,t._uintid,this.store),Jy.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),c&&t._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(t,t._videoTrack));const d=this.remoteUserMap.get(t);d?d.set(n,a):this.remoteUserMap.set(t,new Map([[n,a]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex((e=>{let{user:i,kind:r}=e;return i.uid===t.uid&&n===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(Jb.MediaReconnectEnd,t.uid))}))}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===zb.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===Hb.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===Hb.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==zb.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===Hb.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===Hb.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===Hb.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==zb.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===Hb.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===Hb.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=Jn(e).call(e,((e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,r;i===Hb.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===Hb.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===Hb.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),n}isPreSubScribe(e){if(!this.connection||this.state!==zb.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===Hb.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void Jy.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||Jy.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(qb.LocalAudioTrack);if((null==t?void 0:t.track)instanceof ik){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==qb.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===qb.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===qb.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(qb.LocalAudioTrack),o=n?this.localTrackMap.get(qb.LocalVideoLowTrack):this.localTrackMap.get(qb.LocalVideoTrack);rA.publish(this.store.sessionId,{eventElapse:FU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(ZD.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find((e=>e instanceof $L)),a=n?null===(o=this.localTrackMap.get(qb.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof Gk));rA.publish(this.store.sessionId,{eventElapse:FU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(ZD.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===Hb.VIDEO?i._videoSSRC:i._audioSSRC;r&&rA.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===Hb.VIDEO,audio:n===Hb.AUDIO,peerid:i.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:FU.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){Jy.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new ly("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.isPlanB?new LV({},this.store):new nF({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(qb.LocalAudioTrack);if((null==e?void 0:e.track)instanceof ik){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=zb.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(qb.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(qb.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Gk||t&&t.track instanceof $L?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(qb.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=oE(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(Jy.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=zb.Reconnecting,Oy("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.isPlanB?new LV({},this.store):new nF({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case qb.LocalVideoTrack:Dn(t=n._hints).call(t,ZD.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case qb.LocalAudioTrack:n instanceof ik?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case qb.LocalVideoLowTrack:}})),this.emit(Jb.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(Jb.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),Jy.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof eV?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof eV?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return XU((function*(){if(!t.connection||t.state!==zb.Connected)return;const i=yield jU(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield jU(t.connection.restartICE(e));const r=yield jU(n.next());if(r.done)return;const o=r.value,s=yield o;switch(t.reportPCDisconnectedOrFailed(e),e){case Kb.TCP:t._pcStatsUploadType=Yb.TCP_RESTART;break;case Kb.RELAY:t._pcStatsUploadType=Yb.RELAY_RESTART;break;default:t._pcStatsUploadType=Yb.OLD_RESTART}t._isInRestartIce=!0,n.next(s)}catch(e){var r;null===(r=n)||void 0===r||r.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(qb.LocalVideoTrack),i=this.localTrackMap.get(qb.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!r)return 1;const o=kv(this,Jb.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(ZD.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return aA[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=kv(this,Jb.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Gh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(Jy.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==zb.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===qb.LocalVideoTrack&&!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding){const t=this.localTrackMap.get(qb.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=Vv(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(qb.LocalAudioTrack);for(const r of e){if(r instanceof Gk&&(this.localTrackMap.has(qb.LocalVideoTrack)||s?new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:qb.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:qb.LocalVideoLowTrack})}if(r instanceof $L)if(a){const e=a.track;if(e instanceof ik)nV([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=rV([e,r]);Jy.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(o instanceof ik)nV([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&LD().webAudioMediaStreamDest&&!r._bypassWebAudio){o=rV(o?[r,o]:[r])}else o=r}return o&&(Jy.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),n.push({track:o,type:qb.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=Vv(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof $L){const e=this.localTrackMap.get(qb.LocalAudioTrack);if(!e)continue;e.track instanceof ik?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([qb.LocalAudioTrack,e]),e.track.close())):t.push([qb.LocalAudioTrack,e])}if(i instanceof Gk){const e=this.localTrackMap.get(qb.LocalVideoTrack);if(!e)continue;t.push([qb.LocalVideoTrack,e]);const i=this.localTrackMap.get(qb.LocalVideoLowTrack);i&&t.push([qb.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=Vv(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=Vv(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case qb.LocalVideoTrack:t.addListener(QD.GET_STATS,this.handleGetLocalVideoStats),t.addListener(QD.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(QD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(QD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case qb.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case qb.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof ik?e.trackList.forEach((e=>{e.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(QD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(QD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(QD.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case qb.LocalVideoTrack:t.off(QD.GET_STATS,this.handleGetLocalVideoStats),t.off(QD.GET_RTC_STATS,this.handleGetRTCStats),t.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(QD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(QD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case qb.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case qb.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof ik?e.trackList.forEach((e=>{e.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(QD.GET_STATS,this.handleGetLocalAudioStats),e.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(QD.GET_STATS,this.handleGetLocalAudioStats),e.off(QD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(QD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(QD.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(QD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(QD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof rM&&t.addListener(QD.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof oM&&t.addListener(QD.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(QD.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(Hb.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(Hb.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,o,{track:s,type:a}=e;switch(a){case qb.LocalAudioTrack:r=Lb.Audio,o={dtx:s instanceof ek&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case qb.LocalVideoTrack:r=Dn(n=s._hints).call(n,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High,o=aF(aF({},Lw(s)),{},{codec:this.store.codec,svc_mode:RM()});break;case qb.LocalVideoLowTrack:r=Lb.Low,o=aF(aF({},Lw(s)),{},{codec:this.store.codec,svc_mode:RM()})}return{stream_type:r,attributes:o,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(Jb.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),Oy("NEW_ICE_RESTART")){var i;if(Dn(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState){Jy.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(t));"CONNECTED"===kv(this,Jb.QueryClientConnectionState)&&this.emit(Jb.RequestRestartICE,t)}},i=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),Jy.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(Jb.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())},n=Oy("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout((()=>{if(Oy("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&LD().supportPCSetConfiguration)t(Kb.RELAY),this._restartTimer=window.setTimeout(i,n);else if(PI())t(Kb.UDP),this._restartTimer=window.setTimeout(i,4e3);else{if(t(Kb.TCP),LD().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout((()=>{t(Kb.RELAY),this._restartTimer=window.setTimeout(i,n)}),n));this._restartTimer=window.setTimeout(i,n)}}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&Oy("ICE_RESTART")){"CONNECTED"===kv(this,Jb.QueryClientConnectionState)&&this.emit(Jb.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(Jy.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout((()=>this.emit(Jb.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(Jy.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout((()=>this.emit(Jb.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),rA.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Rv.TRACER}).onSuccess(),this.emit(Jb.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(rP.FIRST_FRAME_DECODED),rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_AUDIO_DECODE,eA.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_AUDIO_RECEIVED,eA.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&rA.firstRemoteFrame(this.store.sessionId,$y.FIRST_VIDEO_RECEIVED,eA.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(Jb.ConnectionTypeChange,i),Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Vw(t))," -> ").concat(JSON.stringify(Vw(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{Jy.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Vw(t))," -> ").concat(JSON.stringify(Vw(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return aF(aF({},e),t)}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(qb.LocalAudioTrack);if(e instanceof $L&&(null==i?void 0:i.track)instanceof ik)return i.track.isActive||t.push([qb.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===qb.LocalVideoTrack)){const e=this.localTrackMap.get(qb.LocalVideoLowTrack);e&&t.push([qb.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(qb.LocalAudioTrack);if(e instanceof $L&&(null==i?void 0:i.track)instanceof ik)return i.track.isActive&&t.push([qb.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===qb.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(qb.LocalVideoLowTrack);e&&t.push([qb.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case qb.LocalAudioTrack:i=Lb.Audio;break;case qb.LocalVideoTrack:i=Dn(t=r._hints).call(t,ZD.SCREEN_TRACK)?Lb.Screen:Lb.High;break;case qb.LocalVideoLowTrack:i=Lb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case Hb.VIDEO:return void(i._videoSSRC&&t.push({stream_type:Hb.VIDEO,ssrcId:i._videoSSRC}));case Hb.AUDIO:return void(i._audioSSRC&&t.push({stream_type:Hb.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===Hb.VIDEO?e|=Ub.Video:e|=Ub.Audio,t.set(i,e)}else n===Hb.VIDEO?t.set(i,Ub.Video):t.set(i,Ub.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(qb.LocalVideoTrack),i=this.localTrackMap.get(qb.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}mapPubResToRemoteConfig(e,t){return e.map(((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find((e=>{let{stream_type:t}=e;return r===t})))||void 0===n?void 0:n.attributes}))}async tryToUnmuteAudio(e){for(let i=0;i{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await Lv(this,Jb.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(Jb.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(Jb.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await Qv(py(this.dtlsFailedCount,hy)),this.emit(Jb.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await Pv(this,Jb.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(Jb.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(qb.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof Gk))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof Gk)).length>1)throw new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof $L)).length>1&&(e.some((e=>e instanceof $L&&e._bypassWebAudio))||!LD().webAudioMediaStreamDest))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Gk&&this.pendingLocalTracks.some((e=>e instanceof Gk)))throw new iv(tv.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof $L&&this.pendingLocalTracks.some((e=>e instanceof $L))&&(!LD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof $L&&e._bypassWebAudio))))throw new iv(tv.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!Oy("DISABLE_DUAL_STREAM_USE_ENCODING")&&LD().supportDualStreamEncoding,n=aF(aF({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():xx(e,n);const o=Zv(8,"track-low-"),s=new Gk(r,aF(aF({},i&&{scaleResolutionDownBy:xw(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(iP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,$D.LOW_STREAM)})),s._hints.push(ZD.LOW_STREAM),e.on("sei-to-send",(e=>{s.emit("sei-to-send",e)})),e.addListener(QD.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof nF){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();rA.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(o=h.candidateType)&&void 0!==o?o:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(s=p.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i,preallocation:this.connection.isPreallocation})}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(d_(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));rA.firstRemoteVideoDecode(this.store.sessionId,$y.FIRST_VIDEO_DECODE,eA.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:FU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===qb.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,$D.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof nF&&("disconnected"!==this.connection.iceConnectionState&&"checking"!==this.connection.iceConnectionState&&"failed"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===Yb.TCP_RESTART&&e===Kb.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,Yb.DISCONNECTED_OR_FAILED)))}},ib(oF.prototype,"startP2PConnection",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"startP2PConnection"),oF.prototype),ib(oF.prototype,"connect",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"connect"),oF.prototype),ib(oF.prototype,"updateRemoteRTPCapabilities",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"updateRemoteRTPCapabilities"),oF.prototype),ib(oF.prototype,"publishDataChannel",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"publishDataChannel"),oF.prototype),ib(oF.prototype,"unpublish",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unpublish"),oF.prototype),ib(oF.prototype,"unpublishDataChannel",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unpublishDataChannel"),oF.prototype),ib(oF.prototype,"unpublishLowStream",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unpublishLowStream"),oF.prototype),ib(oF.prototype,"subscribeDataChannel",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"subscribeDataChannel"),oF.prototype),ib(oF.prototype,"subscribe",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"subscribe"),oF.prototype),ib(oF.prototype,"massSubscribe",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"massSubscribe"),oF.prototype),ib(oF.prototype,"unsubscribe",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unsubscribe"),oF.prototype),ib(oF.prototype,"unsubscribeDataChannel",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unsubscribeDataChannel"),oF.prototype),ib(oF.prototype,"massUnsubscribe",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"massUnsubscribe"),oF.prototype),ib(oF.prototype,"muteRemote",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"muteRemote"),oF.prototype),ib(oF.prototype,"unmuteRemote",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"unmuteRemote"),oF.prototype),ib(oF.prototype,"hasRemoteMediaWithLock",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"hasRemoteMediaWithLock"),oF.prototype),ib(oF.prototype,"disconnectForReconnect",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"disconnectForReconnect"),oF.prototype),ib(oF.prototype,"updateBitrateLimit",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"updateBitrateLimit"),oF.prototype),ib(oF.prototype,"remoteMediaSsrcChanged",[uF],Object.getOwnPropertyDescriptor(oF.prototype,"remoteMediaSsrcChanged"),oF.prototype),oF);function uF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s1&&void 0!==arguments[1])||arguments[1])&&Jy.debug("install service ".concat(e.name)),hF[e.name]=e}function _F(e){const t=hF[e];if(!t)throw new iv(tv.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function EF(e,t){return _F("DataStream").create(e,t)}function fF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function mF(e){for(var t=1;t0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(t.pop(),IF(i.context,r),a=0):a=Math.min(a,SF),setTimeout((()=>t.length&&CF(e)),a)}function IF(e,t){e.safeEmit(wv.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function vF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return IF(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=gF.get(n)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=mF(mF({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),gF.set(n,r);let a=!1;var c;RF.has(n)?a=!(null===(c=RF.get(n))||void 0===c||!c.isSyncing):RF.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||CF(n)}const yF=vI().name;function AF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function bF(e){for(var t=1;t{const e=i.shift();e&&await e(),i.length>0&&n{i.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),n{Jy.warn("Your browser does not support preloading, this feature be run in a secure environment")}),"preload_webcrypto_not_supported");if(!i&&null!==i)throw new iv(tv.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&av(i,"token",1,2047),av(e,"appid",1,2047),Tb(t),n&&Sb(n);const s=$v();Jy.debug("preload channel ".concat(t,", uid is ").concat(n));const a={appId:e,cname:t,token:i||e,uid:"string"!=typeof n?n:null,sid:s,proxyServer:r};let c,d;"string"==typeof n?(a.stringUid=n,[d,c]=await Gh.all([wU(n,{sid:s,appId:e},VF.token),NU(bF(bF({},a),{},{token:i||e,uid:0}),VF.token)]),a.uid=d.uid,c.gatewayInfo.uid=a.uid,c.gatewayInfo.res.uid=a.uid):(o&&(a.stringUid=o),c=await NU(a,VF.token));const l={sid:s,appId:e,cname:t,token:i||e,uid:a.stringUid||n,intUid:a.uid||c.gatewayInfo.uid,stringUid:a.stringUid,ts:Date.now(),sua:d,ap:c};await async function(e){let t;try{e.uid&&jF({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=qF(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",Yv(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,Hv(window.btoa(JSON.stringify(e))));return Kv(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=KF(wF);const r=t?JSON.parse(t):[];r.push({[i]:n}),r.length>Oy("AP_CACHE_NUM")&&r.shift(),YF(wF,JSON.stringify(r))}catch(e){Jy.warn("Error caching server parameters:",e.message),YF(wF,"")}}(l),kF++}catch(e){throw MF++,function(e){LF||(LF=window.setTimeout((()=>{let t="";UF.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),rA.reportApiInvoke(null,{name:gv.PRELOAD,options:{success:kF,failed:MF,err:t}}).onError(e),kF=0,MF=0,UF.clear(),LF=null}),NF));const t=UF.get(e.code)||0;UF.set(e.code,t+1)}(e),e}}async function BF(e){try{const t=jF(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",Yv(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,Hv(e));return JSON.parse(window.atob(Kv(new Uint8Array(n))))}catch(e){return}}(t,e.token||e.appId);if(!i)return;if(!function(e,t){const i=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!i)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(i,e))return;if(i&&Date.now()-i.ts=0;i--)if(t(e[i]))return i;return-1}(i,(e=>n in e));if(-1===r)return;const o=i.splice(r,1)[0];return YF(wF,JSON.stringify(i)),o[n]}catch(e){Jy.warn("Error delete preload info: ".concat(t),e.message),YF(wF,"")}}function GF(e){if(e){let t=DF.get(e);t&&(window.clearTimeout(t),t=null,DF.delete(e)),Dn(PF).call(PF,e)||"disabled"!==e.cloudProxyServer||PF.push(e)}if(DF.size0){const e=PF.shift();DF.set(e,window.setTimeout((async()=>{const{appId:t,cname:i,token:n,stringUid:r,uid:o,proxyServer:s}=e;try{await xF(t,i,n,o,s,r),DF.has(e)&&GF(e)}catch(t){Jy.warn("update preload failed",t.message),WF(e)}}),Oy("AP_UPDATE_INTERVAL")))}}function WF(e){const t=PF.indexOf(e);-1!==t&&PF.splice(t,1);let i=DF.get(e);i&&(window.clearTimeout(i),i=null,DF.delete(e),GF())}function HF(e,t){const i=e.sua,n=e.ap;t&&i&&rA.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),rA.reportResourceTiming(e.ap.url,e.sid),rA.joinWebProxyAP(e.sid,{lts:n.requestTime,elapse:n.elapse,sucess:1,apServerAddr:n.url,turnServerAddrList:n.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[bw.CHOOSE_SERVER,bw.CLOUD_PROXY_FALLBACK].toString()}),rA.joinChooseServer(e.sid,{lts:n.requestTime,elapse:n.elapse,succ:!0,csAddr:n.url,opid:n.opid,serverList:n.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:n.gatewayInfo.cid.toString(),uid:n.gatewayInfo.uid.toString(),csIp:n.gatewayInfo.csIp,unilbsServerIds:[bw.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function KF(e){return window.atob(window.localStorage.getItem(e)||"")}function YF(e,t){window.localStorage.setItem(e,window.btoa(t))}function qF(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),ay(t)}function zF(e){let t=function(){const e=ZF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let i=e.appId;void 0!==i&&(dB(t,10),oB(t,i));let n=e.cid;void 0!==n&&(dB(t,16),dB(t,n));let r=e.cname;void 0!==r&&(dB(t,26),oB(t,r));let o=e.deviceId;void 0!==o&&(dB(t,34),oB(t,o));let s=e.elapse;void 0!==s&&(dB(t,40),uB(t,s));let a=e.fileSize;void 0!==a&&(dB(t,48),uB(t,QF(a)));let c=e.height;void 0!==c&&(dB(t,56),uB(t,QF(c)));let d=e.jpg;void 0!==d&&(dB(t,66),dB(t,d.length),nB(t,d));let l=e.networkType;void 0!==l&&(dB(t,72),uB(t,QF(l)));let u=e.osType;void 0!==u&&(dB(t,80),uB(t,QF(u)));let h=e.requestId;void 0!==h&&(dB(t,90),oB(t,h));let p=e.sdkVersion;void 0!==p&&(dB(t,98),oB(t,p));let _=e.sequence;void 0!==_&&(dB(t,104),uB(t,QF(_)));let E=e.sid;void 0!==E&&(dB(t,114),oB(t,E));let f=e.timestamp;void 0!==f&&(dB(t,120),uB(t,f));let m=e.uid;void 0!==m&&(dB(t,128),dB(t,m));let T=e.vid;void 0!==T&&(dB(t,136),dB(t,T));let S=e.width;void 0!==S&&(dB(t,144),uB(t,QF(S)));let g=e.service;void 0!==g&&(dB(t,152),dB(t,g));let R=e.callbackData;void 0!==R&&(dB(t,162),dB(t,R.length),nB(t,R));let C=e.ticket;void 0!==C&&(dB(t,170),oB(t,C));let I=e.vendorConfigs;void 0!==I&&(dB(t,178),oB(t,I))}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function JF(e){return function(e){let t={};e:for(;!eB(e);){let i=cB(e);switch(i>>>3){case 0:break e;case 1:t.code=cB(e);break;case 2:t.msg=rB(e,cB(e));break;case 3:t.requestId=rB(e,cB(e));break;case 4:t.timestamp=lB(e,!1);break;default:XF(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function XF(e,t){switch(t){case 0:for(;128&sB(e););break;case 2:$F(e,cB(e));break;case 5:$F(e,4);break;case 1:$F(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function QF(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let ZF=[];function $F(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function eB(e){return e.offset>=e.limit}function tB(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function iB(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function nB(e,t){let i=tB(e,t.length);e.bytes.set(t,i)}function rB(e,t){let i=iB(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function oB(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function sB(e){return e.bytes[iB(e,1)]}function aB(e,t){let i=tB(e,1);e.bytes[i]=t}function cB(e){let t,i=0,n=0;do{t=sB(e),i<32&&(n|=(127&t)<>>=0;t>=128;)aB(e,127&t|128),t>>>=7;aB(e,t)}function lB(e,t){let i,n=0,r=0,o=0;return i=sB(e),n=127&i,128&i&&(i=sB(e),n|=(127&i)<<7,128&i&&(i=sB(e),n|=(127&i)<<14,128&i&&(i=sB(e),n|=(127&i)<<21,128&i&&(i=sB(e),r=127&i,128&i&&(i=sB(e),r|=(127&i)<<7,128&i&&(i=sB(e),r|=(127&i)<<14,128&i&&(i=sB(e),r|=(127&i)<<21,128&i&&(i=sB(e),o=127&i,128&i&&(i=sB(e),o|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|o<<24,unsigned:t}}function uB(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=tB(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}const hB={},pB={},_B=4294967296,EB=_B*_B,fB=EB/2,mB=CB(0,!0),TB=CB(0),SB=IB(0,-2147483648,!1),gB=IB(-1,2147483647,!1),RB=IB(-1,-1,!0);function CB(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=pB[e],n)?n:(i=IB(e,0,!0),r&&(pB[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=hB[e],n)?n:(i=IB(e,e<0?-1:0,!1),r&&(hB[e]=i),i)}function IB(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function vB(e,t){if(isNaN(e))return t?mB:TB;if(t){if(e<0)return mB;if(e>=EB)return RB}else{if(e<=-fB)return SB;if(e+1>=fB)return gB}return e<0?t?mB:TB:IB(e%_B|0,e/_B|0,t)}function yB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class AB extends mv{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(iw.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),ng(this,"name","AgoraRTCImageModeration"),ng(this,"_connectionState",tw.CONNECTING),ng(this,"_sequence",0),ng(this,"_moderationStartTime",void 0),ng(this,"_workerConnection",void 0),ng(this,"_workerMessageLengthLimit",void 0),ng(this,"_qualityRatio",void 0),ng(this,"_connectInfo",void 0),ng(this,"_cancelTokenSource",pI.CancelToken.source()),ng(this,"_retryConfig",void 0),ng(this,"_moderationInterval",void 0),ng(this,"_moderationTimer",null),ng(this,"_moderationMode",1),ng(this,"_quality",1),ng(this,"_qualityTimer",null),ng(this,"_ticket",void 0),ng(this,"_moderationIntervalMinimum",void 0),ng(this,"_uploadFailedNum",0),ng(this,"_uploadNum",0),ng(this,"_uploadTimer",null),ng(this,"_extraInfo",void 0),ng(this,"_vendor",""),ng(this,"_encoder",new TextEncoder),ng(this,"_moderationId",void 0),ng(this,"inspectImage",(()=>{if(this.connectionState!==tw.CONNECTED)throw new mb(tv.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===tw.CONNECTED?this.requestToInspectImage():Jy.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval{Jy.debug("[".concat(this._moderationId,"] Moderation operation :").concat(nw[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(iw.STATE_CHANGE,nw.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Gh(((n,r)=>{this.on(iw.CONNECTION_STATE_CHANGE,((e,t)=>{e===tw.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),Jy.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===tw.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=Oy("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;RU++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:RU,seq:RU,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return _y((async()=>{h=Date.now();const e=await $M(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new mb(tv.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw Jy.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new mb(tv.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw Jy.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new mb(tv.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw Jy.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new mb(tv.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw Jy.error(e.toString()),e}const n=Oy("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(rA.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(rA.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==tv.OPERATION_ABORTED&&t.code!==tv.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(iw.STATE_CHANGE,nw.AP_CONNECTED);const{addressList:o,ticket:s}=r;return this._ticket=s,o}async connectWorker(e){this.emit(iw.STATE_CHANGE,nw.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(fb.CONNECTED,(async()=>{this.emit(iw.STATE_CHANGE,nw.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=tw.CONNECTED})),this._workerConnection.on(fb.CLOSED,(()=>{this.connectionState=tw.CLOSED})),this._workerConnection.on(fb.FAILED,(()=>{this.connectionState=tw.CLOSED})),this._workerConnection.on(fb.RECONNECTING,(()=>{this.connectionState=this.connectionState===tw.CONNECTED?tw.RECONNECTING:tw.CONNECTING})),this._workerConnection.on(fb.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=JF(new Uint8Array(e.data));Oy("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Jy.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,Jy.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{rA.reportApiInvoke(this._connectInfo.sid||null,{name:gv.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:Rv.TRACER}).onError(new mb(tv.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),Oy("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else Jy.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(fb.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this._workerConnection.on(fb.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=kv(this,iw.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(Oy("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Jy.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else Oy("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Jy.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await lL(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+Zv(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:AB.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.22.0",sequence:this._sequence,sid:s,timestamp:vB(c),uid:a,vid:o,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=zF(h);if(p.byteLength1024)throw new mb(tv.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new mb(tv.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const wB={name:"ImageModeration",create:function(e){let{config:t}=e;return bB(t),new AB(t)}};var OB,NB,DB,PB,LB,kB,MB,UB,xB,VB,FB,BB,jB,GB,WB,HB,KB,YB,qB,zB,JB,XB,QB,ZB,$B,ej,tj,ij,nj,rj,oj,sj,aj,cj,dj,lj,uj,hj,pj,_j,Ej;function fj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function mj(e){for(var t=1;t{if(!Array.isArray(t)){if(!(t instanceof yP))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),DB=nA({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==oP.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),PB=nA({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),LB=nA({argsMap:(e,t,i)=>[t,i]}),kB=nA({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),MB=nA({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),UB=nA({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),xB=nA(),VB=nA(),FB=nA(),BB=nA(),jB=nA(),GB=nA(),WB=nA(),HB=nA(),KB=nA(),YB=nA(),qB=nA(),zB=nA(),JB=nA(),XB=nA(),QB=nA({argsMap:(e,t)=>[t]}),ZB=nA(),$B=nA(),ej=nA(),tj=nA(),ij=nA(),nj=nA(),rj=nA(),oj=nA(),sj=nA({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),aj=nA(),cj=nA(),dj=nA(),lj=nA(),uj=nA(),hj=nA(),pj=nA({reportResult:!0}),_j=nA(),Ej=class extends mv{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e){let t;if(super(),ng(this,"store",void 0),ng(this,"_uid",void 0),ng(this,"_channelName",void 0),ng(this,"_uintUid",void 0),ng(this,"_users",[]),ng(this,"_config",void 0),ng(this,"_clientId",void 0),ng(this,"_appId",void 0),ng(this,"_sessionId",null),ng(this,"_key",void 0),ng(this,"_rtmConfig",{}),ng(this,"_joinInfo",void 0),ng(this,"_gateway",void 0),ng(this,"_statsCollector",void 0),ng(this,"_configDistribute",void 0),ng(this,"_leaveMutex",new ly("client-leave")),ng(this,"_publishMutex",new ly("client-publish")),ng(this,"_renewTokenMutex",new ly("client-renewtoken")),ng(this,"_subscribeMutex",new ly("client-subscribe")),ng(this,"_encryptionMode","none"),ng(this,"_encryptionSecret",null),ng(this,"_encryptionSalt",null),ng(this,"_encryptDataStream",!1),ng(this,"_encryptDataStreamKey",null),ng(this,"_encryptDataStreamIv",null),ng(this,"_proxyServer",void 0),ng(this,"_turnServer",{servers:[],mode:"auto"}),ng(this,"_cloudProxyServerMode","disabled"),ng(this,"_isDualStreamEnabled",!1),ng(this,"_defaultStreamFallbackType",void 0),ng(this,"_lowStreamParameter",void 0),ng(this,"_streamFallbackTypeCacheMap",new Map),ng(this,"_remoteStreamTypeCacheMap",new Map),ng(this,"_axiosCancelSource",pI.CancelToken.source()),ng(this,"_audioVolumeIndicationInterval",void 0),ng(this,"_networkQualityInterval",void 0),ng(this,"_userOfflineTimeout",void 0),ng(this,"_streamRemovedTimeout",void 0),ng(this,"_liveTranscodeStreamingClient",void 0),ng(this,"_liveRawStreamingClient",void 0),ng(this,"_channelMediaRelayClient",void 0),ng(this,"_networkQualitySensitivity","normal"),ng(this,"_p2pChannel",void 0),ng(this,"_useLocalAccessPoint",!1),ng(this,"_setLocalAPVersion",void 0),ng(this,"_joinAndNotLeaveYet",!1),ng(this,"_numberOfJoinCount",0),ng(this,"_remoteDefaultVideoStreamType",void 0),ng(this,"_inspect",void 0),ng(this,"_moderation",void 0),ng(this,"_license",void 0),ng(this,"_pendingPublishedUsers",[]),ng(this,"ntpAlignErrorCount",0),ng(this,"remoteInboundOffset",0),ng(this,"_handleLocalTrackEnable",((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),ng(this,"_handleLocalTrackDisable",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),ng(this,"_handleUserOnline",(e=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(e.uid,this.channelName))return void Jy.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&Jy.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(wv.USER_JOINED,t));else{const t=new eV(e.uid,e.uint_id||e.uid);this._users.push(t),Jy.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(wv.USER_JOINED,t)}})),ng(this,"_handleUserOffline",(e=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:xv(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),Jy.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(wv.USER_LEAVED,t,e.reason))})),ng(this,"_handleAddAudioOrVideoStream",((e,t,i,n,r,o,s)=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(t,this.channelName))return;const a=this._users.find((e=>e.uid===t));if(!a)return void Jy.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));Jy.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),o&&(a._audioOrtc=o)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==s&&(a._rtxSsrcId=s),o&&(a._videoOrtc=o)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(Jy.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.safeEmit(wv.USER_PUBLISHED,a,e)),"video"===e?rA.onGatewayStream(this._sessionId,$y.ON_ADD_VIDEO_STREAM,eA.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):rA.onGatewayStream(this._sessionId,$y.ON_ADD_AUDIO_STREAM,eA.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then((t=>{if(t&&(Jy.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof lF))return this._p2pChannel.unsubscribe(a,e,!0).then((()=>this._subscribe(a,e,!0).catch((e=>{Jy.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(Jy.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch((e=>{Jy.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),ng(this,"_handleRemoveStream",(e=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void Jy.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));Jy.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{Jy.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(wv.USER_UNPUBLISHED,t,"audio"),Jy.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(wv.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{Jy.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(wv.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{Jy.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(wv.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof lF&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),rA.onGatewayStream(this._sessionId,$y.ON_REMOVE_STREAM,eA.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()})),ng(this,"_handleSetStreamLocalEnable",((e,t,i)=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void Jy.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));Jy.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";Jy.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(wv.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";Jy.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(wv.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(Jy.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(wv.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),Jy.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(wv.USER_UNPUBLISHED,n,e)):void 0})),ng(this,"_handleMuteStream",((e,t,i)=>{if(Oy("BLOCK_LOCAL_CLIENT")&&dA(e,this.channelName))return;Jy.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void Jy.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";Jy.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(wv.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";Jy.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(wv.USER_INFO_UPDATED,e,t)}}const o="audio"===t?n.hasAudio:n.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?n._audioSSRC:n._videoSSRC)?(Jy.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(wv.USER_PUBLISHED,n,t)):void Jy.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),Jy.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(wv.USER_UNPUBLISHED,n,t)}})),ng(this,"_handleP2PLost",(async e=>{Jy.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():Jy.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),ng(this,"_handleTokenWillExpire",(()=>{Jy.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(wv.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),ng(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),Jy.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),ng(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(wv.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(wv.NETWORK_QUALITY,e)})),ng(this,"_handleP2PAddAudioOrVideoStream",((e,t,i,n)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void Jy.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));Jy.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const o="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._audioMid=n)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._videoMid=n)),("audio"===e?r.hasAudio:r.hasVideo)&&!o&&(Jy.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(wv.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(Jy.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{Jy.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=Zv(5,"client-"),this.store=new Py(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),Jy.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(Cy," build: ").concat(Ay,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{bv(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){Jy.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new IV(this.store),this._statsCollector.onStatsException=(e,t,i)=>{Jy.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(wv.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));r&&rA.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useP2P="p2p"===e.mode,this._gateway=new XM(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||hy,httpRetryConfig:e.httpRetryConfig||hy,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._configDistribute=new UU,this.store.useP2P?(this._p2pChannel=new SV(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new lF(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,r){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];wy("JOIN_GATEWAY_USE_443PORT_ONLY",o),wy("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof vw&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,i){fI.get(e)||fI.set(e,[]),mI.get(e)||mI.set(e,t),TI.get(e)||TI.set(e,0);const n=fI.get(e),r=mI.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(TI.get(e)===r){const e=EI();n.push(e),await e.promise}TI.set(e,TI.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a0&&(n[0].resolve(),n.shift()),0===TI.get(e)&&(fI.set(e,[]),mI.set(e,0),TI.set(e,0)),c}("client.join",Oy("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r)}async join(e,t,i,n,r){const o=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const s="HTTPS"===(fy||fy||(fy=(window.location.protocol.split(":")[0]||"").toUpperCase(),fy)),a=Ry()?window.isSecureContext:"Browser Not Support";if(!Ry()&&!s||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";Jy.warning(e)}"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),Jy.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart))),rA.setAppId(e);try{if(!i&&null!==i)throw new mb(tv.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&av(i,"token",1,2047),av(e,"appid",1,2047),Tb(t),n&&Sb(n),r&&av(r,"optionalInfo",1,2047)}catch(r){throw rA.reportApiInvoke($v(),{name:gv.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Rv.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){Jy.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),Jy.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw rA.reportApiInvoke($v(),{name:gv.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Rv.TRACER}).onError(r),r}this._gateway.state="CONNECTING";const c=await BF({appId:e,cname:t,uid:n,stringUid:"string"==typeof n?n:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(!this._joinAndNotLeaveYet)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const d=(null==c?void 0:c.sid)||$v();Jy.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=d,this.store.sessionId=this._sessionId);const l=rA.reportApiInvoke(d,{name:gv.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Rv.TRACER}),u=mj(mj({},this._rtmConfig),{},{clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!c},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(u.stringUid=n,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=await(async e=>{const t=function(e){const t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e{"CONNECTING"===this.connectionState&&h===this._sessionId&&rA.joinChannelTimeout(this._sessionId,5)}),5e3);try{var p;let n;const r=u.cloudProxyServer;if(Dn(p=["proxy3","proxy4","proxy5"]).call(p,r)){const e=Oy("PROXY_SERVER_TYPE3");Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(rA.setProxyServer(u.proxyServer),Jy.setProxyServer(u.proxyServer),this.store.requestAPStart(),c){if(Jy.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(u.stringUid?", ".concat(u.stringUid," => ").concat(c.intUid):""," ")),u.stringUid&&!u.uid&&(u.uid=c.intUid),n={gatewayInfo:c.ap.gatewayInfo},Oy("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===u.turnServer.mode)if(0===c.ap.proxyInfo.addresses.length)Jy.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await Uw(c.ap.proxyInfo,c.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||sA.tcpport,udpport:e.udpport||sA.udpport,username:e.username||sA.username,password:e.password||sA.password,forceturn:!1,security:!0})));u.turnServer={mode:"manual",servers:e}}HF(c,u.stringUid)}else{if(u.stringUid&&!u.uid){let e;[e,n]=await Gh.all([bU(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||hy,this.store),AU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||hy,!0,this.store)]),Jy.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(e)),u.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await AU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||hy,!0,this.store);if(!this._joinAndNotLeaveYet)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(jb.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)}))}),0),this._key=i||e;const o=n.gatewayInfo,s=u.uid?u.uid:o.uid;this._joinInfo=mj(mj({},u),{},{cid:o.cid,uid:s,vid:o.vid,apResponse:o.res,apGatewayAddress:o.apGatewayAddress,uni_lbs_ip:o.uni_lbs_ip,gatewayAddrs:o.gatewayAddrs}),this.store.intUid=s;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));l.onSuccess(a),this._appId=e,this._channelName=u.cname,this._uid=a,this.store.uid=a,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(NI()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const d=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return Jy.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(d)),setTimeout((()=>{Jy.startUpload()}),5e3),this.store.joinEnd(),_=this,Dn(cA).call(cA,_)||cA.push(_),"disabled"===this._cloudProxyServerMode&&LD().supportWebCrypto&&Oy("ENABLE_PRELOAD")&&GF(this._joinInfo),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===tv.OPERATION_ABORTED?Jy.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):Jy.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==tv.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),l.onError(t),t}var _}_joinGateway(){if(!this._joinInfo||!this._key)throw new mb(tv.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!Oy("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}async leave(){Jy.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(NI()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=cA.indexOf(e);-1!==t&&cA.splice(t,1)}(this),this._statsCollector.stopUpdateStats();const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return Jy.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),Jy.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof yP))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new mb(tv.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new mb(tv.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof yP))throw new mb(tv.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new mb(tv.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}Jy.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof Gk&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),Jy.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw Jy.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{n()}}async _publishDataChannel(e){ov(e.id,"id",0,65535,!0),nv(e.ordered,"ordered"),av(e.metadata,"metadata",0,512),Jy.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new mb(tv.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new mb(tv.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&Oy("FORCE_TURN")&&!Oy("TURN_ENABLE_TCP")&&!Oy("TURN_ENABLE_UDP"))throw new mb(tv.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return EF(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw Jy.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new mb(tv.CREATE_DATACHANNEL_ERROR);try{await Gh.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==tv.DISCONNECT_P2P)throw e}}return Jy.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw Jy.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new mb(tv.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof yP))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);Jy.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this._p2pChannel instanceof SV){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(rw.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),Jy.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw Jy.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),Jy.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&await this._gateway.unpublishDataChannel(i),Jy.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw Jy.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof eV)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(rv(t,"mediaType",["audio","video"]),this._p2pChannel instanceof SV)throw new mb(tv.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===Hb.AUDIO,n=t===Hb.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:o,ortc:s,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==o)throw new mb(tv.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new eV(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=o,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),n&&(l._videoSSRC=o,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),null!=a&&(l._rtxSsrcId=a)),Jy.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(o)),await this._p2pChannel.subscribe(l,t,o,a,s);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new mb(tv.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(t){throw Jy.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var i;if(ov(t,"channelId",0,65535,!0),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n)throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new mb(tv.INVALID_REMOTE_USER,"user is not published");const r=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!r)throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new mb(tv.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();Jy.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Dn(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new mb(tv.CREATE_DATACHANNEL_ERROR);const t={id:r.id,datachannelId:r._originDataChannelId,ordered:r.ordered,maxRetransmits:r.maxRetransmits,metadata:null!==(s=r.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await r._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==tv.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return Jy.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,i){if(rv(t,"mediaType",["audio","video"]),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new mb(tv.INVALID_REMOTE_USER,"user is not published");throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new mb(tv.REMOTE_USER_IS_NOT_PUBLISHED);throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const r=await this._subscribeMutex.lock();Jy.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this._p2pChannel instanceof SV&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}Jy.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{Jy.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new mb(tv.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw Jy.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,i){if(this._p2pChannel instanceof SV)return this._p2pSubscribe(e,t);if(rv(t,"mediaType",["audio","video"]),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new mb(tv.INVALID_REMOTE_USER,"user is not published");throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new mb(tv.REMOTE_USER_IS_NOT_PUBLISHED);throw Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let r="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?Hb.AUDIO:Hb.VIDEO,ssrcId:r};const c=await this._subscribeMutex.lock();Jy.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==r&&(r=i,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?Hb.AUDIO:Hb.VIDEO,ssrcId:r}),FU.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,s,o);try{this._p2pChannel.isPreSubScribe(r)||await this._gateway.subscribe(e.uid,a,!0)}catch(i){if((null==i?void 0:i.code)!==tv.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}Jy.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{Jy.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new mb(tv.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw Jy.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(cv(e,"subscribeList"),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();Jy.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const r=(e=[...e]).map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}})),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:o,mediaType:s}=n;if(rv(s,"mediaType",["audio","video"]),!o){const e=new mb(tv.INVALID_PARAMS,"user property does not exist in subscribeList item");throw Jy.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}const a=this._users.find((e=>e===o));if(!a){const i=new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");Jy.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const i=new mb(tv.REMOTE_USER_IS_NOT_PUBLISHED);Jy.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=i,e.splice(t,1);continue}const c=Ub.Video|Ub.LwoVideo,d=i.get(o);if(d){if("video"===s?d&c:d&Ub.Audio){e.splice(t,1),Jy.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,d|("video"===s?c:Ub.Audio))}else i.set(o,"video"===s?c:Ub.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:o}=n,s=Ub.Video|Ub.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const n=i.get(r);i.set(r,"video"===o?n^s:n^Ub.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=Jn(s=Array.from(i.entries())).call(s,((e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&Ub.Audio&&(r.audio_ssrc=i._audioSSRC),n&Ub.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===Hb.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===Hb.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:o}=e;(n||r||o)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:o})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let[i,n]=t;const r=this.remoteUsers.find((e=>e.uid===i));if(r){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=Hb.VIDEO:n.audio_error_code&&(t=Hb.AUDIO),e.push({user:r,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=uw(i);Jy.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new mb(tv.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var i;rA.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===Hb.VIDEO,audio:e.mediaType===Hb.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===Hb.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)})),Jy.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),n()}}async unsubscribe(e,t,i){if(!(e instanceof eV)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&rv(t,"mediaType",["audio","video"]),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");throw Jy.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}Jy.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const r=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof SV)await this._p2pChannel.unsubscribe(e,t);else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&xv(this._users,e),Jy.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===tv.DISCONNECT_P2P)return void Jy.warning("disconnecting p2p, abort unsubscribe request.");throw Jy.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&ov(t,"id",0,65535,!0),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new mb(tv.INVALID_REMOTE_USER,"user is not in the channel");throw Jy.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let n;if("number"==typeof t){const i=e._dataChannels.find((e=>e.id===t));i&&(n=[i])}else n=e._dataChannels;if(void 0===n){const i=new mb(tv.REMOTE_USER_IS_NOT_PUBLISHED);throw Jy.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}Jy.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(n.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,n);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),Jy.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===tv.DISCONNECT_P2P)return void Jy.warning("disconnecting p2p, abort unsubscribe request.");throw Jy.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(cv(e,"unsubscribeList"),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");Jy.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new mb(tv.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw Jy.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}rv(r,"mediaType",["video","audio",void 0]);const o=this._users.find((e=>e===n));if(!o){Jy.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const s=Ub.Video|Ub.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&Ub.Audio;break;default:a=o&(Ub.Audio|s)}if(a){Jy.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue}r?"audio"===r?t.set(n,o|Ub.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|Ub.Audio|s)}else r?"audio"===r?t.set(n,Ub.Audio):"video"===r&&t.set(n,s):t.set(n,Ub.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),Jy.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===tv.DISCONNECT_P2P)return void Jy.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw Jy.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new iv(tv.INVALID_PARAMS);dv(e.width)||sv(e.width,"streamParameter.width"),dv(e.height)||sv(e.height,"streamParameter.height"),dv(e.framerate)||sv(e.framerate,"streamParameter.framerate"),dv(e.bitrate)||ov(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&Jy.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),Jy.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(av(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new mb(tv.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,rA.setProxyServer(this._proxyServer),Jy.setProxyServer(this._proxyServer),Jy.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new mb(tv.INVALID_OPERATION,"You have already set the proxy")}if(yv(e))return this._turnServer={servers:e,mode:"original-manual"},void Jy.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>Av(e))),this._turnServer={servers:e,mode:"manual"},Jy.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new mb(tv.INVALID_OPERATION,"you should set license before join channel")}if(av(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new mb(tv.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,Jy.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new mb(tv.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new mb(tv.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new mb(tv.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,Jy.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"Stop proxy server after leave channel");rA.setProxyServer(),Jy.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",Jy.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new mb(tv.INVALID_PARAMS,"accessPoints is required.");cv(e.accessPoints.serverList,"accessPoints.serverList"),av(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{ov(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new mb(tv.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");Oy("CLOSE_AFB_FOR_LOCAL_AP")&&(wy("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),wy("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),s=o.map((e=>"".concat(e,":").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,wy("WEBCS_DOMAIN",s),wy("WEBCS_DOMAIN_BACKUP_LIST",s),wy("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(cv(e.report.hostname,"report.hostname"),wy("EVENT_REPORT_DOMAIN",e.report.hostname[0]),wy("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(wy("EVENT_REPORT_DOMAIN",o[0]),wy("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),wy("STATS_COLLECTOR_PORT",a),e.report?wy("ENABLE_EVENT_REPORT",!0):wy("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(cv(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),wy("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(cv(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=o;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),wy("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?wy("ENABLE_CONFIG_DISTRIBUTE",!0):wy("ENABLE_CONFIG_DISTRIBUTE",!1),Jy.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(cv(e,"serverList"),av(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new mb(tv.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,wy("WEBCS_DOMAIN",e),wy("WEBCS_DOMAIN_BACKUP_LIST",e),wy("GATEWAY_DOMAINS",[t]),wy("EVENT_REPORT_DOMAIN",e[0]),wy("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),wy("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),Jy.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(rv(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw Jy.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else Jy.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){rv(t,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw Jy.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}Jy.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){rv(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw Jy.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}Jy.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){!function(e){rv(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"])}(e),av(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Dn(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new mb(tv.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new mb(tv.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(nv(n,"encryptDataStream"),!Dn(r).call(r,e))throw new mb(tv.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||Jy.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=Kv(i))}async renewToken(e){if(av(e,"token",1,2047),!this._key||!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(Oy("USE_NEW_TOKEN")){Jy.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await LU(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||hy);Jy.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else Jy.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});Jy.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,Jy.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?Jy.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(wv.VOLUME_INDICATOR,e)}),Oy("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new mb(tv.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new mb(tv.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new mb(tv.LIVE_STREAMING_TASK_CONFLICT);const i=t?gb.TRANSCODE:gb.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(gb.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new mb(tv.INVALID_PARAMS,"can not find live streaming url to stop");await Gh.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){yV(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){yV(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Dn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=Jn(n=Array.from(i)).call(n,((e,t)=>e+t),0),o={serverTs:0,seq:Vy++,length:i.length,checkSum:r},s=new Uint8Array(oy(r,2)),a=new ArrayBuffer(xy),c=new DataView(a);c.setUint32(0,o.serverTs),c.setUint16(4,o.seq),c.setUint16(6,o.length),c.setUint16(8,o.checkSum);const d=16-i.length%16;i=qv(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:ky,additionalData:s},t,i);return qv(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new mb(tv.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(hb.DATA_STREAM,{payload:Kv(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-TF},!i)}sendMetadata(e){if(!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new mb(tv.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(hb.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:Kv(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(Qy),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"can not send custom report, not joined");await rA.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){rv(t.spatialLayer,"spatialLayer",[0,1,2,3]),rv(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw Jy.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(nv(t,"apRTM"),ov(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,Jy.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(Jy.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=pI.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&WF(this._joinInfo),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new ly("client-publish"),this._subscribeMutex=new ly("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;const n=e||$v();e?Jy.debug("[".concat(this._clientId,"] new Session ").concat(n)):Jy.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n;const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:1,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1};rA.sessionInit(this._sessionId,mj({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new mb(tv.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&Oy("FORCE_TURN")&&!Oy("TURN_ENABLE_TCP")&&!Oy("TURN_ENABLE_UDP"))throw new mb(tv.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");Jy.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this._p2pChannel instanceof SV){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(rw.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0)}catch(e){if(e.code!==tv.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof Gk&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===tv.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new mb(tv.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));Jy.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate{if(!this._joinInfo||!this._appId){return new mb(tv.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const e=(t={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},_F("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{rA.reportApiInvoke(this._sessionId,{name:gv.ON_LIVE_STREAM_ERROR,options:[e,t],tag:Rv.TRACER}).onSuccess(),this.safeEmit(wv.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{rA.reportApiInvoke(this._sessionId,{name:gv.ON_LIVE_STREAM_WARNING,options:[e,t],tag:Rv.TRACER}).onSuccess(),this.safeEmit(wv.LIVE_STREAMING_WARNING,e,t)},e.on(Ab.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new mb(tv.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const r=Oy("UAP_AP").slice(0,Oy("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await hU(r,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,hy).then(t).catch(i)})),e};return e===gb.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new mb(tv.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const{sendResolutionWidth:t,sendResolutionHeight:i}=this.getLocalVideoStats(),n=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:i}},_F("ChannelMediaRelay").create(e));n.on("state",(e=>{e===Db.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(wv.CHANNEL_MEDIA_RELAY_STATE,e)})),n.on("event",(e=>{this.safeEmit(wv.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=n,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];if(t){const e=[];this._users.forEach((t=>{t._dataChannels.forEach((n=>{i.every((e=>e.uid!==t._uintid||e.stream_id!==n.id))&&e.push({uid:t._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})}))})),e.length>0&&this._handleUpdateDataChannel({added:[],deleted:e})}Array.isArray(i)&&i.length>0&&i.forEach((e=>{const{uid:i,stream_id:n,ordered:o,max_retrans_times:s,metadata:a}=e,c=this._users.find((e=>e._uintid===i));if(!c)return void Jy.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));Jy.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Dn(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i);if(!(-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id)))){const e={id:n,ordered:!!o,maxRetransmits:s,metadata:a},i=function(e){return EF(e,!0)}(e);c._dataChannels.push(i),Jy.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(wv.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(Jy.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{Jy.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})),t&&(this.safeEmit(wv.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach((e=>{const{uid:t,stream_id:i}=e,n=this._users.find((e=>e._uintid===t));if(!n)return void Jy.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=n._dataChannels.find((t=>t.id===e.stream_id));r&&(Jy.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then((e=>{if(n._dataChannels=n._dataChannels.filter((e=>e!==r)),e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),Jy.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(wv.USER_UNPUBLISHED,n,"datachannel",r._config))}))}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){Jy.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{Jy.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(wv.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else Jy.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(kb.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(kb.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===vv.FALLBACK)return;const r=()=>{this.safeEmit(wv.CONNECTION_STATE_CHANGE,e,t,i)};if(rA.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:gv.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:Rv.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),Jy.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var o;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{Jy.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{Jy.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{Jy.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{Jy.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{Jy.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Hb.AUDIO,!1)),e._trust_video_mute_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Hb.VIDEO,!1)),e._trust_audio_enabled_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(Jy.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(Jy.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}r()})),this._gateway.on(kb.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new mb(tv.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;const i=await BF(mj(mj({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));i?(t=i.ap,HF(i),this._joinInfo.preload=!0):(t=await yU(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||hy,this.store),this._joinInfo.preload=!1),this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[i,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:r}):n.push({host:i,port:r})})),e(n)}catch(e){t(e)}})),this._gateway.on(kb.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(wv.NETWORK_QUALITY,e)})),this._gateway.on(kb.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(wv.STREAM_TYPE_CHANGED,e,t);rA.reportApiInvoke(this._sessionId,{name:gv.STREAM_TYPE_CHANGE,options:[e,t],tag:Rv.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.on(kb.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(kb.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();Oy("ENABLE_PREALLOC_PC")&&i||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(kb.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;const i=bM(e.ortc,t,e.attributes.userAttributes.preSubSsrcs);this._p2pChannel.connect(i)})),this._gateway.on(kb.PRE_CONNECT_PC,(async e=>{const{candidates:t,fingerprint:i}=e;if(this._joinInfo&&t.length>0&&!this._p2pChannel.isPlanB){var n;await this._p2pChannel.startP2PConnection({turnServer:this._joinInfo.turnServer});const{cert:e,cid:r}=this._joinInfo.apResponse;await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(r,"_").concat(e),icePwd:"".concat(r,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(n=Oy("FINGERPRINT"))&&void 0!==n?n:i}]},candidates:t,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0})}}))}_handleGatewaySignalEvents(){this._gateway.signal.on(_b.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(_b.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(_b.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc))),this._gateway.signal.on(_b.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(_b.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(_b.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)})),this._gateway.signal.on(_b.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(_b.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(_b.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Hb.AUDIO,!0))),this._gateway.signal.on(_b.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Hb.AUDIO,!1))),this._gateway.signal.on(_b.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Hb.VIDEO,!0))),this._gateway.signal.on(_b.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Hb.VIDEO,!1))),this._gateway.signal.on(_b.RECEIVE_METADATA,(e=>{const t=Hv(e.metadata);this.safeEmit(wv.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(_b.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let i=Hv(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Dn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.lengtht.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==i?void 0:i._audioSSRC)));n=null==r?void 0:r.jitterBufferMs}null==n&&(n=0),vF(mj(mj({},e),{},{payload:i}),n,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(_b.ON_CRYPT_ERROR,(()=>{Wv((()=>{Jy.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(wv.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(_b.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(_b.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{Jy.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,vv.TOKEN_EXPIRE),this.safeEmit(wv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(_b.ON_STREAM_FALLBACK_UPDATE,(e=>{Jy.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(wv.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(_b.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),Jy.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(_b.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(_b.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(ub.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case hb.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some((e=>{let{stream_type:t}=e;return t===Lb.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t!==Lb.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===Lb.Screen||t===Lb.ScreenLow}));"offer"===t.state&&rA.publish(this._joinInfo.sid,{eventElapse:FU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:tv.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(i=e.find((e=>{let{stream_type:t}=e;return t===Lb.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:o?null===(n=e.find((e=>{let{stream_type:t}=e;return t!==Lb.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case hb.SUBSCRIBE:t&&rA.subscribe(this._joinInfo.sid,{succ:!1,ec:tv.TIMEOUT,audio:t.stream_type===Hb.AUDIO,video:t.stream_type===Hb.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:FU.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(_b.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(_b.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;Oy("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!dA(e.string_id||e.stream_id,this.channelName))));const t=[],i=[];for(const n of e.users){let e=this._users.find((e=>e._uintid===n.stream_id));e?e._trust_in_room_=!0:(e=new eV(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(wv.PUBLISHED_USER_LIST).length&&(Jy.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(wv.USER_JOINED,e)));const r=Ub.Audio&n.stream_type,o=(Ub.Video|Ub.LwoVideo)&n.stream_type,s=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=o&&e.hasVideo;o&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(wv.PUBLISHED_USER_LIST).length&&(Jy.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(wv.USER_PUBLISHED,e,"audio")),o&&!c&&0===this.getListeners(wv.PUBLISHED_USER_LIST).length&&(Jy.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(wv.USER_PUBLISHED,e,"video")),(r&&!a||o&&!c||s)&&t.push(e),o&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(Jy.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(i).catch((e=>{Jy.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(wv.PUBLISHED_USER_LIST).length>0?Oy("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(Jy.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(wv.PUBLISHED_USER_LIST,t)):Jy.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map((e=>e.uid)).join(", ")))})),this._gateway.signal.on(_b.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;this._p2pChannel instanceof lF&&this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return Dn(t=Object.keys(Ly)).call(t,e)})))}))}_handleP2PEvents(){this._gateway.signal.on(_b.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(rw.PUBLISH,((e,t,i)=>{const{uid:n}=e;e.forEach((e=>{const{kind:r,ssrcs:o,mid:s,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,n,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===n));return c&&this._p2pChannel instanceof SV?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,r,!!a)}))})),this._gateway.signal.on(rw.CALL,(async(e,t,i)=>{if(this._p2pChannel instanceof SV)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e))}catch(e){i(e)}})),this._gateway.signal.on(ub.P2P_CONNECTION,(async e=>{this._p2pChannel instanceof SV&&await this._p2pChannel.p2pConnect(e)})),this._gateway.signal.on(rw.UNPUBLISH,(async(e,t,i)=>{if(this._p2pChannel instanceof SV){const{unpubMsg:n,uid:r}=e,o=this._users.find((e=>e.uid===r));if(!o)return Jy.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{n.forEach((async e=>{let{stream_type:t}=e;const i=t===Lb.Audio?Hb.AUDIO:Hb.VIDEO;await this._p2pChannel.unsubscribe(o,i),this._handleMuteStream(r,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(rw.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case sw.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,Hb.VIDEO,!0);break;case sw.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,Hb.AUDIO,!0);break;case sw.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,Hb.VIDEO,!1);break;case sw.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,Hb.AUDIO,!1)}})),this._gateway.signal.on(rw.RESTART_ICE,(async(e,t,i)=>{if(this._p2pChannel instanceof SV)try{const{direction:i,iceParameter:n}=e;if(i!==Eb.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(rw.CANDIDATE,(e=>{if(this._p2pChannel instanceof SV){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(Jb.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(rw.RESTART_ICE,e,i===Eb.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(Jb.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(rw.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(Jb.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(rw.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(Jb.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===tv.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(Jb.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===tv.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(Jb.StateChange,((e,t)=>{t===zb.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(Jb.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===tv.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(Jb.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===tv.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(Jb.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(Jb.RequestRePublishDataChannel,((e,t,i)=>{Gh.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==tv.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(Jb.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===Hb.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(Jb.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(Jb.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(Jb.MediaReconnectStart,(e=>{this.safeEmit(wv.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(Jb.MediaReconnectEnd,(e=>{this.safeEmit(wv.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(Jb.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(Jb.RequestRestartICE,(async e=>{if(this._p2pChannel instanceof SV)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const{iceParameters:o}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r);await t.next({remoteIceParameters:o})})),this._p2pChannel.on(Jb.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(Jb.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:o}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),s=bM(r,o);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(Jb.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(Jb.P2PLost,(()=>{this.safeEmit(wv.P2P_LOST,this.store.uid)})),this._p2pChannel.on(Jb.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(Jb.ConnectionTypeChange,(e=>{this.safeEmit(wv.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(Jb.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(Jb.QueryClientConnectionState,(e=>{e(this.connectionState)}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},_F("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);const{appId:n,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await i.init({appId:n,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},hy)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(Zb.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(wv.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===Xb.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(wv.CONTENT_INSPECT_ERROR,new mb(tv.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(Zb.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===tv.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return Jy.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(wv.CONTENT_INSPECT_RESULT,e,t)})),e.on(Zb.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(nv(e,"enabled"),e){if(!t)throw new mb(tv.INVALID_PARAMS,"config is required");if(bB(t),!this._joinInfo)throw new mb(tv.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(i={config:t},_F("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);const{appId:n,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await e.init({appId:n,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},hy)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new mb(tv.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(iw.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(wv.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===tw.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new mb(tv.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(iw.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){rv(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new mb(tv.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,Jy.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return Jy.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){nv(e,"enabled"),wy("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}},ib(Ej.prototype,"leave",[OB],Object.getOwnPropertyDescriptor(Ej.prototype,"leave"),Ej.prototype),ib(Ej.prototype,"publish",[NB],Object.getOwnPropertyDescriptor(Ej.prototype,"publish"),Ej.prototype),ib(Ej.prototype,"unpublish",[DB],Object.getOwnPropertyDescriptor(Ej.prototype,"unpublish"),Ej.prototype),ib(Ej.prototype,"subscribe",[PB],Object.getOwnPropertyDescriptor(Ej.prototype,"subscribe"),Ej.prototype),ib(Ej.prototype,"presubscribe",[LB],Object.getOwnPropertyDescriptor(Ej.prototype,"presubscribe"),Ej.prototype),ib(Ej.prototype,"massSubscribe",[kB],Object.getOwnPropertyDescriptor(Ej.prototype,"massSubscribe"),Ej.prototype),ib(Ej.prototype,"unsubscribe",[MB],Object.getOwnPropertyDescriptor(Ej.prototype,"unsubscribe"),Ej.prototype),ib(Ej.prototype,"massUnsubscribe",[UB],Object.getOwnPropertyDescriptor(Ej.prototype,"massUnsubscribe"),Ej.prototype),ib(Ej.prototype,"setLowStreamParameter",[xB],Object.getOwnPropertyDescriptor(Ej.prototype,"setLowStreamParameter"),Ej.prototype),ib(Ej.prototype,"enableDualStream",[VB],Object.getOwnPropertyDescriptor(Ej.prototype,"enableDualStream"),Ej.prototype),ib(Ej.prototype,"disableDualStream",[FB],Object.getOwnPropertyDescriptor(Ej.prototype,"disableDualStream"),Ej.prototype),ib(Ej.prototype,"setClientRole",[BB],Object.getOwnPropertyDescriptor(Ej.prototype,"setClientRole"),Ej.prototype),ib(Ej.prototype,"setProxyServer",[jB],Object.getOwnPropertyDescriptor(Ej.prototype,"setProxyServer"),Ej.prototype),ib(Ej.prototype,"setTurnServer",[GB],Object.getOwnPropertyDescriptor(Ej.prototype,"setTurnServer"),Ej.prototype),ib(Ej.prototype,"setLicense",[WB],Object.getOwnPropertyDescriptor(Ej.prototype,"setLicense"),Ej.prototype),ib(Ej.prototype,"startProxyServer",[HB],Object.getOwnPropertyDescriptor(Ej.prototype,"startProxyServer"),Ej.prototype),ib(Ej.prototype,"stopProxyServer",[KB],Object.getOwnPropertyDescriptor(Ej.prototype,"stopProxyServer"),Ej.prototype),ib(Ej.prototype,"setLocalAccessPointsV2",[YB],Object.getOwnPropertyDescriptor(Ej.prototype,"setLocalAccessPointsV2"),Ej.prototype),ib(Ej.prototype,"setLocalAccessPoints",[qB],Object.getOwnPropertyDescriptor(Ej.prototype,"setLocalAccessPoints"),Ej.prototype),ib(Ej.prototype,"setRemoteDefaultVideoStreamType",[zB],Object.getOwnPropertyDescriptor(Ej.prototype,"setRemoteDefaultVideoStreamType"),Ej.prototype),ib(Ej.prototype,"setRemoteVideoStreamType",[JB],Object.getOwnPropertyDescriptor(Ej.prototype,"setRemoteVideoStreamType"),Ej.prototype),ib(Ej.prototype,"setStreamFallbackOption",[XB],Object.getOwnPropertyDescriptor(Ej.prototype,"setStreamFallbackOption"),Ej.prototype),ib(Ej.prototype,"setEncryptionConfig",[QB],Object.getOwnPropertyDescriptor(Ej.prototype,"setEncryptionConfig"),Ej.prototype),ib(Ej.prototype,"renewToken",[ZB],Object.getOwnPropertyDescriptor(Ej.prototype,"renewToken"),Ej.prototype),ib(Ej.prototype,"enableAudioVolumeIndicator",[$B],Object.getOwnPropertyDescriptor(Ej.prototype,"enableAudioVolumeIndicator"),Ej.prototype),ib(Ej.prototype,"startLiveStreaming",[ej],Object.getOwnPropertyDescriptor(Ej.prototype,"startLiveStreaming"),Ej.prototype),ib(Ej.prototype,"setLiveTranscoding",[tj],Object.getOwnPropertyDescriptor(Ej.prototype,"setLiveTranscoding"),Ej.prototype),ib(Ej.prototype,"stopLiveStreaming",[ij],Object.getOwnPropertyDescriptor(Ej.prototype,"stopLiveStreaming"),Ej.prototype),ib(Ej.prototype,"startChannelMediaRelay",[nj],Object.getOwnPropertyDescriptor(Ej.prototype,"startChannelMediaRelay"),Ej.prototype),ib(Ej.prototype,"updateChannelMediaRelay",[rj],Object.getOwnPropertyDescriptor(Ej.prototype,"updateChannelMediaRelay"),Ej.prototype),ib(Ej.prototype,"stopChannelMediaRelay",[oj],Object.getOwnPropertyDescriptor(Ej.prototype,"stopChannelMediaRelay"),Ej.prototype),ib(Ej.prototype,"sendCustomReportMessage",[sj],Object.getOwnPropertyDescriptor(Ej.prototype,"sendCustomReportMessage"),Ej.prototype),ib(Ej.prototype,"pickSVCLayer",[aj],Object.getOwnPropertyDescriptor(Ej.prototype,"pickSVCLayer"),Ej.prototype),ib(Ej.prototype,"setRTMConfig",[cj],Object.getOwnPropertyDescriptor(Ej.prototype,"setRTMConfig"),Ej.prototype),ib(Ej.prototype,"enableContentInspect",[dj],Object.getOwnPropertyDescriptor(Ej.prototype,"enableContentInspect"),Ej.prototype),ib(Ej.prototype,"disableContentInspect",[lj],Object.getOwnPropertyDescriptor(Ej.prototype,"disableContentInspect"),Ej.prototype),ib(Ej.prototype,"setImageModeration",[uj],Object.getOwnPropertyDescriptor(Ej.prototype,"setImageModeration"),Ej.prototype),ib(Ej.prototype,"setP2PTransport",[hj],Object.getOwnPropertyDescriptor(Ej.prototype,"setP2PTransport"),Ej.prototype),ib(Ej.prototype,"getJoinChannelServiceRecords",[pj],Object.getOwnPropertyDescriptor(Ej.prototype,"getJoinChannelServiceRecords"),Ej.prototype),ib(Ej.prototype,"setPublishAudioFilterEnabled",[_j],Object.getOwnPropertyDescriptor(Ej.prototype,"setPublishAudioFilterEnabled"),Ej.prototype),Ej);class Sj{constructor(e,t){ng(this,"id",0),ng(this,"element",void 0),ng(this,"peerPair",void 0),ng(this,"context",void 0),ng(this,"audioPlayerElement",void 0),ng(this,"audioTrack",void 0),Sj.count+=1,this.id=Sj.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new Gh((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new mb(tv.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new mb(tv.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new mb(tv.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){Jy.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}var gj,Rj;ng(Sj,"count",0);const Cj=window.AudioContext||window.webkitAudioContext;const Ij=new(gj=nA({report:rA}),ib((Rj=class{constructor(){ng(this,"units",[]),ng(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return Jy.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Cj);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new Sj(e,this.context),this.units.push(t)),t.startEchoCancellation(),Jy.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return vI().name!==gI.SAFARI}}).prototype,"processExternalMediaAEC",[gj],Object.getOwnPropertyDescriptor(Rj.prototype,"processExternalMediaAEC"),Rj.prototype),Rj);function vj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function yj(e){for(var t=1;t1&&void 0!==arguments[1]&&arguments[1];if(!Aj)return;const i=QK._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(QK.onSecurityPolicyViolation||QK.getListeners(ew.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;Oy("CSP_DETECTED_HOSTNAME_LIST").some((e=>Dn(t).call(t,e)))&&(QK.onSecurityPolicyViolation&&"function"==typeof QK.onSecurityPolicyViolation&&QK.onSecurityPolicyViolation(e),QK.getListeners(ew.SECURITY_POLICY_VIOLATION).length>0&&QK.safeEmit(ew.SECURITY_POLICY_VIOLATION,e))};i&&Aj.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||QK.getListeners(ew.SECURITY_POLICY_VIOLATION).length>0)&&Aj.addEventListener("securitypolicyviolation",n),QK._cspEventHandlerPointer=n}var wj=l,Oj=VR,Nj=RegExp.prototype,Dj=function(e){return e===Nj||wj(Nj,e)?Oj(e):e.flags},Pj=i(Dj);function Lj(e){let t=e.length;for(;--t>=0;)e[t]=0}const kj=256,Mj=286,Uj=30,xj=15,Vj=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Fj=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Bj=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),jj=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Gj=new Array(576);Lj(Gj);const Wj=new Array(60);Lj(Wj);const Hj=new Array(512);Lj(Hj);const Kj=new Array(256);Lj(Kj);const Yj=new Array(29);Lj(Yj);const qj=new Array(Uj);function zj(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let Jj,Xj,Qj;function Zj(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}Lj(qj);const $j=e=>e<256?Hj[e]:Hj[256+(e>>>7)],eG=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},tG=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{tG(e,i[2*t],i[2*t+1])},nG=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},rG=(e,t,i)=>{const n=new Array(16);let r,o,s=0;for(r=1;r<=xj;r++)s=s+i[r-1]<<1,n[r]=s;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=nG(n[t]++,t))}},oG=e=>{let t;for(t=0;t{e.bi_valid>8?eG(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},aG=(e,t,i,n)=>{const r=2*t,o=2*i;return e[r]{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let n,r,o,s,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?iG(e,r,t):(o=Kj[r],iG(e,o+kj+1,t),s=Vj[o],0!==s&&(r-=Yj[o],tG(e,r,s)),n--,o=$j(n),iG(e,o,i),s=Fj[o],0!==s&&(n-=qj[o],tG(e,n,s)))}while(a{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let s,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,s=0;s>1;s>=1;s--)cG(e,i,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],cG(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,i[2*c]=i[2*s]+i[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,i[2*s+1]=i[2*a+1]=c,e.heap[1]=c++,cG(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=xj;h++)e.bl_count[h]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=i[2*i[2*l+1]+1]+1,h>c&&(h=c,E++),i[2*l+1]=h,l>n||(e.bl_count[h]++,p=0,l>=a&&(p=s[l-a]),_=i[2*l],e.opt_len+=_*(h+p),o&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>n||(i[2*u+1]!==h&&(e.opt_len+=(h-i[2*u+1])*i[2*u],i[2*u+1]=h),l--)}})(e,t),rG(i,d,e.bl_count)},uG=(e,t,i)=>{let n,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=s,s=t[2*(n+1)+1],++a{let n,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),n=0;n<=i;n++)if(r=s,s=t[2*(n+1)+1],!(++a{tG(e,0+(n?1:0),3),sG(e),eG(e,i),eG(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var EG=e=>{pG||((()=>{let e,t,i,n,r;const o=new Array(16);for(i=0,n=0;n<28;n++)for(Yj[n]=i,e=0;e<1<>=7;n{let r,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t{let t;for(uG(e,e.dyn_ltree,e.l_desc.max_code),uG(e,e.dyn_dtree,e.d_desc.max_code),lG(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*jj[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=r&&(r=o)):r=o=i+5,i+4<=r&&-1!==t?_G(e,t,i,n):4===e.strategy||o===r?(tG(e,2+(n?1:0),3),dG(e,Gj,Wj)):(tG(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(tG(e,t-257,5),tG(e,i-1,5),tG(e,n-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Kj[i]+kj+1)]++,e.dyn_dtree[2*$j(t)]++),e.sym_next===e.sym_end),TG=e=>{tG(e,2,3),iG(e,256,Gj),(e=>{16===e.bi_valid?(eG(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},SG={_tr_init:EG,_tr_stored_block:_G,_tr_flush_block:fG,_tr_tally:mG,_tr_align:TG};var gG=(e,t,i,n)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;0!==i;){s=i>2e3?2e3:i,i-=s;do{r=r+t[n++]|0,o=o+r|0}while(--s);r%=65521,o%=65521}return r|o<<16|0};const RG=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var CG=(e,t,i,n)=>{const r=RG,o=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return-1^e},IG={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},vG={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:yG,_tr_stored_block:AG,_tr_flush_block:bG,_tr_tally:wG,_tr_align:OG}=SG,{Z_NO_FLUSH:NG,Z_PARTIAL_FLUSH:DG,Z_FULL_FLUSH:PG,Z_FINISH:LG,Z_BLOCK:kG,Z_OK:MG,Z_STREAM_END:UG,Z_STREAM_ERROR:xG,Z_DATA_ERROR:VG,Z_BUF_ERROR:FG,Z_DEFAULT_COMPRESSION:BG,Z_FILTERED:jG,Z_HUFFMAN_ONLY:GG,Z_RLE:WG,Z_FIXED:HG,Z_DEFAULT_STRATEGY:KG,Z_UNKNOWN:YG,Z_DEFLATED:qG}=vG,zG=286,JG=30,XG=19,QG=2*zG+1,ZG=15,$G=258,eW=262,tW=42,iW=113,nW=666,rW=(e,t)=>(e.msg=IG[t],t),oW=e=>2*e-(e>4?9:0),sW=e=>{let t=e.length;for(;--t>=0;)e[t]=0},aW=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let cW=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},lW=(e,t)=>{bG(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,dW(e.strm)},uW=(e,t)=>{e.pending_buf[e.pending++]=t},hW=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},pW=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=gG(e.adler,t,r,i):2===e.state.wrap&&(e.adler=CG(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},_W=(e,t)=>{let i,n,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-eW?e.strstart-(e.w_size-eW):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+$G;let p=d[o+s-1],_=d[o+s];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+s]===_&&d[i+s-1]===p&&d[i]===d[o]&&d[++i]===d[o+1]){o+=2,i++;do{}while(d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&os){if(e.match_start=t,s=n,n>=a)break;p=d[o+s-1],_=d[o+s]}}}while((t=u[t&l])>c&&0!=--r);return s<=e.lookahead?s:e.lookahead},EW=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-eW)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),aW(e),n+=t),0===e.strm.avail_in)break;if(i=pW(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=cW(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=cW(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,n,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outn+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,dW(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(pW(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===s);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(pW(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=o||(n||t===LG)&&t!==NG&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,s=t===LG&&0===e.strm.avail_in&&i===n?1:0,AG(e,e.block_start,i,s),e.block_start+=i,dW(e.strm)),s?3:1)},mW=(e,t)=>{let i,n;for(;;){if(e.lookahead=3&&(e.ins_h=cW(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-eW&&(e.match_length=_W(e,i)),e.match_length>=3)if(n=wG(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=cW(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=cW(e,e.ins_h,e.window[e.strstart+1]);else n=wG(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(lW(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===LG?(lW(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(lW(e,!1),0===e.strm.avail_out)?1:2},TW=(e,t)=>{let i,n,r;for(;;){if(e.lookahead=3&&(e.ins_h=cW(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=wG(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=cW(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(lW(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=wG(e,0,e.window[e.strstart-1]),n&&lW(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=wG(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===LG?(lW(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(lW(e,!1),0===e.strm.avail_out)?1:2};function SW(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const gW=[new SW(0,0,0,0,fW),new SW(4,4,8,4,mW),new SW(4,5,16,8,mW),new SW(4,6,32,32,mW),new SW(4,4,16,16,TW),new SW(8,16,32,32,TW),new SW(8,16,128,128,TW),new SW(8,32,128,256,TW),new SW(32,128,258,1024,TW),new SW(32,258,258,4096,TW)];function RW(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=qG,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*QG),this.dyn_dtree=new Uint16Array(2*(2*JG+1)),this.bl_tree=new Uint16Array(2*(2*XG+1)),sW(this.dyn_ltree),sW(this.dyn_dtree),sW(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(ZG+1),this.heap=new Uint16Array(2*zG+1),sW(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*zG+1),sW(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const CW=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==tW&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==iW&&t.status!==nW?1:0},IW=e=>{if(CW(e))return rW(e,xG);e.total_in=e.total_out=0,e.data_type=YG;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?tW:iW,e.adler=2===t.wrap?0:1,t.last_flush=-2,yG(t),MG},vW=e=>{const t=IW(e);return t===MG&&(e=>{e.window_size=2*e.w_size,sW(e.head),e.max_lazy_match=gW[e.level].max_lazy,e.good_match=gW[e.level].good_length,e.nice_match=gW[e.level].nice_length,e.max_chain_length=gW[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},yW=(e,t,i,n,r,o)=>{if(!e)return xG;let s=1;if(t===BG&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||i!==qG||n<8||n>15||t<0||t>9||o<0||o>HG||8===n&&1!==s)return rW(e,xG);8===n&&(n=9);const a=new RW;return e.state=a,a.strm=e,a.status=tW,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<{if(CW(e)||t>kG||t<0)return e?rW(e,xG):xG;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===nW&&t!==LG)return rW(e,0===e.avail_out?FG:xG);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(dW(e),0===e.avail_out)return i.last_flush=-1,MG}else if(0===e.avail_in&&oW(t)<=oW(n)&&t!==LG)return rW(e,FG);if(i.status===nW&&0!==e.avail_in)return rW(e,FG);if(i.status===tW&&0===i.wrap&&(i.status=iW),i.status===tW){let t=qG+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=GG||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,hW(i,t),0!==i.strstart&&(hW(i,e.adler>>>16),hW(i,65535&e.adler)),e.adler=1,i.status=iW,dW(e),0!==i.pending)return i.last_flush=-1,MG}if(57===i.status)if(e.adler=0,uW(i,31),uW(i,139),uW(i,8),i.gzhead)uW(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),uW(i,255&i.gzhead.time),uW(i,i.gzhead.time>>8&255),uW(i,i.gzhead.time>>16&255),uW(i,i.gzhead.time>>24&255),uW(i,9===i.level?2:i.strategy>=GG||i.level<2?4:0),uW(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(uW(i,255&i.gzhead.extra.length),uW(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=CG(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(uW(i,0),uW(i,0),uW(i,0),uW(i,0),uW(i,0),uW(i,9===i.level?2:i.strategy>=GG||i.level<2?4:0),uW(i,3),i.status=iW,dW(e),0!==i.pending)return i.last_flush=-1,MG;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=CG(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,dW(e),0!==i.pending)return i.last_flush=-1,MG;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=CG(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=CG(e.adler,i.pending_buf,i.pending-n,n)),dW(e),0!==i.pending)return i.last_flush=-1,MG;n=0}t=i.gzindexn&&(e.adler=CG(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=CG(e.adler,i.pending_buf,i.pending-n,n)),dW(e),0!==i.pending)return i.last_flush=-1,MG;n=0}t=i.gzindexn&&(e.adler=CG(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(dW(e),0!==i.pending))return i.last_flush=-1,MG;uW(i,255&e.adler),uW(i,e.adler>>8&255),e.adler=0}if(i.status=iW,dW(e),0!==i.pending)return i.last_flush=-1,MG}if(0!==e.avail_in||0!==i.lookahead||t!==NG&&i.status!==nW){let n=0===i.level?fW(i,t):i.strategy===GG?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(EW(e),0===e.lookahead)){if(t===NG)return 1;break}if(e.match_length=0,i=wG(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(lW(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===LG?(lW(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(lW(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===WG?((e,t)=>{let i,n,r,o;const s=e.window;for(;;){if(e.lookahead<=$G){if(EW(e),e.lookahead<=$G&&t===NG)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){o=e.strstart+$G;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=wG(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=wG(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(lW(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===LG?(lW(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(lW(e,!1),0===e.strm.avail_out)?1:2})(i,t):gW[i.level].func(i,t);if(3!==n&&4!==n||(i.status=nW),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),MG;if(2===n&&(t===DG?OG(i):t!==kG&&(AG(i,0,0,!1),t===PG&&(sW(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),dW(e),0===e.avail_out))return i.last_flush=-1,MG}return t!==LG?MG:i.wrap<=0?UG:(2===i.wrap?(uW(i,255&e.adler),uW(i,e.adler>>8&255),uW(i,e.adler>>16&255),uW(i,e.adler>>24&255),uW(i,255&e.total_in),uW(i,e.total_in>>8&255),uW(i,e.total_in>>16&255),uW(i,e.total_in>>24&255)):(hW(i,e.adler>>>16),hW(i,65535&e.adler)),dW(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?MG:UG)},bW=(e,t)=>{let i=t.length;if(CW(e))return xG;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==tW||n.lookahead)return xG;if(1===r&&(e.adler=gG(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(sW(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,EW(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=cW(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,EW(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,n.wrap=r,MG},wW={deflateInit:(e,t)=>yW(e,t,qG,15,8,KG),deflateInit2:yW,deflateReset:vW,deflateResetKeep:IW,deflateSetHeader:(e,t)=>CW(e)||2!==e.state.wrap?xG:(e.state.gzhead=t,MG),deflate:AW,deflateEnd:e=>{if(CW(e))return xG;const t=e.state.status;return e.state=null,t===iW?rW(e,VG):MG},deflateSetDictionary:bW,deflateInfo:"pako deflate (from Nodeca project)"};const OW=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var NW={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)OW(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;PW[254]=PW[254]=1;var LW={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,o,s=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const o=new Array(2*i);for(r=0,n=0;n4)o[r++]=65533,n+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&n1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&DW)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+PW[e[i]]>t?i:t}};var kW=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const MW=Object.prototype.toString,{Z_NO_FLUSH:UW,Z_SYNC_FLUSH:xW,Z_FULL_FLUSH:VW,Z_FINISH:FW,Z_OK:BW,Z_STREAM_END:jW,Z_DEFAULT_COMPRESSION:GW,Z_DEFAULT_STRATEGY:WW,Z_DEFLATED:HW}=vG;function KW(e){this.options=NW.assign({level:GW,method:HW,chunkSize:16384,windowBits:15,memLevel:8,strategy:WW},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kW,this.strm.avail_out=0;let i=wW.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==BW)throw new Error(IG[i]);if(t.header&&wW.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?LW.string2buf(t.dictionary):"[object ArrayBuffer]"===MW.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=wW.deflateSetDictionary(this.strm,e),i!==BW)throw new Error(IG[i]);this._dict_set=!0}}function YW(e,t){const i=new KW(t);if(i.push(e,!0),i.err)throw i.msg||IG[i.err];return i.result}KW.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?FW:UW,"string"==typeof e?i.input=LW.string2buf(e):"[object ArrayBuffer]"===MW.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(o===xW||o===VW)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=wW.deflate(i,o),r===jW)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=wW.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===BW;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},KW.prototype.onData=function(e){this.chunks.push(e)},KW.prototype.onEnd=function(e){e===BW&&(this.result=NW.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var qW={Deflate:KW,deflate:YW,deflateRaw:function(e,t){return(t=t||{}).raw=!0,YW(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,YW(e,t)},constants:vG};const zW=16209;var JW=function(e,t){let i,n,r,o,s,a,c,d,l,u,h,p,_,E,f,m,T,S,g,R,C,I,v,y;const A=e.state;i=e.next_in,v=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,u=A.window,h=A.hold,p=A.bits,_=A.lencode,E=A.distcode,f=(1<>>24,h>>>=S,p-=S,S=T>>>16&255,0===S)y[r++]=65535&T;else{if(!(16&S)){if(0==(64&S)){T=_[(65535&T)+(h&(1<>>=S,p-=S),p<15&&(h+=v[i++]<>>24,h>>>=S,p-=S,S=T>>>16&255,!(16&S)){if(0==(64&S)){T=E[(65535&T)+(h&(1<a){e.msg="invalid distance too far back",A.mode=zW;break e}if(h>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&A.sane){e.msg="invalid distance too far back",A.mode=zW;break e}if(C=0,I=u,0===l){if(C+=c-S,S2;)y[r++]=I[C++],y[r++]=I[C++],y[r++]=I[C++],g-=3;g&&(y[r++]=I[C++],g>1&&(y[r++]=I[C++]))}else{C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],g-=3}while(g>2);g&&(y[r++]=y[C++],g>1&&(y[r++]=y[C++]))}break}}break}}while(i>3,i-=g,p-=g<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,_,E=0,f=0,m=0,T=0,S=0,g=0,R=0,C=0,I=0,v=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=XW;E++)A[E]=0;for(f=0;f=1&&0===A[T];T--);if(S>T&&(S=T),0===T)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(m=1;m0&&(0===e||1!==T))return-1;for(b[1]=0,E=1;E852||2===e&&I>592)return 1;for(;;){w=E-R,s[f]+1<_?(O=0,N=s[f]):s[f]>=_?(O=D[s[f]-_],N=y[s[f]-_]):(O=96,N=0),d=1<>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<>=1;if(0!==d?(v&=d-1,v+=d):v=0,f++,0==--A[E]){if(E===T)break;E=t[i+s[f]]}if(E>S&&(v&h)!==u){for(0===R&&(R=S),p+=m,g=E-R,C=1<852||2===e&&I>592)return 1;u=v&h,r[u]=S<<24|g<<16|p-o|0}}return 0!==v&&(r[p+v]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:iH,Z_BLOCK:nH,Z_TREES:rH,Z_OK:oH,Z_STREAM_END:sH,Z_NEED_DICT:aH,Z_STREAM_ERROR:cH,Z_DATA_ERROR:dH,Z_MEM_ERROR:lH,Z_BUF_ERROR:uH,Z_DEFLATED:hH}=vG,pH=16180,_H=16190,EH=16191,fH=16192,mH=16194,TH=16199,SH=16200,gH=16206,RH=16209,CH=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function IH(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const vH=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},yH=e=>{if(vH(e))return cH;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=pH,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,oH},AH=e=>{if(vH(e))return cH;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,yH(e)},bH=(e,t)=>{let i;if(vH(e))return cH;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?cH:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,AH(e))},wH=(e,t)=>{if(!e)return cH;const i=new IH;e.state=i,i.strm=e,i.window=null,i.mode=pH;const n=bH(e,t);return n!==oH&&(e.state=null),n};let OH,NH,DH=!0;const PH=e=>{if(DH){OH=new Int32Array(512),NH=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(tH(1,e.lens,0,288,OH,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;tH(2,e.lens,0,32,NH,0,e.work,{bits:5}),DH=!1}e.lencode=OH,e.lenbits=9,e.distcode=NH,e.distbits=5},LH=(e,t,i,n)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>n&&(r=n),o.window.set(t.subarray(i-n,i-n+r),o.wnext),(n-=r)?(o.window.set(t.subarray(i-n,i),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,n,r,o,s,a,c,d,l,u,h,p,_,E,f,m,T,S,g,R,C,I,v=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(vH(e)||!e.output||!e.input&&0!==e.avail_in)return cH;i=e.state,i.mode===EH&&(i.mode=fH),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,I=oH;e:for(;;)switch(i.mode){case pH:if(0===i.wrap){i.mode=fH;break}for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=CG(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=RH;break}if((15&d)!==hH){e.msg="unknown compression method",i.mode=RH;break}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg="invalid window size",i.mode=RH;break}i.dmax=1<>8&1),512&Pj(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=CG(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=CG(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>8),512&Pj(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=CG(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&Pj(i)){for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=CG(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&Pj(i)&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(o,o+p),C)),512&Pj(i)&&4&i.wrap&&(i.check=CG(i.check,n,p,o)),a-=p,o+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&Pj(i)){if(0===a)break e;p=0;do{C=n[o+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C))}while(C&&p>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=EH;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>=7&l,l-=7&l,i.mode=gH;break}for(;l<3;){if(0===a)break e;a--,d+=n[o++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(PH(i),i.mode=TH,t===rH){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=RH}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=RH;break}if(i.length=65535&d,d=0,l=0,i.mode=mH,t===rH)break e;case mH:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,i.length-=p;break}i.mode=EH;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[o++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=RH;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},I=tH(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid code lengths set",i.mode=RH;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,m=v>>>16&255,T=65535&v,!(f<=l);){if(0===a)break e;a--,d+=n[o++]<>>=f,l-=f,i.lens[i.have++]=T;else{if(16===T){for(b=f+2;l>>=f,l-=f,0===i.have){e.msg="invalid bit length repeat",i.mode=RH;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===T){for(b=f+3;l>>=f,l-=f,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=f+7;l>>=f,l-=f,C=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=RH;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===RH)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=RH;break}if(i.lenbits=9,A={bits:i.lenbits},I=tH(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid literal/lengths set",i.mode=RH;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},I=tH(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,I){e.msg="invalid distances set",i.mode=RH;break}if(i.mode=TH,t===rH)break e;case TH:i.mode=SH;case SH:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=d,i.bits=l,JW(e,h),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===EH&&(i.back=-1);break}for(i.back=0;v=i.lencode[d&(1<>>24,m=v>>>16&255,T=65535&v,!(f<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],f=v>>>24,m=v>>>16&255,T=65535&v,!(S+f<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=f,l-=f,i.back+=f,i.length=T,0===m){i.mode=16205;break}if(32&m){i.back=-1,i.mode=EH;break}if(64&m){e.msg="invalid literal/length code",i.mode=RH;break}i.extra=15&m,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;v=i.distcode[d&(1<>>24,m=v>>>16&255,T=65535&v,!(f<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],f=v>>>24,m=v>>>16&255,T=65535&v,!(S+f<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=f,l-=f,i.back+=f,64&m){e.msg="invalid distance code",i.mode=RH;break}i.offset=T,i.extra=15&m,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=RH;break}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=RH;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=s-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[s++]=E[_++]}while(--p);0===i.length&&(i.mode=SH);break;case 16205:if(0===c)break e;r[s++]=i.length,c--,i.mode=SH;break;case gH:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[o++]<wH(e,15),inflateInit2:wH,inflate:kH,inflateEnd:e=>{if(vH(e))return cH;let t=e.state;return t.window&&(t.window=null),e.state=null,oH},inflateGetHeader:(e,t)=>{if(vH(e))return cH;const i=e.state;return 0==(2&i.wrap)?cH:(i.head=t,t.done=!1,oH)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,o;return vH(e)?cH:(n=e.state,0!==n.wrap&&n.mode!==_H?cH:n.mode===_H&&(r=1,r=gG(r,t,i,0),r!==n.check)?dH:(o=LH(e,t,i,i),o?(n.mode=16210,lH):(n.havedict=1,oH)))},inflateInfo:"pako inflate (from Nodeca project)"};var UH=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const xH=Object.prototype.toString,{Z_NO_FLUSH:VH,Z_FINISH:FH,Z_OK:BH,Z_STREAM_END:jH,Z_NEED_DICT:GH,Z_STREAM_ERROR:WH,Z_DATA_ERROR:HH,Z_MEM_ERROR:KH}=vG;function YH(e){this.options=NW.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kW,this.strm.avail_out=0;let i=MH.inflateInit2(this.strm,t.windowBits);if(i!==BH)throw new Error(IG[i]);if(this.header=new UH,MH.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=LW.string2buf(t.dictionary):"[object ArrayBuffer]"===xH.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=MH.inflateSetDictionary(this.strm,t.dictionary),i!==BH)))throw new Error(IG[i])}function qH(e,t){const i=new YH(t);if(i.push(e),i.err)throw i.msg||IG[i.err];return i.result}YH.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?FH:VH,"[object ArrayBuffer]"===xH.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),o=MH.inflate(i,s),o===GH&&r&&(o=MH.inflateSetDictionary(i,r),o===BH?o=MH.inflate(i,s):o===HH&&(o=GH));i.avail_in>0&&o===jH&&i.state.wrap>0&&0!==e[i.next_in];)MH.inflateReset(i),o=MH.inflate(i,s);switch(o){case WH:case HH:case GH:case KH:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===jH))if("string"===this.options.to){let e=LW.utf8border(i.output,i.next_out),t=i.next_out-e,r=LW.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==BH||0!==a){if(o===jH)return o=MH.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},YH.prototype.onData=function(e){this.chunks.push(e)},YH.prototype.onEnd=function(e){e===BH&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=NW.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var zH={Inflate:YH,inflate:qH,inflateRaw:function(e,t){return(t=t||{}).raw=!0,qH(e,t)},ungzip:qH,constants:vG};const{Deflate:JH,deflate:XH,deflateRaw:QH,gzip:ZH}=qW,{Inflate:$H,inflate:eK,inflateRaw:tK,ungzip:iK}=zH;var nK=XH,rK=eK,oK=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(oK||{});class sK{constructor(){ng(this,"_sequence",0),ng(this,"_startTime",Date.now()),ng(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;Oy("SHOW_DATASTREAM2_LOG")&&Jy.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let o=0;if(r.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,r.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,r.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),o),o+=e.byteLength}if(n.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let o,s;if(i+=4,Oy("SHOW_DATASTREAM2_LOG")&&Jy.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){s=this.deserializeExtension(e.slice(i)),i+=2+s.length,o=e.slice(i);let t=!1;if(s.datas.length>0){const e=s.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,i),n.forEach((e=>{t?(s.setUint8(a++,e.id),s.setUint8(a++,e.length),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(s.setUint8(a++,e.id|e.length<<4),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const o=n===oK.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),s.push({id:e,length:t,data:i})}if(c!==r)throw Error("parse error");return{profile:n,length:r,datas:s}}decompress(e){return rK(new Uint8Array(e))}compress(e){return nK(new Uint8Array(e))}}const aK={name:"DataStream",create:(e,t)=>{const i=t?new cM(e):new dM(e);return i.useDataStream(new sK),i}};class cK extends mv{constructor(e,t,i){super(),ng(this,"ws",void 0),ng(this,"requestId",1),ng(this,"heartBeatTimer",void 0),ng(this,"joinInfo",void 0),ng(this,"clientId",void 0),ng(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),ng(this,"onClose",(e=>{this.emit("close"),this.dispose()})),ng(this,"onMessage",(e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new yw("cross-channel-".concat(this.clientId),i),this.ws.on(fb.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(fb.CONNECTED,this.onOpen),this.ws.on(fb.ON_MESSAGE,this.onMessage),this.ws.on(fb.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Gh(((t,i)=>{const n=window.setTimeout((()=>{i(new mb(tv.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new mb(tv.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(n),i(new mb(tv.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new mb(tv.WS_DISCONNECT);const t=()=>new Gh(((e,t)=>{this.ws.once(fb.CLOSED,(()=>t(new mb(tv.WS_ABORT)))),this.ws.once(fb.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Gh(((e,t)=>{const n=()=>{t(new mb(tv.WS_ABORT))};this.ws.once(fb.RECONNECTING,n),this.ws.once(fb.CLOSED,n),this.once("req_".concat(i),e),Qv(3e3).then((()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(fb.RECONNECTING,n),this.ws.off(fb.CLOSED,n),t(new mb(tv.TIMEOUT,"cross channel ws request timeout"))}))})),r=await n;if(!r||200!==r.code)throw new mb(tv.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(fb.REQUEST_NEW_URLS),this.ws.on(fb.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class dK extends mv{set state(e){e!==this._state&&(e!==Db.RELAY_STATE_FAILURE&&(this.errorCode=Pb.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),ng(this,"joinInfo",void 0),ng(this,"sid",void 0),ng(this,"clientId",void 0),ng(this,"cancelToken",pI.CancelToken.source()),ng(this,"workerToken",void 0),ng(this,"requestId",0),ng(this,"signal",void 0),ng(this,"prevChannelMediaConfig",void 0),ng(this,"httpRetryConfig",void 0),ng(this,"_resolution",void 0),ng(this,"_state",Db.RELAY_STATE_IDLE),ng(this,"errorCode",Pb.RELAY_OK),ng(this,"onStatus",(e=>{Jy.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",Nb.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",Nb.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=Pb.SRC_TOKEN_EXPIRED,this.state=Db.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=Pb.DEST_TOKEN_EXPIRED,this.state=Db.RELAY_STATE_FAILURE))})),ng(this,"onReconnect",(async()=>{Jy.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Nb.NETWORK_DISCONNECTED),this.state=Db.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==Db.RELAY_STATE_IDLE&&(Jy.error("auto restart channel media relay failed",e.toString()),this.errorCode=Pb.SERVER_CONNECTION_LOST,this.state=Db.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=$v(),this.signal=new cK(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==Db.RELAY_STATE_IDLE)throw new mb(tv.INVALID_OPERATION);this.state=Db.RELAY_STATE_CONNECTING,await this.connect(),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new mb(tv.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new mb(tv.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new mb(tv.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==Db.RELAY_STATE_RUNNING)throw new mb(tv.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==Db.RELAY_STATE_RUNNING)throw new mb(tv.INVALID_OPERATION);const t=this.genMessage(Ob.SetVideoProfile);await this.signal.request(t),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),Jy.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=Db.RELAY_STATE_IDLE,this.dispose()}dispose(){Jy.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=pI.CancelToken.source(),this.state=Db.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await PU(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",Nb.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(Ob.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(Ob.SetSdkProfile,e);await this.signal.request(i),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(Ob.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Nb.PACKET_JOINED_SRC_CHANNEL),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(Ob.SetSourceUserId,e);await this.signal.request(r),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(Ob.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Nb.PACKET_JOINED_DEST_CHANNEL),Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const s=this.genMessage(Ob.StartPacketTransfer,e);await this.signal.request(s),this.emit("event",Nb.PACKET_SENT_TO_DEST_CHANNEL),this.state=Db.RELAY_STATE_RUNNING,Jy.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(Ob.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",Nb.PACKET_UPDATE_DEST_CHANNEL),Jy.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(Ob.StopPacketTransfer);await this.signal.request(e),Jy.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:Cy,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.22.0"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case Ob.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case Ob.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new mb(tv.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case Ob.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new mb(tv.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case Ob.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new mb(tv.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},o;case Ob.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case Ob.Reconnect:return o.clientRequest={command:"Reconnect"},o;case Ob.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case Ob.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new mb(tv.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},o;case Ob.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const lK={name:"ChannelMediaRelay",create:function(e){return new dK(e.joinInfo,e.clientId,e.websocketRetryConfig||hy,e.httpRetryConfig||hy,e.resolution)}};function uK(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hK(e){for(var t=1;t{this.reconnectMode="retry",this.startPingPong()})),ng(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(rA.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===gb.TRANSCODE?1:2}),this.emit(yb.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new yw("live-streaming",i),this.websocket.on(fb.CONNECTED,this.handleWebSocketOpen),this.websocket.on(fb.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(fb.REQUEST_NEW_URLS,((e,t)=>{Pv(this,yb.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(fb.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new mb(tv.UNEXPECTED_ERROR);const s=hK({command:e,sdkVersion:"4.22.0"===Cy?"0.0.1":Cy,seq:o,requestId:o,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new mb(tv.WS_DISCONNECT);const a=()=>new Gh(((e,t)=>{this.websocket.once(fb.CLOSED,(()=>t(new mb(tv.WS_ABORT)))),this.websocket.once(fb.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Gh(((e,t)=>{const i=()=>{t(new mb(tv.WS_ABORT))};this.websocket.once(fb.RECONNECTING,i),this.websocket.once(fb.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&rA.workerEvent(this.spec.sid,hK(hK({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let l=null;try{l=await c}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&rA.workerEvent(this.spec.sid,hK(hK({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.22.0"===Cy?"0.0.1":Cy;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case bb.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void Jy.warning("live stream response already exists stream");case bb.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case bb.LIVE_STREAM_RESPONSE_BAD_STREAM:case bb.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new mb(tv.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case bb.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case bb.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new mb(tv.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case bb.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new mb(tv.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(yb.WARNING,t,e.serverResponse.url)}case bb.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new mb(tv.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(yb.WARNING,t,e.serverResponse.url)}case bb.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case bb.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new mb(tv.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case bb.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new mb(tv.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(yb.WARNING,t,e.serverResponse.url)}case bb.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case bb.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case bb.LIVE_STREAM_RESPONSE_WORKER_LOST:case bb.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case bb.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case bb.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new mb(tv.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(ey)}),6e3)}}function _K(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function EK(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:hy,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:hy;super(),ng(this,"onLiveStreamWarning",void 0),ng(this,"onLiveStreamError",void 0),ng(this,"spec",void 0),ng(this,"retryTimeout",1e4),ng(this,"connection",void 0),ng(this,"httpRetryConfig",void 0),ng(this,"wsRetryConfig",void 0),ng(this,"streamingTasks",new Map),ng(this,"isStartingStreamingTask",!1),ng(this,"taskMutex",new ly("live-streaming")),ng(this,"cancelToken",pI.CancelToken.source()),ng(this,"transcodingConfig",void 0),ng(this,"uapResponse",void 0),ng(this,"lastTaskId",1),ng(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=EK(EK({},vb),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(Jy.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>EK(EK(EK({},Rb),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){dv(e.width)||ov(e.width,"config.width",0,1e4),dv(e.height)||ov(e.height,"config.height",0,1e4),dv(e.videoBitrate)||ov(e.videoBitrate,"config.videoBitrate",1,1e6),dv(e.videoFrameRate)||ov(e.videoFrameRate,"config.videoFrameRate"),dv(e.lowLatency)||nv(e.lowLatency,"config.lowLatency"),dv(e.audioSampleRate)||rv(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),dv(e.audioBitrate)||ov(e.audioBitrate,"config.audioBitrate",1,128),dv(e.audioChannels)||rv(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),dv(e.videoGop)||ov(e.videoGop,"config.videoGop"),dv(e.videoCodecProfile)||rv(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),dv(e.userCount)||ov(e.userCount,"config.userCount",0,17),dv(e.backgroundColor)||ov(e.backgroundColor,"config.backgroundColor",0,16777215),dv(e.userConfigExtraInfo)||av(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!dv(e.transcodingUsers)&&(cv(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{Sb(e.uid),dv(e.x)||ov(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),dv(e.y)||ov(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),dv(e.width)||ov(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),dv(e.height)||ov(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),dv(e.zOrder)||ov(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),dv(e.alpha)||ov(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),dv(e.watermark)||Ib(e.watermark,"watermark"),dv(e.backgroundImage)||Ib(e.backgroundImage,"backgroundImage"),e.images&&!dv(e.images)&&(cv(e.images,"config.images"),e.images.forEach(((e,t)=>{Ib(e,"images[".concat(t,"]"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>EK(EK(EK({},Cb),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(EK(EK(EK({},Cb),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(EK(EK(EK({},Cb),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>EK({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Gh.resolve(e.uid):bU(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Gh.all(n)).forEach(((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(Jw(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});Jy.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{Jy.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{Jy.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{Jy.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,i){if(!this.transcodingConfig&&t===gb.TRANSCODE)throw new mb(tv.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const n={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};Jy.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&i)return void r();if(this.streamingTasks.get(e)&&!i)return r(),new mb(tv.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case gb.TRANSCODE:n.transcodingConfig=EK({},this.transcodingConfig);case gb.RAW:}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new Gh(((t,n)=>{Qv(this.retryTimeout).then((()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),a=await Gh.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===gb.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,Jy.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:n,mode:t,url:e,taskId:o}),r()}catch(n){if(r(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Gh(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new mb(tv.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{Jy.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===gb.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{Jy.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(i)}))}resetAllTask(){var e;const t=Array.from(Jw(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=pI.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new mb(tv.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await Pv(this,Ab.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new pK(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(yb.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(yb.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(yb.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new mb(tv.UNEXPECTED_ERROR,"can not get new live streaming address list"));Pv(this,Ab.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(i)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case bb.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case bb.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new mb(tv.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return Jy.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case bb.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new mb(tv.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case bb.LIVE_STREAM_RESPONSE_WORKER_LOST:case bb.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(Jw(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(Jy.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new mb(tv.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{Jy.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)})).catch((e=>{Jy.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const mK={name:"LiveStreaming",create:function(e){return new fK(e.joinInfo,e.websocketRetryConfig||hy,e.httpRetryConfig||hy)}};function TK(e){let t=OK();return function(e,t){let i=e.appId;void 0!==i&&(WK(t,10),UK(t,i));let n=e.cid;void 0!==n&&(WK(t,16),WK(t,n));let r=e.cname;void 0!==r&&(WK(t,26),UK(t,r));let o=e.deviceId;void 0!==o&&(WK(t,34),UK(t,o));let s=e.elapse;void 0!==s&&(WK(t,40),HK(t,s));let a=e.fileSize;void 0!==a&&(WK(t,48),HK(t,bK(a)));let c=e.height;void 0!==c&&(WK(t,56),HK(t,bK(c)));let d=e.jpg;void 0!==d&&(WK(t,66),WK(t,d.length),function(e,t){let i=LK(e,t.length);e.bytes.set(t,i)}(t,d));let l=e.networkType;void 0!==l&&(WK(t,72),HK(t,bK(l)));let u=e.osType;void 0!==u&&(WK(t,80),HK(t,bK(u)));let h=e.requestId;void 0!==h&&(WK(t,90),UK(t,h));let p=e.sdkVersion;void 0!==p&&(WK(t,98),UK(t,p));let _=e.sequence;void 0!==_&&(WK(t,104),HK(t,bK(_)));let E=e.sid;void 0!==E&&(WK(t,114),UK(t,E));let f=e.timestamp;void 0!==f&&(WK(t,120),HK(t,f));let m=e.uid;void 0!==m&&(WK(t,128),WK(t,m));let T=e.vid;void 0!==T&&(WK(t,136),WK(t,T));let S=e.width;void 0!==S&&(WK(t,144),HK(t,bK(S)));let g=e.service;void 0!==g&&(WK(t,152),WK(t,g));let R=e.callbackData;void 0!==R&&(WK(t,162),UK(t,R));let C=e.jpgEncryption;void 0!==C&&(WK(t,168),WK(t,C));let I=e.requestType;void 0!==I&&(WK(t,176),WK(t,I));let v=e.scorePorn;void 0!==v&&(WK(t,185),jK(t,v));let y=e.scoreSexy;void 0!==y&&(WK(t,193),jK(t,y));let A=e.scoreNeutral;void 0!==A&&(WK(t,201),jK(t,A));let b=e.scene;void 0!==b&&(WK(t,208),WK(t,b));let w=e.ossFilePrefix;void 0!==w&&(WK(t,218),UK(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){WK(t,226);let i=OK();RK(e,i),WK(t,i.limit),xK(t,i),NK(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function SK(e){return function(e){let t={};e:for(;!PK(e);){let i=GK(e);switch(i>>>3){case 0:break e;case 1:t.code=GK(e);break;case 2:t.msg=MK(e,GK(e));break;case 3:{let i=CK(e);t.data=gK(e),e.limit=i;break}default:IK(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function gK(e){let t={};e:for(;!PK(e);){let i=GK(e);switch(i>>>3){case 0:break e;case 1:t.requestId=MK(e,GK(e));break;case 2:t.requestType=GK(e)>>>0;break;case 3:t.scorePorn=BK(e);break;case 4:t.scoreSexy=BK(e);break;case 5:t.scoreNeutral=BK(e);break;case 6:t.requestScene=GK(e)>>>0;break;case 7:t.scene=GK(e)>>>0;break;default:IK(e,7&i)}}return t}function RK(e,t){let i=e.service;void 0!==i&&(WK(t,8),WK(t,i));let n=e.vendor;void 0!==n&&(WK(t,16),WK(t,n));let r=e.token;void 0!==r&&(WK(t,26),UK(t,r));let o=e.callbackUrl;void 0!==o&&(WK(t,34),UK(t,o))}function CK(e){let t=GK(e),i=e.limit;return e.limit=e.offset+t,i}function IK(e,t){switch(t){case 0:for(;128&VK(e););break;case 2:DK(e,GK(e));break;case 5:DK(e,4);break;case 1:DK(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let vK=new Float32Array(1);new Uint8Array(vK.buffer);let yK=new Float64Array(1),AK=new Uint8Array(yK.buffer);function bK(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let wK=[];function OK(){const e=wK.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function NK(e){wK.push(e)}function DK(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function PK(e){return e.offset>=e.limit}function LK(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function kK(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function MK(e,t){let i=kK(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function UK(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function xK(e,t){let i=LK(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e>>=0;t>=128;)FK(e,127&t|128),t>>>=7;FK(e,t)}function HK(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=LK(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}function KK(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const YK=new Map([["moderation",1],["supervise",2]]);function qK(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}class zK extends mv{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Zb.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=Jn(t=e.map((e=>YK.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),ng(this,"name","AgoraRTCVideoContentInspect"),ng(this,"_connectionState",Xb.CONNECTING),ng(this,"_innerConnectionState",void 0),ng(this,"sequence",0),ng(this,"inspectStartTime",void 0),ng(this,"workerManagerConnection",void 0),ng(this,"workerConnection",void 0),ng(this,"workerMessageLengthLimit",void 0),ng(this,"inspectIntervalMinimum",void 0),ng(this,"qualityRatio",void 0),ng(this,"_connectInfo",void 0),ng(this,"_cancelTokenSource",pI.CancelToken.source()),ng(this,"_retryConfig",void 0),ng(this,"wmSequence",0),ng(this,"inspectInterval",void 0),ng(this,"inspectTimer",null),ng(this,"ossFilePrefix",void 0),ng(this,"extraInfo",void 0),ng(this,"_inspectType",void 0),ng(this,"_inspectMode",void 0),ng(this,"_quality",1),ng(this,"qualityTimer",null),ng(this,"_inspectId",void 0),ng(this,"_needWorkUrlOnly",!1),ng(this,"inspectImage",(()=>{if(this.connectionState!==Xb.CONNECTED)throw new mb(tv.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===Xb.CONNECTED?this.requestToInspectImage():Jy.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval{this._innerConnectionState=e,Jy.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Qb[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new yw("worker-"+this._inspectId,hy),this.handleWorkerEvents()}async init(e,t){this.emit(Zb.STATE_CHANGE,Qb.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Gh(((n,r)=>{this.on(Zb.CONNECTION_STATE_CHANGE,((e,t)=>{t===Xb.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=Oy("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;RU++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:RU,seq:RU,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return _y((async()=>{h=Date.now();const e=await $M(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new mb(tv.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw Jy.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new mb(tv.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw Jy.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new mb(tv.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw Jy.error(e.toString()),e}const n=Oy("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=Oy("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(rA.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(rA.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==tv.OPERATION_ABORTED&&t.code!==tv.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(Zb.STATE_CHANGE,Qb.AP_CONNECTED);const{addressList:o}=r;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(Zb.STATE_CHANGE,Qb.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(fb.CONNECTED,(async()=>{this.emit(Zb.STATE_CHANGE,Qb.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.22.0",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(fb.CLOSED,(()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(Zb.STATE_CHANGE,Qb.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw Jy.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new mb(tv.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw Jy.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new mb(tv.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=Oy("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(Zb.STATE_CHANGE,Qb.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(Zb.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(fb.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(fb.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(fb.CONNECTED,(async()=>{this.emit(Zb.STATE_CHANGE,Qb.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=Xb.CONNECTED})),this.workerConnection.on(fb.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=SK(new Uint8Array(e.data));if(Oy("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&Jy.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(Zb.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=Jn(t=Object.keys(e)).call(t,((t,i)=>e[t]>e[i]?t:i),"porn"),r=Object.keys(e).find((e=>e===n));this.emit(Zb.INSPECT_RESULT,r)}else this.emit(Zb.INSPECT_RESULT,void 0,new mb(tv.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(Zb.INSPECT_RESULT,void 0,new mb(tv.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else Jy.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(Zb.INSPECT_RESULT,void 0,new mb(tv.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(fb.CLOSED,(()=>{this.connectionState=Xb.CLOSED})),this.workerConnection.on(fb.FAILED,(()=>{this.connectionState=Xb.CLOSED})),this.workerConnection.on(fb.RECONNECTING,(()=>{this.connectionState=this.connectionState===Xb.CONNECTED?Xb.RECONNECTING:Xb.CONNECTING})),this.workerConnection.on(fb.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this.workerConnection.on(fb.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(Zb.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=kv(this,Zb.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(Zb.INSPECT_RESULT,void 0,new mb(tv.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(Zb.INSPECT_RESULT,void 0,new mb(tv.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await lL(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+Zv(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:qK(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.22.0",sequence:this.sequence,sid:s,timestamp:qK(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=TK(h);if(p.byteLength{var t;if(!Dn(t=["supervise","moderation"]).call(t,e))throw new mb(tv.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new mb(tv.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new zK(t)}};wy("PROCESS_ID","process-".concat(Zv(8,""),"-").concat(Zv(4,""),"-").concat(Zv(4,""),"-").concat(Zv(4,""),"-").concat(Zv(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void Jy.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Jy.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(by,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;Ny[e]=n,by[e]=n}}))}catch(t){Jy.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(Ny.AREAS)&&Ny.AREAS.length>0&&cU(Ny.AREAS,!0);const XK=(e,t,i)=>{Jy.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),wy(e,t,i)};pF(lK,!1),pF(mK,!1),pF(wB,!1),pF(JK,!1),pF(aK,!1);const QK=function(e){const t=new mv,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===ew.SECURITY_POLICY_VIOLATION&&bj(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return yj(yj({},i),n)}({__TRACK_LIST__:JD,VERSION:Cy,BUILD:Ay,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:XK,getParameter:Oy,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return LD().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new mb(tv.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=rA.reportApiInvoke(null,{name:gv.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:Rv.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n),t&&zI()&&MI(75)&&(new e).close()}catch(e){return Jy.error("check system requirement failed: ",e),!1}let i=!1;const n=vI();n.name===gI.CHROME&&Number(n.version)>=58&&("WebKit"!==CI.engine.name||function(){const e=vI();if(wI()){if(e.os===SI.MAC_OS)return!0;if(e.os===SI.IOS){const e=CI.os.version&&CI.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}())&&(i=!0),(n.name===gI.FIREFOX&&Number(n.version)>=56||n.name===gI.OPERA&&Number(n.version)>=45||n.name===gI.SAFARI&&Number(n.version)>=11||"WebKit"===n.name&&(LI()||KI())&&n.osVersion&&Number(n.osVersion.split(".")[0])>=11||YI()||vI().name===gI.QQ)&&(i=!0),Jy.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return YP.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return YP.getRecordingDevices(e)},getCameras:function(e){return YP.getCamerasDevices(e)},getElectronScreenSources:VP,getPlaybackDevices:function(e){return YP.getSpeakers(e)},createClient:function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=rA.reportApiInvoke(null,{name:gv.CREATE_CLIENT,options:[t],tag:Rv.TRACER});try{!function(e){rv(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),rv(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&rv(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&av(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&Av(e.turnServer),void 0!==e.httpRetryConfig&&Cv(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&Cv(e.websocketRetryConfig)}(t)}catch(e){throw i.onError(e),e}return(VI(16,0,!0)||FI(16,0,!0))&&("vp9"===t.codec&&(t.codec="vp8",Jy.debug("browser not support vp9, force use vp8")),wy("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),i.onSuccess(),new Tj(mj(mj({forceWaitGatewayResponse:!0},t),{},{role:Dn(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}))},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=Oy("CAMERA_CAPTURE_CONFIG"),i=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_CAM_VIDEO_TRACK,options:[IP({},e),t]});t&&(e.encoderConfig=t);const n=aL(e),r=Zv(8,"track-cam-");let o=null;Jy.info("start create camera video track with config",JSON.stringify(e),"trackId",r);try{o=(await GP({video:n},r)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new iv(tv.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(Jy)}e.optimizationMode&&Hk(r,o,e,HD(e.encoderConfig));const s=new Wk(o,e,n,e.scalabiltyMode?YD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r);return i.onSuccess(s.getTrackId()),Jy.info("create camera video success, trackId:",r),s},createCustomVideoTrack:function(e){const t=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new Gk(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?YD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,Zv(8,"track-cus-"),[ZD.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),Jy.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_SCREEN_VIDEO_TRACK,options:[IP({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const n=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&OI()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:o}=e;(kI(107)||UI(107)||BI(93))&&(i&&(rv(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(rv(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(rv(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(kI(105)||UI(105)||BI(91))&&o&&(rv(o,"systemAudio",["exclude","include"]),t.systemAudio=o),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const s=e.encoderConfig?KD(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:s?s.width:void 0,maxHeight:s?s.height:void 0},s&&(s.frameRate&&("number"==typeof s.frameRate?(t.mandatory.maxFrameRate=s.frameRate,t.mandatory.minFrameRate=s.frameRate):(t.mandatory.maxFrameRate=s.frameRate.max||s.frameRate.ideal||s.frameRate.exact||void 0,t.mandatory.minFrameRate=s.frameRate.min||s.frameRate.ideal||s.frameRate.exact||void 0),t.frameRate=s.frameRate),s.width&&(t.width=s.width),s.height&&(t.height=s.height)),t}(e),r=Zv(8,"track-scr-v-");let o=null,s=null;const a=LD();if(!a.supportShareAudio&&"enable"===t){const e=new iv(tv.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw(Jy)}Jy.info("start create screen video track with config",e,"withAudio",t,"trackId",r);try{const e=await GP({screen:n,screenAudio:"auto"===t?a.supportShareAudio:"enable"===t},r);o=e.getVideoTracks()[0]||null,s=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new iv(tv.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(Jy)}if(!s&&"enable"===t){o&&o.stop();const e=new iv(tv.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(Jy)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(Hk(r,o,e,e.encoderConfig&&KD(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const c=new Gk(o,e.encoderConfig?KD(e.encoderConfig):{},e.scalabiltyMode?YD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[ZD.SCREEN_TRACK]);if(!s)return i.onSuccess(c.getTrackId()),Jy.info("create screen video track success","video:",c.getTrackId()),c;const d=new $L(s,void 0,Zv(8,"track-scr-a-"),!1);return i.onSuccess([c.getTrackId(),d.getTrackId()]),Jy.info("create screen video track success","video:",c.getTrackId(),"audio:",d.getTrackId()),[c,d]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=Oy("CAMERA_CAPTURE_CONFIG"),n=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const r=aL(t),o=cL(e),s=Zv(8,"track-mic-"),a=Zv(8,"track-cam-");let c=null,d=null;Jy.info("start create camera video track(".concat(a,") and microphone audio track(").concat(s,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await GP({audio:o,video:r},"".concat(s,"-").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw n.onError(e),e}if(!c||!d){const e=new iv(tv.UNEXPECTED_ERROR,"can not find tracks in media stream");return n.onError(e),e.throw(Jy)}t.optimizationMode&&Hk(a,d,t,HD(t.encoderConfig));const l=new ek(c,e,o,s),u=new Wk(d,t,r,t.scalabiltyMode?YD(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,a);return n.onSuccess([l.getTrackId(),u.getTrackId()]),Jy.info("create camera video track(".concat(a,") and microphone audio track(").concat(s,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=cL(e),n=Zv(8,"track-mic-");let r=null;Jy.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await GP({audio:i},n)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new iv(tv.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(Jy)}const o=new ek(r,e,i,n);return t.onSuccess(o.getTrackId()),Jy.info("create microphone audio track success, trackId:",n),o},createCustomAudioTrack:function(e){const t=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new $L(e.mediaStreamTrack,e.encoderConfig?zD(e.encoderConfig):{},Zv(8,"track-cus-"),!1);return Jy.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},s=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(Oy("DISABLE_WEBAUDIO"))throw new iv(tv.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const a=Zv(8,"track-buf-");Jy.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",a);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(e,t){let i=null;if("string"==typeof e){const t=rk.get(e);if(t)return Jy.debug("use cached audio resource: ",e),t;try{i=(await _y((()=>pI.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new iv(tv.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Gh(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new iv(tv.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new iv(tv.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=OP();return new Gh(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new iv(tv.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&rk.set(e,n),n}(r,i)}catch(e){return s.onError(e),e.throw(Jy)}const d=new nk(r),l=new tk(c,d,n?zD(n):{},a);return Jy.info("create buffer source audio track success, trackId:",a),s.onSuccess(l.getTrackId()),l},setAppType:function(e){if(Jy.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw Jy.debug("Invalid appType"),new mb(tv.INVALID_PARAMS,"invalid app type",e);wy("APP_TYPE",Math.floor(e))},setLogLevel:function(e){Jy.setLogLevel(e)},enableLogUpload:function(){Oy("USE_NEW_LOG")?wy("UPLOAD_LOG",!0):Jy.enableLogUpload()},disableLogUpload:function(){Oy("USE_NEW_LOG")?wy("UPLOAD_LOG",!1):Jy.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new vV},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof $L||e instanceof oM)){const e=new mb(tv.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof $L?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new Gh((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:n,maxVolumeLevel:o,result:t};Jy.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),i.onSuccess(s),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=rA.reportApiInvoke(null,{tag:Rv.TRACER,name:gv.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Gk||e instanceof rM)){const e=new mb(tv.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof Gk?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),o=document.createElement("video");o.style.width="1px",o.style.height="1px",o.setAttribute("muted",""),o.muted=!0,o.setAttribute("playsinline",""),o.controls=!1,(NI()||wI())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([r]),o.play();const s=document.createElement("canvas");s.width=160,s.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,o=0,s=null;return new Gh(((a,c)=>{function d(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new mb(tv.UNEXPECTED_ERROR,"can not get canvas 2d context.");return Jy.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e{r&&(r(),a(o))}),t),r=PP((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw i.onError(e),e}yF===gI.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return Jy.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:cU,audioElementPlayCenter:ZP,resumeAudioContext:function(){ZP.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){Ij.processExternalMediaAEC(e)},registerExtensions:function(e){const t=Oy("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Dn(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=Jy.extLog,i.reporter.hookApiInvoke=rA.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach((e=>{i.parameters[e]=Oy(e)}))})),XK("PLUGIN_INFO",t)},ChannelMediaRelayError:Pb,ChannelMediaRelayEvent:Nb,ChannelMediaRelayState:Db,RemoteStreamFallbackType:tP,RemoteStreamType:eP,ConnectionDisconnectedReason:vv,AudienceLatencyLevelType:Iv,AREAS:xb,preload:async function(e,t,i,n){return FF(e,t,i,n)}});return Object.defineProperties(QK,{onAudioAutoplayFailed:{get:()=>zP.onAudioAutoplayFailed,set:e=>{zP.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>zP.onAutoplayFailed,set:e=>{zP.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>QK._onSecurityPolicyViolation,set(e){QK._onSecurityPolicyViolation=e,bj(e)}},__CLIENT_LIST__:{get:()=>Oy("SHOW_GLOBAL_CLIENT_LIST")?cA:[]}}),YP.on(EP.CAMERA_DEVICE_CHANGED,(e=>{Jy.info("camera device changed",JSON.stringify(e)),QK.onCameraChanged&&QK.onCameraChanged(e),QK.safeEmit(ew.CAMERA_CHANGED,e)})),YP.on(EP.RECORDING_DEVICE_CHANGED,(e=>{Jy.info("microphone device changed",JSON.stringify(e)),QK.onMicrophoneChanged&&QK.onMicrophoneChanged(e),QK.safeEmit(ew.MICROPHONE_CHANGED,e)})),YP.on(EP.PLAYOUT_DEVICE_CHANGED,(e=>{Jy.debug("playout device changed",JSON.stringify(e)),QK.onPlaybackDeviceChanged&&QK.onPlaybackDeviceChanged(e),QK.safeEmit(ew.PLAYBACK_DEVICE_CHANGED,e)})),ZP.onAutoplayFailed=()=>{Jy.info("detect audio element autoplay failed"),zP.onAudioAutoplayFailed&&zP.onAudioAutoplayFailed()},wP.on("autoplay-failed",(()=>{Jy.info("detect webaudio autoplay failed"),zP.onAudioAutoplayFailed&&zP.onAudioAutoplayFailed(),QK.safeEmit(ew.AUTOPLAY_FAILED)})),wP.on(UD.STATE_CHANGE,((e,t)=>{Jy.info("audio context state changed: ".concat(t," => ").concat(e)),QK.onAudioContextStateChanged&&QK.onAudioContextStateChanged(e,t),QK.safeEmit(ew.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),Uv.on(Dv.NETWORK_STATE_CHANGE,((e,t)=>{Jy.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=QK),QK}));