vendor: 5,488 bytes, lines 1-5
1/** 2 * AgoraWebSDK_N-v4.24.2-200-0-g58279341-dirty Copyright AgoraInc. 3 */ 4 5!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,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),S=d,g=S({}.toString),T=S("".slice),R=function(e){return T(g(e),8,-1)},C=R,v=d,y=function(e){if("Function"===C(e))return v(e)},I="object"==typeof document&&document.all,A={all:I,IS_HTMLDDA:void 0===I&&void 0!==I},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,V=U&&!M.call({1:2},1);k.f=V?function(e){var t=U(this,e);return!!t&&t.enumerable}:M;var x,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},z=Y,q=TypeError,X=function(e){if(z(e))throw q("Can't call method on "+e);return e},J=K,Q=X,Z=function(e){return J(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=(x=_e.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!F&&le&&(!(x=le.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=le.match(/Chrome\/(\d+)/))&&(F=+x[1]);var Ee=F,me=Ee,fe=n,Se=h.String,ge=!!Object.getOwnPropertySymbols&&!fe((function(){var e=Symbol();return!Se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41})),Te=ge&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,Ce=w,ve=l,ye=Object,Ie=Te?function(e){return"symbol"==typeof e}:function(e){var t=Re("Symbol");return Ce(t)&&ve(t.prototype,ye(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,Ve=te,xe=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,ze=X,qe=Object,Xe=function(e){return qe(ze(e))},Je=Xe,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Je(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=ge,ct=Te,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=Ie,mt=ke,ft=function(e,t){var i,n;if("string"===t&&Ue(i=e.toString)&&!Ve(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!Ve(n=Me(i,e)))return n;if("string"!==t&&Ue(i=e.toString)&&!Ve(n=Me(i,e)))return n;throw xe("Can't convert object to primitive value")},St=TypeError,gt=ht("toPrimitive"),Tt=function(e,t){if(!_t(e)||Et(e))return e;var i,n=mt(e,gt);if(n){if(void 0===t&&(t="default"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw St("Can't convert object to primitive value")}return void 0===t&&(t="number"),ft(e,t)},Rt=Ie,Ct=function(e){var t=Tt(e,"string");return Rt(t)?t:t+""},vt=te,yt=h.document,It=vt(yt)&&vt(yt.createElement),At=function(e){return It?yt.createElement(e):{}},bt=At,wt=!N&&!n((function(){return 7!=Object.defineProperty(bt("div"),"a",{get:function(){return 7}}).a}
vendor: 4,531 bytes, line 5
5)),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=Ct,Mt=Ze,Ut=wt,Vt=Object.getOwnPropertyDescriptor;O.f=Ot?Vt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return Vt(e,t)}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t])};var xt=n,Ft=w,Bt=/#|\.prototype\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?xt(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,zt=De,qt=r,Xt=y(y.bind),Jt=function(e,t){return zt(e),void 0===t?e:qt?Xt(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,mi=N?function(e,t,i){return _i.f(e,t,Ei(1,i))}:function(e,t,i){return e[t]=i,e},fi=h,Si=f,gi=y,Ti=w,Ri=O.f,Ci=Yt,vi=ie,yi=Jt,Ii=mi,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 Si(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?fi:p?fi[u]:(fi[u]||{}).prototype,m=h?vi:vi[u]||Ii(vi,u,{})[u],f=m.prototype;for(o in t)n=!(i=Ci(h?o:u+(p?".":"#")+o,e.forced))&&E&&Ai(E,o),a=m[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?yi(s,fi):e.wrap&&n?bi(s):_&&Ti(s)?gi(s):s,(e.sham||s&&s.sham||a&&a.sham)&&Ii(d,"sham",!0),Ii(m,o,d),_&&(Ai(vi,r=u+"Prototype")||Ii(vi,r,{}),Ii(vi[r],o,s),e.real&&f&&(i||!f[o])&&Ii(f,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,Vi=function(e,t){var i=ki(e);return i<0?Mi(i+t,0):Ui(i,t)},xi=Li,Fi=Math.min,Bi=function(e){return e>0?Fi(xi(e),9007199254740991):0},ji=Bi,Gi=function(e){return ji(e.length)},Wi=Z,Hi=Vi,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}},zi={includes:Yi(!0),indexOf:Yi(!1)},qi=zi.includes;wi({target:"Array",proto:!0,forced:n((function(){return!Array(1).includes()}))},{includes:function(e){return qi(this,e,arguments.length>1?arguments[1]:void 0)}});var Xi=ie,Ji=function(e){return Xi[e+"Prototype"]},Qi=Ji("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,mn=function(e){if("Symbol"===_n(e))throw TypeError("Cannot convert a Symbol value to a string");return En(e)},fn=ht("match"),Sn=wi,gn=function(e){if(nn(e))throw rn("The method doesn't accept regular expressions");return e},Tn=X,Rn=mn,Cn=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[fn]=!1,"/./"[e](t)}catch(e){}}return!1},vn=d("".indexOf);Sn({target:"String",proto:!0,forced:!Cn("includes")},{includes:function(e){return!!~vn(Rn(Tn(this)),Rn(gn(e)),arguments.length>1?arguments[1]:void 0)}});var yn=Ji("String").includes,In=l,An=Qi,bn=yn,wn=Array.prototype,On=String.prototype,Nn=function(e){var t=e.includes;return e===wn||In(wn,e)&&t===wn.includes?An:"string"==typeof e||e===On||In(On,e)&&t===On.includes?bn:t},Dn=i(Nn),Pn=De,Ln=Xe,kn=K,Mn=Gi,Un=TypeError,Vn=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}
vendor: 9,361 bytes, line 5
5if(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}},xn={left:Vn(!1),right:Vn(!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=xn.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=Ji("Array").reduce,Hn=l,Kn=Wn,Yn=Array.prototype,zn=function(e){var t=e.reduce;return e===Yn||Hn(Yn,e)&&t===Yn.reduce?Kn:t},qn=zn,Xn=i(qn),Jn=R,Qn=Array.isArray||function(e){return"Array"==Jn(e)},Zn=wi,$n=Qn,er=d([].reverse),tr=[1,2];Zn({target:"Array",proto:!0,forced:String(tr)===String(tr.reverse())},{reverse:function(){return $n(this)&&(this.length=this.length),er(this)}});var ir=Ji("Array").reverse,nr=l,rr=ir,or=Array.prototype,sr=function(e){var t=e.reverse;return e===or||nr(or,e)&&t===or.reverse?rr:t},ar=sr,cr=i(ar),dr=nt,lr=Ye("keys"),ur=function(e){return lr[e]||(lr[e]=dr(e))},hr=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),pr=Ze,_r=w,Er=Xe,mr=hr,fr=ur("IE_PROTO"),Sr=Object,gr=Sr.prototype,Tr=mr?Sr.getPrototypeOf:function(e){var t=Er(e);if(pr(t,fr))return t[fr];var i=t.constructor;return _r(i)&&t instanceof i?i.prototype:t instanceof Sr?gr:null},Rr=d,Cr=De,vr=w,yr=String,Ir=TypeError,Ar=function(e,t,i){try{return Rr(Cr(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},br=ii,wr=function(e){if("object"==typeof e||vr(e))return e;throw Ir("Can't set "+yr(e)+" as a prototype")},Or=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Ar(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return br(i),wr(n),t?e(i,n):i.__proto__=n,i}}():void 0),Nr={},Dr={},Pr=Ze,Lr=Z,kr=zi.indexOf,Mr=Dr,Ur=d([].push),Vr=function(e,t){var i,n=Lr(e),r=0,o=[];for(i in n)!Pr(Mr,i)&&Pr(n,i)&&Ur(o,i);for(;t.length>r;)Pr(n,i=t[r++])&&(~kr(o,i)||Ur(o,i));return o},xr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Fr=Vr,Br=xr.concat("length","prototype");Nr.f=Object.getOwnPropertyNames||function(e){return Fr(e,Br)};var jr={};jr.f=Object.getOwnPropertySymbols;var Gr=ae,Wr=Nr,Hr=jr,Kr=ii,Yr=d([].concat),zr=Gr("Reflect","ownKeys")||function(e){var t=Wr.f(Kr(e)),i=Hr.f;return i?Yr(t,i(e)):t},qr=Ze,Xr=zr,Jr=O,Qr=Qt,Zr={},$r=Vr,eo=xr,to=Object.keys||function(e){return $r(e,eo)},io=N,no=Zt,ro=Qt,oo=ii,so=Z,ao=to;Zr.f=io&&!no?Object.defineProperties:function(e,t){oo(e);for(var i,n=so(t),r=ao(t),o=r.length,s=0;o>s;)ro.f(e,i=r[s++],n[i]);return e};var co,lo=ae("document","documentElement"),uo=ii,ho=Zr,po=xr,_o=Dr,Eo=lo,mo=At,fo="prototype",So="script",go=ur("IE_PROTO"),To=function(){},Ro=function(e){return"<"+So+">"+e+"</"+So+">"},Co=function(e){e.write(Ro("")),e.close();var t=e.parentWindow.Object;return e=null,t},vo=function(){try{co=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;vo="undefined"!=typeof document?document.domain&&co?Co(co):(t=mo("iframe"),i="java"+So+":",t.style.display="none",Eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Ro("document.F=Object")),e.close(),e.F):Co(co);for(var n=po.length;n--;)delete vo[fo][po[n]];return vo()};_o[go]=!0;var yo=Object.create||function(e,t){var i;return null!==e?(To[fo]=uo(e),i=new To,To[fo]=null,i[go]=e):i=vo(),void 0===t?i:ho.f(i,t)},Io=te,Ao=mi,bo=Error,wo=d("".replace),Oo=String(bo("zxcasd").stack),No=/\n\s*at [^:]*:[^\n]*/,Do=No.test(Oo),Po=B,Lo=!n((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Po(1,7)),7!==e.stack)})),ko=mi,Mo=function(e,t){if(Do&&"string"==typeof e&&!bo.prepareStackTrace)for(;t--;)e=wo(e,No,"");return e},Uo=Lo,Vo=Error.captureStackTrace,xo={},Fo=xo,Bo=ht("iterator"),jo=Array.prototype,Go=function(e){return void 0!==e&&(Fo.Array===e||jo[Bo]===e)},Wo=pn,Ho=ke,Ko=Y,Yo=xo,zo=ht("iterator"),qo=function(e){if(!Ko(e))return Ho(e,zo)||Ho(e,"@@iterator")||Yo[Wo(e)]},Xo=L,Jo=De,Qo=ii,Zo=be,$o=qo,es=TypeError,ts=function(e,t){var i=arguments.length<2?$o(e):t;if(Jo(i))return Qo(Xo(i,e));throw es(Zo(e)+" is not iterable")},is=L,ns=ii,rs=ke,os=function(e,t,i){var n,r;ns(e);try{if(!(n=rs(e,"return"))){if("throw"===t)throw i;return i}n=is(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return ns(n),i},ss=Jt,as=L,cs=ii,ds=be,ls=Go,us=Gi,hs=l,ps=ts,_s=qo,Es=os,ms=TypeError,fs=function(e,t){this.stopped=e,this.result=t},Ss=fs.prototype,gs=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=ss(t,l),m=function(e){return n&&Es(n,"normal",e),new fs(!0,e)},f=function(e){return u?(cs(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=_s(e)))throw ms(ds(e)+" is not iterable");if(ls(r)){for(o=0,s=us(e);s>o;o++)if((a=f(e[o]))&&hs(Ss,a))return a;return new fs(!1)}n=ps(e,r)}for(c=h?e.next:n.next;!(d=as(c,n)).done;){try{a=f(d.value)}catch(e){Es(n,"throw",e)}if("object"==typeof a&&a&&hs(Ss,a))return a}return new fs(!1)},Ts=mn,Rs=wi,Cs=l,vs=Tr,ys=Or,Is=function(e,t,i){for(var n=Xr(t),r=Qr.f,o=Jr.f,s=0;s<n.length;s++){var a=n[s];qr(e,a)||i&&qr(i,a)||r(e,a,o(t,a))}},As=yo,bs=mi,ws=B,Os=function(e,t){Io(t)&&"cause"in t&&Ao(e,"cause",t.cause)},Ns=function(e,t,i,n){Uo&&(Vo?Vo(e,t):ko(e,"stack",Mo(i,n)))},Ds=gs,Ps=function(e,t){return void 0===e?arguments.length<2?"":t:Ts(e)},Ls=ht("toStringTag"),ks=Error,Ms=[].push,Us=function(e,t){var i,n=Cs(Vs,this);ys?i=ys(ks(),n?vs(this):Vs):(i=n?this:As(Vs),bs(i,Ls,"Error")),void 0!==t&&bs(i,"message",Ps(t)),Ns(i,Us,i.stack,1),arguments.length>2&&Os(i,arguments[2]);var r=[];return Ds(e,Ms,{that:r}),bs(i,"errors",r),i};ys?ys(Us,ks):Is(Us,ks,{name:!0});var Vs=Us.prototype=As(ks.prototype,{constructor:ws(1,Us),message:ws(1,""),name:ws(1,"AggregateError")});Rs({global:!0,constructor:!0,arity:2},{AggregateError:Us});var xs,Fs,Bs,js=w,Gs=h.WeakMap,Ws=js(Gs)&&/native code/.test(String(Gs)),Hs=h,Ks=te,Ys=mi,zs=Ze,qs=He,Xs=ur,Js=Dr,Qs="Object already initialized",Zs=Hs.TypeError,$s=Hs.WeakMap;if(Ws||qs.state){var ea=qs.state||(qs.state=new $s);ea.get=ea.get,ea.has=ea.has,ea.set=ea.set,xs=function(e,t){if(ea.has(e))throw Zs(Qs);return t.facade=e,ea.set(e,t),t},Fs=function(e){return ea.get(e)||{}},Bs=function(e){return ea.has(e)}}else{var ta=Xs("state");Js[ta]=!0,xs=function(e,t){if(zs(e,ta))throw Zs(Qs);return t.facade=e,Ys(e,ta,t),t},Fs=function(e){return zs(e,ta)?e[ta]:{}},Bs=function(e){return zs(e,ta)}}var ia,na,ra,oa={set:xs,get:Fs,has:Bs,enforce:function(e){return Bs(e)?Fs(e):xs(e,{})},getterFor:function(e){return function(t){var i;if(!Ks(t)||(i=Fs(t)).type!==e)throw Zs("Incompatible receiver, "+e+" required");return i}}},sa=N,aa=Ze,ca=Function.prototype,da=sa&&Object.getOwnPropertyDescriptor,la=aa(ca,"name"),ua={EXISTS:la,PROPER:la&&"something"===function(){}.name,CONFIGURABLE:la&&(!sa||sa&&da(ca,"name").configurable)},ha=mi,pa=function(e,t,i,n){return n&&n.enumerable?e[t]=i:ha(e,t,i),e},_a=n,Ea=w,ma=te,fa=yo,Sa=Tr,ga=pa,Ta=ht("iterator"),Ra=!1;[].keys&&("next"in(ra=[].keys())?(na=Sa(Sa(ra)))!==Object.prototype&&(ia=na):Ra=!0);var Ca=!ma(ia)||_a((function(){var e={};return ia[Ta].call(e)!==e}));Ea((ia=Ca?{}:fa(ia))[Ta])||ga(ia,Ta,(function(){return this}));var va={IteratorPrototype:ia,BUGGY_SAFARI_ITERATORS:Ra},ya=pn,Ia=sn?{}.toString:function(){return"[object "+ya(this)+"]"},Aa=sn,ba=Qt.f,wa=mi,Oa=Ze,Na=Ia,Da=ht("toStringTag"),Pa=function(e,t,i,n){if(e){var r=i?e:e.prototype;Oa(r,Da)||ba(r,Da,{configurable:!0,value:t}),n&&!Aa&&wa(r,"toString",Na)}},La=va.IteratorPrototype,ka=yo,Ma=B,Ua=Pa,Va=xo,xa=function(){return this},Fa=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ka(La,{next:Ma(+!n,i)}),Ua(e,r,!1,!0),Va[r]=xa,e},Ba=wi,ja=L,Ga=ua,Wa=Fa,Ha=Tr,Ka=Pa,Ya=pa,za=xo,qa=va,Xa=Ga.PROPER,Ja=qa.BUGGY_SAFARI_ITERATORS,Qa=ht("iterator"),Za="keys",$a="values",ec="entries",tc=function(){return this},ic=function(e,t,i,n,r,o,s){Wa(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 Za:case $a:case ec:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[Qa]||p["@@iterator"]||r&&p[r],E=!Ja&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=Ha(m.call(new e)))!==Object.prototype&&a.next&&(Ka(a,u,!0,!0),za[u]=tc),Xa&&r==$a&&_&&_.name!==$a&&(h=!0,E=function(){return ja(_,this)}),r)if(c={values:l($a),keys:o?E:l(Za),entries:l(ec)},s)for(d in c)(Ja||h||!(d in p))&&Ya(p,d,c[d]);else Ba({target:t,proto:!0,forced:Ja||h},c);return s&&p[Qa]!==E&&Ya(p,Qa,E,{name:r}),za[t]=E,c},nc=function(e,t){return{value:e,done:t}},rc=Z,oc=xo,sc=oa;Qt.f;var ac=ic,cc=nc,dc="Array Iterator",lc=sc.set,uc=sc.getterFor(dc);ac(Array,"Array",(function(e,t){lc(this,{type:dc,target:rc(e),index:0,kind:t})}),(function(){var e=uc(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,cc(void 0,!0)):cc("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),oc.Arguments=oc.Array;var hc=Qt,pc=function(e,t,i){return hc.f(e,t,i)},_c=ae,Ec=pc,mc=N,fc=ht("species"),Sc=l,gc=TypeError,Tc=function(e,t){if(Sc(t,e))return e;throw gc("Incorrect invocation")},Rc=w,Cc=He,vc=d(Function.toString);
vendor: 5,891 bytes, line 5
5Rc(Cc.inspectSource)||(Cc.inspectSource=function(e){return vc(e)});var yc=Cc.inspectSource,Ic=d,Ac=n,bc=w,wc=pn,Oc=yc,Nc=function(){},Dc=[],Pc=ae("Reflect","construct"),Lc=/^\s*(?:class|function)\b/,kc=Ic(Lc.exec),Mc=!Lc.exec(Nc),Uc=function(e){if(!bc(e))return!1;try{return Pc(Nc,Dc,e),!0}catch(e){return!1}},Vc=function(e){if(!bc(e))return!1;switch(wc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Mc||!!kc(Lc,Oc(e))}catch(e){return!0}};Vc.sham=!0;var xc,Fc,Bc,jc,Gc=!Pc||Ac((function(){var e;return Uc(Uc.call)||!Uc(Object)||!Uc((function(){e=!0}))||e}))?Vc:Uc,Wc=Gc,Hc=be,Kc=TypeError,Yc=ii,zc=function(e){if(Wc(e))return e;throw Kc(Hc(e)+" is not a constructor")},qc=Y,Xc=ht("species"),Jc=function(e,t){var i,n=Yc(e).constructor;return void 0===n||qc(i=Yc(n)[Xc])?t:zc(i)},Qc=d([].slice),Zc=TypeError,$c=function(e,t){if(e<t)throw Zc("Not enough arguments");return e},ed=/(?:ipad|iphone|ipod).*applewebkit/i.test(ce),td=h,id=f,nd=Jt,rd=w,od=Ze,sd=n,ad=lo,cd=Qc,dd=At,ld=$c,ud=ed,hd=jn,pd=td.setImmediate,_d=td.clearImmediate,Ed=td.process,md=td.Dispatch,fd=td.Function,Sd=td.MessageChannel,gd=td.String,Td=0,Rd={},Cd="onreadystatechange";sd((function(){xc=td.location}));var vd=function(e){if(od(Rd,e)){var t=Rd[e];delete Rd[e],t()}},yd=function(e){return function(){vd(e)}},Id=function(e){vd(e.data)},Ad=function(e){td.postMessage(gd(e),xc.protocol+"//"+xc.host)};pd&&_d||(pd=function(e){ld(arguments.length,1);var t=rd(e)?e:fd(e),i=cd(arguments,1);return Rd[++Td]=function(){id(t,void 0,i)},Fc(Td),Td},_d=function(e){delete Rd[e]},hd?Fc=function(e){Ed.nextTick(yd(e))}:md&&md.now?Fc=function(e){md.now(yd(e))}:Sd&&!ud?(jc=(Bc=new Sd).port2,Bc.port1.onmessage=Id,Fc=nd(jc.postMessage,jc)):td.addEventListener&&rd(td.postMessage)&&!td.importScripts&&xc&&"file:"!==xc.protocol&&!sd(Ad)?(Fc=Ad,td.addEventListener("message",Id,!1)):Fc=Cd in dd("script")?function(e){ad.appendChild(dd("script"))[Cd]=function(){ad.removeChild(this),vd(e)}}:function(e){setTimeout(yd(e),0)});var bd={set:pd,clear:_d},wd=function(){this.head=null,this.tail=null};wd.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var Od,Nd,Dd,Pd,Ld,kd=wd,Md=/ipad|iphone|ipod/i.test(ce)&&"undefined"!=typeof Pebble,Ud=/web0s(?!.*chrome)/i.test(ce),Vd=h,xd=Jt,Fd=O.f,Bd=bd.set,jd=kd,Gd=ed,Wd=Md,Hd=Ud,Kd=jn,Yd=Vd.MutationObserver||Vd.WebKitMutationObserver,zd=Vd.document,qd=Vd.process,Xd=Vd.Promise,Jd=Fd(Vd,"queueMicrotask"),Qd=Jd&&Jd.value;if(!Qd){var Zd=new jd,$d=function(){var e,t;for(Kd&&(e=qd.domain)&&e.exit();t=Zd.get();)try{t()}catch(e){throw Zd.head&&Od(),e}e&&e.enter()};Gd||Kd||Hd||!Yd||!zd?!Wd&&Xd&&Xd.resolve?((Pd=Xd.resolve(void 0)).constructor=Xd,Ld=xd(Pd.then,Pd),Od=function(){Ld($d)}):Kd?Od=function(){qd.nextTick($d)}:(Bd=xd(Bd,Vd),Od=function(){Bd($d)}):(Nd=!0,Dd=zd.createTextNode(""),new Yd($d).observe(Dd,{characterData:!0}),Od=function(){Dd.data=Nd=!Nd}),Qd=function(e){Zd.head||Od(),Zd.add(e)}}var el=Qd,tl=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},il=h.Promise,nl="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,rl=!nl&&!jn&&"object"==typeof window&&"object"==typeof document,ol=h,sl=il,al=w,cl=Yt,dl=yc,ll=ht,ul=rl,hl=nl,pl=Ee,_l=sl&&sl.prototype,El=ll("species"),ml=!1,fl=al(ol.PromiseRejectionEvent),Sl=cl("Promise",(function(){var e=dl(sl),t=e!==String(sl);if(!t&&66===pl)return!0;if(!_l.catch||!_l.finally)return!0;if(!pl||pl<51||!/native code/.test(e)){var i=new sl((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[El]=n,!(ml=i.then((function(){}))instanceof n))return!0}return!t&&(ul||hl)&&!fl})),gl={CONSTRUCTOR:Sl,REJECTION_EVENT:fl,SUBCLASSING:ml},Tl={},Rl=De,Cl=TypeError,vl=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw Cl("Bad Promise constructor");t=e,i=n})),this.resolve=Rl(t),this.reject=Rl(i)};Tl.f=function(e){return new vl(e)};var yl,Il,Al=wi,bl=jn,wl=h,Ol=L,Nl=pa,Dl=Pa,Pl=function(e){var t=_c(e);mc&&t&&!t[fc]&&Ec(t,fc,{configurable:!0,get:function(){return this}})},Ll=De,kl=w,Ml=te,Ul=Tc,Vl=Jc,xl=bd.set,Fl=el,Bl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},jl=tl,Gl=kd,Wl=oa,Hl=il,Kl=gl,Yl=Tl,zl="Promise",ql=Kl.CONSTRUCTOR,Xl=Kl.REJECTION_EVENT,Jl=Wl.getterFor(zl),Ql=Wl.set,Zl=Hl&&Hl.prototype,$l=Hl,eu=Zl,tu=wl.TypeError,iu=wl.document,nu=wl.process,ru=Yl.f,ou=ru,su=!!(iu&&iu.createEvent&&wl.dispatchEvent),au="unhandledrejection",cu=function(e){var t;return!(!Ml(e)||!kl(t=e.then))&&t},du=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(2===t.rejection&&_u(t),t.rejection=1),!0===a?i=o:(l&&l.enter(),i=a(o),l&&(l.exit(),r=!0)),i===e.promise?d(tu("Promise-chain cycle")):(n=cu(i))?Ol(n,i,c,d):c(i)):d(o)}catch(e){l&&!r&&l.exit(),d(e)}},lu=function(e,t){e.notified||(e.notified=!0,Fl((function(){for(var i,n=e.reactions;i=n.get();)du(i,e);e.notified=!1,t&&!e.rejection&&hu(e)})))},uu=function(e,t,i){var n,r;su?((n=iu.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),wl.dispatchEvent(n)):n={promise:t,reason:i},!Xl&&(r=wl["on"+e])?r(n):e===au&&Bl("Unhandled promise rejection",i)},hu=function(e){Ol(xl,wl,(function(){var t,i=e.facade,n=e.value;if(pu(e)&&(t=jl((function(){bl?nu.emit("unhandledRejection",n,i):uu(au,i,n)})),e.rejection=bl||pu(e)?2:1,t.error))throw t.value}))},pu=function(e){return 1!==e.rejection&&!e.parent},_u=function(e){Ol(xl,wl,(function(){var t=e.facade;bl?nu.emit("rejectionHandled",t):uu("rejectionhandled",t,e.value)}))},Eu=function(e,t,i){return function(n){e(t,n,i)}},mu=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,lu(e,!0))},fu=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);
vendor: 6,065 bytes, line 5
5try{if(e.facade===t)throw tu("Promise can't be resolved itself");var n=cu(t);n?Fl((function(){var i={done:!1};try{Ol(n,t,Eu(fu,i,e),Eu(mu,i,e))}catch(t){mu(i,t,e)}})):(e.value=t,e.state=1,lu(e,!1))}catch(t){mu({done:!1},t,e)}}};ql&&(eu=($l=function(e){Ul(this,eu),Ll(e),Ol(yl,this);var t=Jl(this);try{e(Eu(fu,t),Eu(mu,t))}catch(e){mu(t,e)}}).prototype,(yl=function(e){Ql(this,{type:zl,done:!1,notified:!1,parent:!1,reactions:new Gl,rejection:!1,state:0,value:void 0})}).prototype=Nl(eu,"then",(function(e,t){var i=Jl(this),n=ru(Vl(this,$l));return i.parent=!0,n.ok=!kl(e)||e,n.fail=kl(t)&&t,n.domain=bl?nu.domain:void 0,0==i.state?i.reactions.add(n):Fl((function(){du(n,i)})),n.promise})),Il=function(){var e=new yl,t=Jl(e);this.promise=e,this.resolve=Eu(fu,t),this.reject=Eu(mu,t)},Yl.f=ru=function(e){return e===$l||undefined===e?new Il(e):ou(e)}),Al({global:!0,constructor:!0,wrap:!0,forced:ql},{Promise:$l}),Dl($l,zl,!1,!0),Pl(zl);var Su=ht("iterator"),gu=!1;try{var Tu=0,Ru={next:function(){return{done:!!Tu++}},return:function(){gu=!0}};Ru[Su]=function(){return this},Array.from(Ru,(function(){throw 2}))}catch(e){}var Cu=il,vu=function(e,t){if(!t&&!gu)return!1;var i=!1;try{var n={};n[Su]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(e){}return i},yu=gl.CONSTRUCTOR||!vu((function(e){Cu.all(e).then(void 0,(function(){}))})),Iu=L,Au=De,bu=Tl,wu=tl,Ou=gs;wi({target:"Promise",stat:!0,forced:yu},{all:function(e){var t=this,i=bu.f(t),n=i.resolve,r=i.reject,o=wu((function(){var i=Au(t.resolve),o=[],s=0,a=1;Ou(e,(function(e){var c=s++,d=!1;a++,Iu(i,t,e).then((function(e){d||(d=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Nu=wi,Du=gl.CONSTRUCTOR;il&&il.prototype,Nu({target:"Promise",proto:!0,forced:Du,real:!0},{catch:function(e){return this.then(void 0,e)}});var Pu=L,Lu=De,ku=Tl,Mu=tl,Uu=gs;wi({target:"Promise",stat:!0,forced:yu},{race:function(e){var t=this,i=ku.f(t),n=i.reject,r=Mu((function(){var r=Lu(t.resolve);Uu(e,(function(e){Pu(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Vu=L,xu=Tl;wi({target:"Promise",stat:!0,forced:gl.CONSTRUCTOR},{reject:function(e){var t=xu.f(this);return Vu(t.reject,void 0,e),t.promise}});var Fu=ii,Bu=te,ju=Tl,Gu=function(e,t){if(Fu(e),Bu(t)&&t.constructor===e)return t;var i=ju.f(e);return(0,i.resolve)(t),i.promise},Wu=wi,Hu=il,Ku=gl.CONSTRUCTOR,Yu=Gu,zu=ae("Promise"),qu=!Ku;Wu({target:"Promise",stat:!0,forced:true},{resolve:function(e){return Yu(qu&&this===zu?Hu:this,e)}});var Xu=L,Ju=De,Qu=Tl,Zu=tl,$u=gs;wi({target:"Promise",stat:!0,forced:yu},{allSettled:function(e){var t=this,i=Qu.f(t),n=i.resolve,r=i.reject,o=Zu((function(){var i=Ju(t.resolve),r=[],o=0,s=1;$u(e,(function(e){var a=o++,c=!1;s++,Xu(i,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||n(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||n(r))}))})),--s||n(r)}));return o.error&&r(o.value),i.promise}});var eh=L,th=De,ih=ae,nh=Tl,rh=tl,oh=gs,sh="No one promise resolved";wi({target:"Promise",stat:!0,forced:yu},{any:function(e){var t=this,i=ih("AggregateError"),n=nh.f(t),r=n.resolve,o=n.reject,s=rh((function(){var n=th(t.resolve),s=[],a=0,c=1,d=!1;oh(e,(function(e){var l=a++,u=!1;c++,eh(n,t,e).then((function(e){u||d||(d=!0,r(e))}),(function(e){u||d||(u=!0,s[l]=e,--c||o(new i(s,sh)))}))})),--c||o(new i(s,sh))}));return s.error&&o(s.value),n.promise}});var ah=wi,ch=il,dh=n,lh=ae,uh=w,hh=Jc,ph=Gu,_h=ch&&ch.prototype;ah({target:"Promise",proto:!0,real:!0,forced:!!ch&&dh((function(){_h.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=hh(this,lh("Promise")),i=uh(e);return this.then(i?function(i){return ph(t,e()).then((function(){return i}))}:e,i?function(i){return ph(t,e()).then((function(){throw i}))}:e)}});var Eh=d,mh=Li,fh=mn,Sh=X,gh=Eh("".charAt),Th=Eh("".charCodeAt),Rh=Eh("".slice),Ch=function(e){return function(t,i){var n,r,o=fh(Sh(t)),s=mh(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=Th(o,s))<55296||n>56319||s+1===a||(r=Th(o,s+1))<56320||r>57343?e?gh(o,s):n:e?Rh(o,s,s+2):r-56320+(n-55296<<10)+65536}},vh={codeAt:Ch(!1),charAt:Ch(!0)},yh=vh.charAt,Ih=mn,Ah=oa,bh=ic,wh=nc,Oh="String Iterator",Nh=Ah.set,Dh=Ah.getterFor(Oh);bh(String,"String",(function(e){Nh(this,{type:Oh,string:Ih(e),index:0})}),(function(){var e,t=Dh(this),i=t.string,n=t.index;return n>=i.length?wh(void 0,!0):(e=yh(i,n),t.index+=e.length,wh(e,!1))}));var Ph=ie.Promise,Lh={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},kh=h,Mh=pn,Uh=mi,Vh=xo,xh=ht("toStringTag");for(var Fh in Lh){var Bh=kh[Fh],jh=Bh&&Bh.prototype;jh&&Mh(jh)!==xh&&Uh(jh,xh,Fh),Vh[Fh]=Vh.Array}var Gh=Ph,Wh=i(Gh),Hh=Ji("Array").values,Kh=pn,Yh=Ze,zh=l,qh=Hh,Xh=Array.prototype,Jh={DOMTokenList:!0,NodeList:!0},Qh=function(e){var t=e.values;return e===Xh||zh(Xh,e)&&t===Xh.values||Yh(Jh,Kh(e))?qh:t},Zh=i(Qh),$h=be,ep=TypeError,tp=Ct,ip=Qt,np=B,rp=function(e,t,i){var n=tp(t);n in e?ip.f(e,n,np(0,i)):e[n]=i},op=Vi,sp=Gi,ap=rp,cp=Array,dp=Math.max,lp=function(e,t,i){for(var n=sp(e),r=op(t,n),o=op(void 0===i?n:i,n),s=cp(dp(o-r,0)),a=0;r<o;r++,a++)ap(s,a,e[r]);return s.length=a,s},up=lp,hp=Math.floor,pp=function(e,t){var i=e.length,n=hp(i/2);return i<8?_p(e,t):Ep(e,pp(up(e,0,n),t),pp(up(e,n),t),t)},_p=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},Ep=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},mp=pp,fp=ce.match(/firefox\/(\d+)/i),Sp=!!fp&&+fp[1],gp=/MSIE|Trident/.test(ce),Tp=ce.match(/AppleWeb
5Kit\/(\d+)\./),Rp=!!Tp&&+Tp[1],Cp=wi,vp=d,yp=De,Ip=Xe,Ap=Gi,bp=function(e,t){if(!delete e[t])throw ep("Cannot delete property "+$h(t)+" of "+$h(e))},wp=mn,Op=n,Np=mp,Dp=Bn,Pp=Sp,Lp=gp,kp=Ee,Mp=Rp,Up=[],Vp=vp(Up.sort),xp=vp(Up.push),Fp=Op((function(){Up.sort(void 0)})),Bp=Op((function(){Up.sort(null)})),jp=Dp("sort"),Gp=!Op((function(){if(kp)return kp<70;if(!(Pp&&Pp>3)){if(Lp)return!0;if(Mp)return Mp<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++)Up.push({k:t+n,v:i})}for(Up.sort((function(e,t){return t.v-e.v})),n=0;n<Up.length;n++)t=Up[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));Cp({target:"Array",proto:!0,forced:Fp||!Bp||!jp||!Gp},{sort:function(e){void 0!==e&&yp(e);var t=Ip(this);if(Gp)return void 0===e?Vp(t):Vp(t,e);var i,n,r=[],o=Ap(t);for(n=0;n<o;n++)n in t&&xp(r,t[n]);for(Np(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:wp(t)>wp(i)?1:-1}}(e)),i=Ap(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)bp(t,n++);return t}});var Wp=Ji("Array").sort,Hp=l,Kp=Wp,Yp=Array.prototype,zp=function(e){var t=e.sort;return e===Yp||Hp(Yp,e)&&t===Yp.sort?Kp:t},qp=i(zp),Xp=n,Jp=ht("iterator"),Qp=!Xp((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2"),n="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),n+=i+e})),i.delete("a",2),!e.toJSON||!i.has("a",1)||i.has("a",2)||!t.size&&true||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Jp]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://ÑеÑÑ").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host})),Zp=pa,$p=wi,e_=h,t_=L,i_=d,n_=N,r_=Qp,o_=pa,s_=pc,a_=function(e,t,i){for(var n in t)i&&i.unsafe&&e[n]?e[n]=t[n]:Zp(e,n,t[n],i);return e},c_=Pa,d_=Fa,l_=oa,u_=Tc,h_=w,p_=Ze,__=Jt,E_=pn,m_=ii,f_=te,S_=mn,g_=yo,T_=B,R_=ts,C_=qo,v_=$c,y_=mp,I_=ht("iterator"),A_="URLSearchParams",b_=A_+"Iterator",w_=l_.set,O_=l_.getterFor(A_),N_=l_.getterFor(b_),D_=Object.getOwnPropertyDescriptor,P_=function(e){if(!n_)return e_[e];var t=D_(e_,e);return t&&t.value},L_=P_("fetch"),k_=P_("Request"),M_=P_("Headers"),U_=k_&&k_.prototype,V_=M_&&M_.prototype,x_=e_.RegExp,F_=e_.TypeError,B_=e_.decodeURIComponent,j_=e_.encodeURIComponent,G_=i_("".charAt),W_=i_([].join),H_=i_([].push),K_=i_("".replace),Y_=i_([].shift),z_=i_([].splice),q_=i_("".split),X_=i_("".slice),J_=/\+/g,Q_=Array(4),Z_=function(e){return Q_[e-1]||(Q_[e-1]=x_("((?:%[\\da-f]{2}){"+e+"})","gi"))},$_=function(e){try{return B_(e)}catch(t){return e}},eE=function(e){var t=K_(e,J_," "),i=4;try{return B_(t)}catch(e){for(;i;)t=K_(t,Z_(i--),$_);return t}},tE=/[!'()~]|%20/g,iE={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},nE=function(e){return iE[e]},rE=function(e){return K_(j_(e),tE,nE)},oE=d_((function(e,t){w_(this,{type:b_,iterator:R_(O_(e).entries),kind:t})}),"Iterator",(function(){var e=N_(this),t=e.kind,i=e.iterator.next(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.value]),i}),!0),sE=function(e){this.entries=[],this.url=null,void 0!==e&&(f_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===G_(e,0)?X_(e,1):e:S_(e)))};sE.prototype={type:A_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,n,r,o,s,a,c=C_(e);if(c)for(i=(t=R_(e,c)).next;!(n=t_(i,t)).done;){if(o=(r=R_(m_(n.value))).next,(s=t_(o,r)).done||(a=t_(o,r)).done||!t_(o,r).done)throw F_("Expected sequence with length 2");H_(this.entries,{key:S_(s.value),value:S_(a.value)})}else for(var d in e)p_(e,d)&&H_(this.entries,{key:d,value:S_(e[d])})},parseQuery:function(e){if(e)for(var t,i,n=q_(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=q_(t,"="),H_(this.entries,{key:eE(Y_(i)),value:eE(W_(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;
vendor: 4,544 bytes, line 5
5)e=t[n++],H_(i,rE(e.key)+"="+rE(e.value));return W_(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var aE=function(){u_(this,cE);var e=w_(this,new sE(arguments.length>0?arguments[0]:void 0));n_||(this.size=e.entries.length)},cE=aE.prototype;if(a_(cE,{append:function(e,t){var i=O_(this);v_(arguments.length,2),H_(i.entries,{key:S_(e),value:S_(t)}),n_||this.length++,i.updateURL()},delete:function(e){for(var t=O_(this),i=v_(arguments.length,1),n=t.entries,r=S_(e),o=i<2?void 0:arguments[1],s=void 0===o?o:S_(o),a=0;a<n.length;){var c=n[a];if(c.key!==r||void 0!==s&&c.value!==s)a++;else if(z_(n,a,1),void 0!==s)break}n_||(this.size=n.length),t.updateURL()},get:function(e){var t=O_(this).entries;v_(arguments.length,1);for(var i=S_(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){var t=O_(this).entries;v_(arguments.length,1);for(var i=S_(e),n=[],r=0;r<t.length;r++)t[r].key===i&&H_(n,t[r].value);return n},has:function(e){for(var t=O_(this).entries,i=v_(arguments.length,1),n=S_(e),r=i<2?void 0:arguments[1],o=void 0===r?r:S_(r),s=0;s<t.length;){var a=t[s++];if(a.key===n&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=O_(this);v_(arguments.length,1);for(var n,r=i.entries,o=!1,s=S_(e),a=S_(t),c=0;c<r.length;c++)(n=r[c]).key===s&&(o?z_(r,c--,1):(o=!0,n.value=a));o||H_(r,{key:s,value:a}),n_||(this.size=r.length),i.updateURL()},sort:function(){var e=O_(this);y_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=O_(this).entries,n=__(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new oE(this,"keys")},values:function(){return new oE(this,"values")},entries:function(){return new oE(this,"entries")}},{enumerable:!0}),o_(cE,I_,cE.entries,{name:"entries"}),o_(cE,"toString",(function(){return O_(this).serialize()}),{enumerable:!0}),n_&&s_(cE,"size",{get:function(){return O_(this).entries.length},configurable:!0,enumerable:!0}),c_(aE,A_),$p({global:!0,constructor:!0,forced:!r_},{URLSearchParams:aE}),!r_&&h_(M_)){var dE=i_(V_.has),lE=i_(V_.set),uE=function(e){if(f_(e)){var t,i=e.body;if(E_(i)===A_)return t=e.headers?new M_(e.headers):new M_,dE(t,"content-type")||lE(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),g_(e,{body:T_(0,S_(i)),headers:T_(0,t)})}return e};if(h_(L_)&&$p({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return L_(e,arguments.length>1?uE(arguments[1]):{})}}),h_(k_)){var hE=function(e){return u_(this,U_),new k_(e,arguments.length>1?uE(arguments[1]):{})};U_.constructor=hE,hE.prototype=U_,$p({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:hE})}}var pE,_E={URLSearchParams:aE,getState:O_},EE=ie.URLSearchParams,mE=N,fE=d,SE=L,gE=n,TE=to,RE=jr,CE=k,vE=Xe,yE=K,IE=Object.assign,AE=Object.defineProperty,bE=fE([].concat),wE=!IE||gE((function(){if(mE&&1!==IE({b:1},IE(AE({},"a",{enumerable:!0,get:function(){AE(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!=IE({},e)[i]||TE(IE({},t)).join("")!=n}))?function(e,t){for(var i=vE(e),n=arguments.length,r=1,o=RE.f,s=CE.f;n>r;)for(var a,c=yE(arguments[r++]),d=o?bE(TE(c),o(c)):TE(c),l=d.length,u=0;l>u;)a=d[u++],mE&&!SE(s,c,a)||(i[a]=c[a]);return i}:IE,OE=ii,NE=os,DE=Jt,PE=L,LE=Xe,kE=function(e,t,i,n){try{return n?t(OE(i)[0],i[1]):t(i)}catch(t){NE(e,"throw",t)}},ME=Go,UE=Gc,VE=Gi,xE=rp,FE=ts,BE=qo,jE=Array,GE=d,WE=2147483647,HE=/[^\0-\u007E]/,KE=/[.\u3002\uFF0E\uFF61]/g,YE="Overflow: input needs wider integers to process",zE=RangeError,qE=GE(KE.exec),XE=Math.floor,JE=String.fromCharCode,QE=GE("".charCodeAt),ZE=GE([].join),$E=GE([].push),em=GE("".replace),tm=GE("".split),im=GE("".toLowerCase),nm=function(e){return e+22+75*(e<26)},rm=function(e,t,i){var n=0;for(e=i?XE(e/700):e>>1,e+=XE(e/t);e>455;)e=XE(e/35),n+=36;return XE(n+36*e/(e+38))},om=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=QE(e,i++);if(r>=55296&&r<=56319&&i<n){var o=QE(e,i++);56320==(64512&o)?$E(t,((1023&r)<<10)+(1023&o)+65536):($E(t,r),i--)}else $E(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&$E(t,JE(n));var c=t.length,d=c;for(c&&$E(t,"-");d<r;){var l=WE;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<l&&(l=n);var u=d+1;if(l-o>XE((WE-s)/u))throw zE(YE);for(s+=(l-o)*u,o=l,i=0;i<e.length;
vendor: 5,666 bytes, line 5
5i++){if((n=e[i])<o&&++s>WE)throw zE(YE);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-_,m=36-_;$E(t,JE(nm(_+E%m))),h=XE(E/m),p+=36}$E(t,JE(nm(h))),a=rm(s,u,d==c),s=0,d++}}s++,o++}return ZE(t,"")},sm=wi,am=N,cm=Qp,dm=h,lm=Jt,um=d,hm=pa,pm=pc,_m=Tc,Em=Ze,mm=wE,fm=function(e){var t=LE(e),i=UE(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=DE(r,n>2?arguments[2]:void 0));var s,a,c,d,l,u,h=BE(t),p=0;if(!h||this===jE&&ME(h))for(s=VE(t),a=i?new this(s):jE(s);s>p;p++)u=o?r(t[p],p):t[p],xE(a,p,u);else for(l=(d=FE(t,h)).next,a=i?new this:[];!(c=PE(l,d)).done;p++)u=o?kE(d,r,[c.value,p],!0):c.value,xE(a,p,u);return a.length=p,a},Sm=lp,gm=vh.codeAt,Tm=function(e){var t,i,n=[],r=tm(em(im(e),KE,"."),".");for(t=0;t<r.length;t++)i=r[t],$E(n,qE(HE,i)?"xn--"+om(i):i);return ZE(n,".")},Rm=mn,Cm=Pa,vm=$c,ym=_E,Im=oa,Am=Im.set,bm=Im.getterFor("URL"),wm=ym.URLSearchParams,Om=ym.getState,Nm=dm.URL,Dm=dm.TypeError,Pm=dm.parseInt,Lm=Math.floor,km=Math.pow,Mm=um("".charAt),Um=um(/./.exec),Vm=um([].join),xm=um(1..toString),Fm=um([].pop),Bm=um([].push),jm=um("".replace),Gm=um([].shift),Wm=um("".split),Hm=um("".slice),Km=um("".toLowerCase),Ym=um([].unshift),zm="Invalid scheme",qm="Invalid host",Xm="Invalid port",Jm=/[a-z]/i,Qm=/[\d+-.a-z]/i,Zm=/\d/,$m=/^0x/i,ef=/^[0-7]+$/,tf=/^\d+$/,nf=/^[\da-f]+$/i,rf=/[\0\t\n\r #%/:<>?@[\\\]^|]/,of=/[\0\t\n\r #/:<>?@[\\\]^|]/,sf=/^[\u0000-\u0020]+/,af=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,cf=/[\t\n\r]/g,df=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)Ym(t,e%256),e=Lm(e/256);return Vm(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+=xm(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},lf={},uf=mm({},lf,{" ":1,'"':1,"<":1,">":1,"`":1}),hf=mm({},uf,{"#":1,"?":1,"{":1,"}":1}),pf=mm({},hf,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),_f=function(e,t){var i=gm(e,0);return i>32&&i<127&&!Em(t,e)?e:encodeURIComponent(e)},Ef={ftp:21,file:null,http:80,https:443,ws:80,wss:443},mf=function(e,t){var i;return 2==e.length&&Um(Jm,Mm(e,0))&&(":"==(i=Mm(e,1))||!t&&"|"==i)},ff=function(e){var t;return e.length>1&&mf(Hm(e,0,2))&&(2==e.length||"/"===(t=Mm(e,2))||"\\"===t||"?"===t||"#"===t)},Sf=function(e){return"."===e||"%2e"===Km(e)},gf={},Tf={},Rf={},Cf={},vf={},yf={},If={},Af={},bf={},wf={},Of={},Nf={},Df={},Pf={},Lf={},kf={},Mf={},Uf={},Vf={},xf={},Ff={},Bf=function(e,t,i){var n,r,o,s=Rm(e);if(t){if(r=this.parse(s))throw Dm(r);this.searchParams=null}else{if(void 0!==i&&(n=new Bf(i,!0)),r=this.parse(s,null,n))throw Dm(r);(o=Om(new wm)).bindURL(this),this.searchParams=o}};Bf.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,d=t||gf,l=0,u="",h=!1,p=!1,_=!1;for(e=Rm(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=jm(e,sf,""),e=jm(e,af,"$1")),e=jm(e,cf,""),n=fm(e);l<=n.length;){switch(r=n[l],d){case gf:if(!r||!Um(Jm,r)){if(t)return zm;d=Rf;continue}u+=Km(r),d=Tf;break;case Tf:if(r&&(Um(Qm,r)||"+"==r||"-"==r||"."==r))u+=Km(r);else{if(":"!=r){if(t)return zm;u="",d=Rf,l=0;continue}if(t&&(c.isSpecial()!=Em(Ef,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&Ef[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=Pf:c.isSpecial()&&i&&i.scheme==c.scheme?d=Cf:c.isSpecial()?d=Af:"/"==n[l+1]?(d=vf,l++):(c.cannotBeABaseURL=!0,Bm(c.path,""),d=Vf)}break;case Rf:if(!i||i.cannotBeABaseURL&&"#"!=r)return zm;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=Sm(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=Ff;break}d="file"==i.scheme?Pf:yf;continue;case Cf:if("/"!=r||"/"!=n[l+1]){d=yf;continue}d=bf,l++;break;case vf:if("/"==r){d=wf;break}d=Uf;continue;case yf:if(c.scheme=i.scheme,r==pE)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Sm(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=If;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Sm(i.path),c.query="",d=xf;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Sm(i.path),c.path.length--,d=Uf;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Sm(i.path),c.query=i.query,c.fragment="",d=Ff}break;case If:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=Uf;continue}d=wf}else d=bf;break;case Af:if(d=bf,"/"!=r||"/"!=Mm(u,l+1))continue;l++;break;case bf:if("/"!=r&&"\\"!=r){d=wf;continue}break;case wf:if("@"==r){h&&(u="%40"+u),h=!0,o=fm(u);for(var E=0;E<o.length;E++){var m=o[E];if(":"!=m||_){var f=_f(m,pf);_?c.password+=f:c.username+=f}else _=!0}u=""}else if(r==pE||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return"Invalid authority";l-=fm(u).length+1,u="",d=Of}else u+=r;break;case Of:case Nf:if(t&&"file"==c.scheme){d=kf;continue}if(":"!=r||p){if(r==pE||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return qm;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",d=Mf,t)return;continue}"["==r?p=!0:"]"==r&&(p=!1),u+=r}else{if(""==u)return qm;if(s=c.parseHost(u))return s;if(u="",d=Df,t==Nf)return}break;case Df:if(!Um(Zm,r)){if(r==pE||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var S=Pm(u,10);if(S>65535)return Xm;
vendor: 5,093 bytes, line 5
5c.port=c.isSpecial()&&S===Ef[c.scheme]?null:S,u=""}if(t)return;d=Mf;continue}return Xm}u+=r;break;case Pf:if(c.scheme="file","/"==r||"\\"==r)d=Lf;else{if(!i||"file"!=i.scheme){d=Uf;continue}if(r==pE)c.host=i.host,c.path=Sm(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=Sm(i.path),c.query="",d=xf;else{if("#"!=r){ff(Vm(Sm(n,l),""))||(c.host=i.host,c.path=Sm(i.path),c.shortenPath()),d=Uf;continue}c.host=i.host,c.path=Sm(i.path),c.query=i.query,c.fragment="",d=Ff}}break;case Lf:if("/"==r||"\\"==r){d=kf;break}i&&"file"==i.scheme&&!ff(Vm(Sm(n,l),""))&&(mf(i.path[0],!0)?Bm(c.path,i.path[0]):c.host=i.host),d=Uf;continue;case kf:if(r==pE||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&mf(u))d=Uf;else if(""==u){if(c.host="",t)return;d=Mf}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",d=Mf}continue}u+=r;break;case Mf:if(c.isSpecial()){if(d=Uf,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=pE&&(d=Uf,"/"!=r))continue}else c.fragment="",d=Ff;else c.query="",d=xf;break;case Uf:if(r==pE||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=Km(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||Bm(c.path,"")):Sf(u)?"/"==r||"\\"==r&&c.isSpecial()||Bm(c.path,""):("file"==c.scheme&&!c.path.length&&mf(u)&&(c.host&&(c.host=""),u=Mm(u,0)+":"),Bm(c.path,u)),u="","file"==c.scheme&&(r==pE||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)Gm(c.path);"?"==r?(c.query="",d=xf):"#"==r&&(c.fragment="",d=Ff)}else u+=_f(r,hf);break;case Vf:"?"==r?(c.query="",d=xf):"#"==r?(c.fragment="",d=Ff):r!=pE&&(c.path[0]+=_f(r,lf));break;case xf:t||"#"!=r?r!=pE&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":_f(r,lf)):(c.fragment="",d=Ff);break;case Ff:r!=pE&&(c.fragment+=_f(r,uf))}l++}},parseHost:function(e){var t,i,n;if("["==Mm(e,0)){if("]"!=Mm(e,e.length-1))return qm;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 Mm(e,u)};if(":"==h()){if(":"!=Mm(e,1))return;u+=2,l=++d}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&Um(nf,h());)t=16*t+Pm(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(!Um(Zm,h()))return;for(;Um(Zm,h());){if(o=Pm(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}(Hm(e,1,-1)),!t)return qm;this.host=t}else if(this.isSpecial()){if(e=Tm(e),Um(rf,e))return qm;if(t=function(e){var t,i,n,r,o,s,a,c=Wm(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(o=10,r.length>1&&"0"==Mm(r,0)&&(o=Um($m,r)?16:8,r=Hm(r,8==o?1:2)),""===r)s=0;else{if(!Um(10==o?tf:8==o?ef:nf,r))return e;s=Pm(r,o)}Bm(i,s)}for(n=0;n<t;n++)if(s=i[n],n==t-1){if(s>=km(256,5-t))return null}else if(s>255)return null;for(a=Fm(i),n=0;n<i.length;n++)a+=i[n]*km(256,3-n);return a}(e),null===t)return qm;this.host=t}else{if(Um(of,e))return qm;for(t="",i=fm(e),n=0;n<i.length;n++)t+=_f(i[n],lf);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return Em(Ef,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&mf(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,d=t+":";return null!==r?(d+="//",e.includesCredentials()&&(d+=i+(n?":"+n:"")+"@"),d+=df(r),null!==o&&(d+=":"+o)):"file"==t&&(d+="//"),d+=e.cannotBeABaseURL?s[0]:s.length?"/"+Vm(s,"/"):"",null!==a&&(d+="?"+a),null!==c&&(d+="#"+c),d},setHref:function(e){var t=this.parse(e);if(t)throw Dm(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new jf(e.path[0]).origin}catch(e){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+df(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(Rm(e)+":",gf)},getUsername:function(){return this.username},setUsername:function(e){var t=fm(Rm(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=_f(t[i],pf)}},getPassword:function(){return this.password},setPassword:function(e){var t=fm(Rm(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=_f(t[i],pf)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?df(e):df(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Of)},getHostname:function(){var e=this.host;return null===e?"":df(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,Nf)},getPort:function(){var e=this.port;return null===e?"":Rm(e)}
vendor: 4,386 bytes, line 5
5,setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=Rm(e))?this.port=null:this.parse(e,Df))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Vm(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Mf))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=Rm(e))?this.query=null:("?"==Mm(e,0)&&(e=Hm(e,1)),this.query="",this.parse(e,xf)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=Rm(e))?("#"==Mm(e,0)&&(e=Hm(e,1)),this.fragment="",this.parse(e,Ff)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var jf=function(e){var t=_m(this,Gf),i=vm(arguments.length,1)>1?arguments[1]:void 0,n=Am(t,new Bf(e,!1,i));am||(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())},Gf=jf.prototype,Wf=function(e,t){return{get:function(){return bm(this)[e]()},set:t&&function(e){return bm(this)[t](e)},configurable:!0,enumerable:!0}};if(am&&(pm(Gf,"href",Wf("serialize","setHref")),pm(Gf,"origin",Wf("getOrigin")),pm(Gf,"protocol",Wf("getProtocol","setProtocol")),pm(Gf,"username",Wf("getUsername","setUsername")),pm(Gf,"password",Wf("getPassword","setPassword")),pm(Gf,"host",Wf("getHost","setHost")),pm(Gf,"hostname",Wf("getHostname","setHostname")),pm(Gf,"port",Wf("getPort","setPort")),pm(Gf,"pathname",Wf("getPathname","setPathname")),pm(Gf,"search",Wf("getSearch","setSearch")),pm(Gf,"searchParams",Wf("getSearchParams")),pm(Gf,"hash",Wf("getHash","setHash"))),hm(Gf,"toJSON",(function(){return bm(this).serialize()}),{enumerable:!0}),hm(Gf,"toString",(function(){return bm(this).serialize()}),{enumerable:!0}),Nm){var Hf=Nm.createObjectURL,Kf=Nm.revokeObjectURL;Hf&&hm(jf,"createObjectURL",lm(Hf,Nm)),Kf&&hm(jf,"revokeObjectURL",lm(Kf,Nm))}Cm(jf,"URL"),sm({global:!0,constructor:!0,forced:!cm,sham:!am},{URL:jf});var Yf=wi,zf=n,qf=$c,Xf=mn,Jf=Qp,Qf=ae("URL");Yf({target:"URL",stat:!0,forced:!(Jf&&zf((function(){Qf.canParse()})))},{canParse:function(e){var t=qf(arguments.length,1),i=Xf(e),n=t<2||void 0===arguments[1]?void 0:Xf(arguments[1]);try{return!!new Qf(i,n)}catch(e){return!1}}});var Zf=i(ie.URL);let $f=!0,eS=!0;function tS(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function iS(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 nS(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):($f=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rS(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(eS=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function oS(){if("object"==typeof window){if($f)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function sS(e,t){eS&&console.warn(e+" is deprecated, please use "+t+" instead.")}function aS(e){return"[object Object]"===Object.prototype.toString.call(e)}function cS(e){var t;return aS(e)?Xn(t=Object.keys(e)).call(t,(function(t,i){const n=aS(e[i]),r
vendor: 1,913 bytes, line 5
5=n?cS(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function dS(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?dS(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{dS(e,e.get(t),i)}))})))}function lS(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&&dS(e,i,r)}))})),r}const uS=oS;function hS(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});
vendor: 4,238 bytes, line 5
5const 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=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.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),uS("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return uS("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=>Wh.reject(o(e))))))}}}function pS(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function _S(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 iS(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function ES(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().forEac
vendor: 4,134 bytes, line 5
5h((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 mS(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 Wh(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function fS(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=>lS(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}),iS(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>lS(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?Wh.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Wh.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function SS(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||{}
vendor: 13,234 bytes, line 5
5,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 gS(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return SS(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),Wh.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 TS(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 RS(e,t){iS(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var CS=Object.freeze({__proto__:null,fixNegotiationNeeded:RS,shimAddTrackRemoveTrack:gS,shimAddTrackRemoveTrackWithNative:SS,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:ES,shimGetStats:mS,shimGetUserMedia:hS,shimMediaStream:pS,shimOnTrack:_S,shimPeerConnection:TS,shimSenderReceiverGetStats:fS});function vS(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){sS("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 yS(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 IS(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 AS(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):Wh.resolve(new Map)}}function bS(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}),iS(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function wS(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){sS("removeStream","removeTrack"),this.getSenders().forEach((t=>{var i;t.track&&Dn(i=e.getTracks()).call(i,t.track)&&this.removeTrack(t)}))})}function OS(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function NS(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 DS(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 PS(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?Wh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function LS(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?Wh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var kS=Object.freeze({__proto__:null,shimAddTransceiver:NS,shimCreateAnswer:LS,shimCreateOffer:PS,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,Wh.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:DS,shimGetUserMedia:vS,shimOnTrack:yS,shimPeerConnection:IS,shimRTCDataChannel:OS,shimReceiverGetStats:bS,shimRemoveStream:wS,shimSenderGetStats:AS});function MS(e){if("object"==typeof e&&e.RTCPeerConnection){if("getL
5ocalStreams"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<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{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 US(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 VS(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),Wh.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),Wh.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n},t.addIceCandidate=a}function xS(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(FS(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function FS(e){return e&&void 0!==e.video?Object.assign({},e,{video:cS(e.video)}):e}function BS(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(sS("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function jS(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 GS(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 WS(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var HS=Object.freeze({__proto__:null,shimAudioContext:WS,shimCallbacksAPI:VS,shimConstraints:FS,shimCreateOfferLegacy:GS,shimGetUserMedia:xS,shimLocalStreamsAPI:MS,shimRTCIceServerUrls:BS,shimRemoteStreamsAPI:US,shimTrackEventTransceiver:jS}),KS="\t\n\v\f\r  áââââââ
ââââââ¯âã\u2028\u2029\ufeff",YS=X,zS=mn,qS=KS,XS=d("".replace),JS=RegExp("^["+qS+"]+"),QS=RegExp("(^|[^"+qS+"])["+qS+"]+$"),ZS=function(e){return function(t){var i=zS(YS(t));return 1&e&&(i=XS(i,JS,"")),2&e&&(i=XS(i,QS,"$1")),i}},$S={start:ZS(1),end:ZS(2),trim:ZS(3)},eg=ua.PROPER,tg=n,ig=KS,ng=$S.trim;wi({target:"String",proto:!0,forced:function(e){return tg((function(){return!!ig[e]()||"âÂ
á "!=="âÂ
á "[e]()||eg&&ig[e].name!==e}))}("trim")},{trim:function(){return ng(this)}});var rg=Ji("String").trim,og=l,sg=rg,ag=String.prototype,cg=function(e){var t=e.trim;return"string"==typeof e||e===ag||og(ag,e)&&t===ag.trim?sg:t},dg=i(cg),lg={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;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.pu
vendor: 4,948 bytes, line 5
5sh(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?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<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{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<n.length;r++){const o=n[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const n=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{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="";
vendor: 4,912 bytes, line 5
5n+="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<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(lg);var ug=lg.exports,hg=i(ug),pg=e({__proto__:null,default:hg},[ug]);function _g(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),n=hg.parseCandidate(e.candidate),r=Object.assign(i,n);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.
vendor: 4,119 bytes, line 5
5sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,iS(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Eg(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||iS(e,"icecandidate",(e=>{if(e.candidate){const t=hg.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function mg(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=hg.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=hg.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=hg.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 fg(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},iS(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Sg(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 gg(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.s
vendor: 4,243 bytes, line 5
5dp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==dg(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 Tg(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?Wh.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Wh.resolve())})}function Rg(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 Cg=Object.freeze({__proto__:null,removeExtmapAllowMixed:gg,shimAddIceCandidateNullOrEmpty:Tg,shimConnectionState:Sg,shimMaxMessageSize:mg,shimParameterlessSetLocalDescription:Rg,shimRTCIceCandidate:_g,shimRTCIceCandidateRelayProtocol:Eg,shimSendThrowTypeError:fg});!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=oS,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=tS(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=tS(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=tS(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:Cg,extractVersion:tS,disableLog:nS,disableWarnings:rS,sdp:pg};switch(n.browser){case"chrome":if(!CS||!TS||!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=CS,Tg(e,n),Rg(e),hS(e,n),pS(e),TS(e,n),_S(e),gS(e,n),ES(e),mS(e),fS(e),RS(e,n),_g(e),Eg(e),Sg(e),mg(e,n),fg(e),gg(e,n);break;case"firefox":if(!kS||!IS||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=kS,Tg(e,n),Rg(e),vS(e,n),IS(e,n),yS(e),wS(e),AS(e),bS(e),OS(e),NS(e),DS(e),PS(e),LS(e),_g(e),Sg(e),mg(e,n),fg(e);break;case"safari":if(!HS||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=HS,Tg(e,n),Rg(e),BS(e),GS(e),VS(e),MS(e),US(e),jS(e),xS(e),WS(e),_g(e),Eg(e),mg(e,n),fg(e),gg(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var vg=ii,yg=L,Ig=Ze,Ag=l,bg=function(){var e=vg(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},wg=RegExp.prototype,Og=function(e){var t=e.flags;return void 0!==t||"flags"in wg||Ig(e,"flags")||!Ag(wg,e)?t:yg(bg,e)},Ng=d,Dg=Xe,Pg=Math.floor,Lg=Ng("".charAt),kg=Ng("".replace),Mg=Ng("".slice),Ug=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vg=/\$([$&'`]|\d{1,2})/g,xg=wi,Fg=L,Bg=d,jg=X,Gg=w,Wg=Y,Hg=tn,Kg=mn,Yg=ke,zg=Og,qg=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=Vg;
vendor: 5,171 bytes, line 5
5return void 0!==r&&(r=Dg(r),c=Ug),kg(o,c,(function(o,c){var d;switch(Lg(c,0)){case"$":return"$";case"&":return e;case"`":return Mg(t,0,i);case"'":return Mg(t,s);case"<":d=r[Mg(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>a){var u=Pg(l/10);return 0===u?o:u<=a?void 0===n[u-1]?Lg(c,1):n[u-1]+Lg(c,1):o}d=n[l-1]}return void 0===d?"":d}))},Xg=ht("replace"),Jg=TypeError,Qg=Bg("".indexOf),Zg=Bg("".replace),$g=Bg("".slice),eT=Math.max,tT=function(e,t,i){return i>e.length?-1:""===t?i:Qg(e,t,i)};xg({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,d,l,u=jg(this),h=0,p=0,_="";if(!Wg(e)){if((i=Hg(e))&&(n=Kg(jg(zg(e))),!~Qg(n,"g")))throw Jg("`.replaceAll` does not allow non-global regexes");if(r=Yg(e,Xg))return Fg(r,e,u,t);if(i)return Zg(Kg(u),e,t)}for(o=Kg(u),s=Kg(e),(a=Gg(t))||(t=Kg(t)),c=s.length,d=eT(1,c),h=tT(o,s,0);-1!==h;)l=a?Kg(t(s,h,o)):qg(s,o,h,[],void 0,t),_+=$g(o,p,h)+l,p=h+c,h=tT(o,s,h+d);return p<o.length&&(_+=$g(o,p)),_}});var iT=Ji("String").replaceAll,nT=l,rT=iT,oT=String.prototype,sT=function(e){var t=e.replaceAll;return"string"==typeof e||e===oT||nT(oT,e)&&t===oT.replaceAll?rT:t},aT=i(sT),cT=h;wi({global:!0,forced:cT.globalThis!==cT},{globalThis:cT});var dT=i(h),lT={exports:{}};!function(e,i){!function(t,n){var r="function",o="undefined",s="object",a="string",c="major",d="model",l="name",u="type",h="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",S="smarttv",g="wearable",T="embedded",R="Amazon",C="Apple",v="ASUS",y="BlackBerry",I="Browser",A="Chrome",b="Firefox",w="Google",O="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",V="Xiaomi",x="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},W=function(e,t){return typeof e===a&&-1!==H(t).indexOf(H(e))},H=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,350)},Y=function(e,t){for(var i,o,a,c,d,l,u=0;u<t.length&&!d;){var h=t[u],p=t[u+1];for(i=o=0;i<h.length&&!d&&h[i];)if(d=h[i++].exec(e))for(a=0;a<p.length;a++)l=d[++o],typeof(c=p[a])===s&&c.length>0?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}},z=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(W(t[i][r],e))return"?"===i?n:i}else if(W(t[i],e))return"?"===i?n:i;return e},q={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+I],p],[/\bfocus\/([\w\.]+)/i],[p,[l,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+I]],[/fxios\/([-\w\.]+)/i],[p,[l,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+I]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+I],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,A+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,A+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+I]],[/(chrome|omniweb|arora|[t
vendor: 4,813 bytes, line 5
5izenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,z,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,H]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[h,k],[u,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[h,k],[u,m]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[h,C],[u,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[h,C],[u,f]],[/(macintosh);/i],[d,[h,C]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[h,M],[u,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[h,O],[u,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[h,O],[u,m]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[h,V],[u,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[h,V],[u,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[h,"OPPO"],[u,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[h,"Vivo"],[u,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[h,"Realme"],[u,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[h,P],[u,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[h,P],[u,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[h,N],[u,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[h,N],[u,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[h,"Lenovo"],[u,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[h,"Nokia"],[u,m]],[/(pixel c)\b/i],[d,[h,w],[u,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[h,w],[u,m]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[h,U],[u,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[h,U],[u,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[h,"OnePlus"],[u,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[h,R],[u,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[h,R],[u,m]],[/(playbook);[-\w\),; ]+(rim)/i],[d,h,[u,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[h,y],[u,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[h,v],[u,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[h,v],[u,m]],[/(nexus 9)/i],[d,[h,"HTC"],[u,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[d,/_/g," "],[u,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[h,"Acer"],[u,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[h,"Meizu"],[u,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asu
vendor: 5,737 bytes, line 5
5s)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[h,d,[u,m]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[h,d,[u,f]],[/(surface duo)/i],[d,[h,D],[u,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[h,"Fairphone"],[u,m]],[/(u304aa)/i],[d,[h,"AT&T"],[u,m]],[/\bsie-(\w*)/i],[d,[h,"Siemens"],[u,m]],[/\b(rct\w+) b/i],[d,[h,"RCA"],[u,f]],[/\b(venue[\d ]{2,7}) b/i],[d,[h,"Dell"],[u,f]],[/\b(q(?:mv|ta)\w+) b/i],[d,[h,"Verizon"],[u,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[h,"Barnes & Noble"],[u,f]],[/\b(tm\d{3}\w+) b/i],[d,[h,"NuVision"],[u,f]],[/\b(k88) b/i],[d,[h,"ZTE"],[u,f]],[/\b(nx\d{3}j) b/i],[d,[h,"ZTE"],[u,m]],[/\b(gen\d{3}) b.+49h/i],[d,[h,"Swiss"],[u,m]],[/\b(zur\d{3}) b/i],[d,[h,"Swiss"],[u,f]],[/\b((zeki)?tb.*\b) b/i],[d,[h,"Zeki"],[u,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],d,[u,f]],[/\b(ns-?\w{0,9}) b/i],[d,[h,"Insignia"],[u,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[h,"NextBook"],[u,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],d,[u,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],d,[u,m]],[/\b(ph-1) /i],[d,[h,"Essential"],[u,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[h,"Envizen"],[u,f]],[/\b(trio[-\w\. ]+) b/i],[d,[h,"MachSpeed"],[u,f]],[/\btu_(1491) b/i],[d,[h,"Rotor"],[u,f]],[/(shield[\w ]+) b/i],[d,[h,"Nvidia"],[u,f]],[/(sprint) (\w+)/i],[h,d,[u,m]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[h,D],[u,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[h,x],[u,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[h,x],[u,m]],[/smart-tv.+(samsung)/i],[h,[u,S]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[h,k],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,N],[u,S]],[/(apple) ?tv/i],[h,[d,C+" TV"],[u,S]],[/crkey/i],[[d,A+"cast"],[h,w],[u,S]],[/droid.+aft(\w)( bui|\))/i],[d,[h,R],[u,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[h,M],[u,S]],[/(bravia[\w ]+)( bui|\))/i],[d,[h,U],[u,S]],[/(mitv-\w{5}) bui/i],[d,[h,V],[u,S]],[/Hbbtv.*(technisat) (.*);/i],[h,d,[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,K],[d,K],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,d,[u,E]],[/droid.+; (shield) bui/i],[d,[h,"Nvidia"],[u,E]],[/(playstation [345portablevi]+)/i],[d,[h,U],[u,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[h,D],[u,E]],[/((pebble))app/i],[h,d,[u,g]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[h,C],[u,g]],[/droid.+; (glass) \d/i],[d,[h,w],[u,g]],[/droid.+; (wt63?0{2,3})\)/i],[d,[h,x],[u,g]],[/(quest( 2| pro)?)/i],[d,[h,F],[u,g]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[u,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,m]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,z,q]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,z,q]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,j],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,y]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,A+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},J=function(e,i){if(typeof e===s&&(i=e,e=n),!(this instanceof J))return new J
vendor: 5,760 bytes, line 5
5(e,i).getResult();var E=typeof t!==o&&t.navigator?t.navigator:n,S=e||(E&&E.userAgent?E.userAgent:""),g=E&&E.userAgentData?E.userAgentData:n,T=i?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(X,i):X;return this.getBrowser=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.browser),e[c]=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[p]),E&&E.brave&&typeof E.brave.isBrave==r&&(e[l]="Brave"),e},this.getCPU=function(){var e={};return e[_]=n,Y.call(e,S,T.cpu),e},this.getDevice=function(){var e={};return e[h]=n,e[d]=n,e[u]=n,Y.call(e,S,T.device),!e[u]&&g&&g.mobile&&(e[u]=m),"Macintosh"==e[d]&&E&&typeof E.standalone!==o&&E.maxTouchPoints&&E.maxTouchPoints>2&&(e[d]="iPad",e[u]=f),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.os),!e[l]&&g&&"Unknown"!=g.platform&&(e[l]=g.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 S},this.setUA=function(e){return S=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(S),this};J.VERSION="0.7.34",J.BROWSER=G([l,p,c]),J.CPU=G([_]),J.DEVICE=G([d,h,u,E,m,S,f,g,T]),J.ENGINE=J.OS=G([l,p]),e.exports&&(i=e.exports=J),i.UAParser=J;var Q=typeof t!==o&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new J;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)}(lT,lT.exports);var uT=i(lT.exports),hT=bd.clear;wi({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==hT},{clearImmediate:hT});var pT="function"==typeof Bun&&Bun&&"string"==typeof Bun.version,_T=h,ET=f,mT=w,fT=pT,ST=ce,gT=Qc,TT=$c,RT=_T.Function,CT=/MSIE .\./.test(ST)||fT&&function(){var e=_T.Bun.version.split(".");return e.length<3||0==e[0]&&(e[1]<3||3==e[1]&&0==e[2])}(),vT=wi,yT=h,IT=bd.set,AT=function(e,t){var i=t?2:1;return CT?function(n,r){var o=TT(arguments.length,1)>i,s=mT(n)?n:RT(n),a=o?gT(arguments,i):[],c=o?function(){ET(s,this,a)}:s;return t?e(c,r):e(c)}:e},bT=yT.setImmediate?AT(IT,!1):IT;vT({global:!0,bind:!0,enumerable:!0,forced:yT.setImmediate!==bT},{setImmediate:bT});var wT=i(ie.setImmediate),OT=wi,NT=el,DT=De,PT=$c,LT=jn,kT=h.process;OT({global:!0,enumerable:!0,dontCallGetSet:!0},{queueMicrotask:function(e){PT(arguments.length,1),DT(e);var t=LT&&kT.domain;NT(t?t.bind(e):e)}});var MT=i(ie.queueMicrotask);function UT(e,t){return function(){return e.apply(t,arguments)}}const{toString:VT}=Object.prototype,{getPrototypeOf:xT}=Object,{iterator:FT,toStringTag:BT}=Symbol,jT=(GT=Object.create(null),e=>{const t=VT.call(e);return GT[t]||(GT[t]=t.slice(8,-1).toLowerCase())});var GT;const WT=e=>(e=e.toLowerCase(),t=>jT(t)===e),HT=e=>t=>typeof t===e,{isArray:KT}=Array,YT=HT("undefined");function zT(e){return null!==e&&!YT(e)&&null!==e.constructor&&!YT(e.constructor)&&JT(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const qT=WT("ArrayBuffer");const XT=HT("string"),JT=HT("function"),QT=HT("number"),ZT=e=>null!==e&&"object"==typeof e,$T=e=>{if("object"!==jT(e))return!1;const t=xT(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||BT in e||FT in e)},eR=WT("Date"),tR=WT("File"),iR=WT("Blob"),nR=WT("FileList"),rR=WT("URLSearchParams"),[oR,sR,aR,cR]=["ReadableStream","Request","Response","Headers"].map(WT);function dR(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]),KT(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(zT(e))return;const n=r?Object.getOwnPropertyNames(e):Object.keys(e),o=n.length;let s;for(i=0;i<o;i++)s=n[i],t.call(null,e[s],s,e)}}function lR(e,t){if(zT(e))return null;t=t.toLowerCase();const i=Object.keys(e);let n,r=i.length;for(;r-- >0;)if(n=i[r],t===n.toLowerCase())return n;return null}const uR=void 0!==dT?dT:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,hR=e=>!YT(e)&&e!==uR;const pR=(_R="undefined"!=typeof Uint8Array&&xT(Uint8Array),e=>_R&&e instanceof _R);var _R;const ER=WT("HTMLFormElement"),mR=(e=>{let{hasOwnProperty:t}=e;return(e,i)=>t.call(e,i)})(Object.prototype),fR=WT("RegExp"),SR=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};dR(i,((i,r)=>{let o;!1!==(o=t(i,r,e))&&(n[r]=o||i)})),Object.defineProperties(e,n)};const gR=WT("AsyncFunction"),TR=(RR="function"==typeof wT,CR=JT(uR.postMessage),RR?wT:CR?(vR="axios@".concat(Math.random()),yR=[],uR.addEventListener("message",(e=>{let{source:t,data:i}=e;t===uR&&i===vR&&yR.length&&yR.shift()()}),!1),e=>{yR.push(e),uR.postMessage(vR,"*")}):e=>setTimeout(e));var RR,CR,vR,yR;const IR=void 0!==MT?MT.bind(uR):"undefined"!=typeof process&&process.nextTick||TR;var AR={isArray:KT,isArrayBuffer:qT,isBuffer:zT,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||JT(e.append)&&("formdata"===(t=jT(e))||"object"===t&&JT(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&qT(e.buffer),t},isString:XT,isNumber:QT,isBoolean:e=>!0===e||!1===e,isObject:ZT,isPlainObject:$T,isEmptyObject:e=>{if(!ZT(e)||zT(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:oR,isRequest:sR,isResponse:aR,isHeaders:cR,isUndefined:YT,isDate:eR,isFile:tR,isBlob:iR,isRegExp:fR,isFunction:JT,isStream:e=>ZT(e)&&JT(e.pipe),isURLSearchParams:rR,isTypedArray:pR,isFileList:nR,forEac
vendor: 5,444 bytes, line 5
5h:dR,merge:function e(){const{caseless:t,skipUndefined:i}=hR(this)&&this||{},n={},r=(r,o)=>{const s=t&&lR(n,o)||o;$T(n[s])&&$T(r)?n[s]=e(n[s],r):$T(r)?n[s]=e({},r):KT(r)?n[s]=r.slice():i&&YT(r)||(n[s]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&dR(arguments[e],r);return n},extend:function(e,t,i){let{allOwnKeys:n}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return dR(t,((t,n)=>{i&&JT(t)?Object.defineProperty(e,n,{value:UT(t,i),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:n}),e},trim:e=>dg(e)?dg(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),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),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&&xT(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:jT,kindOfTest:WT,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(KT(e))return e;let t=e.length;if(!QT(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[FT]).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:ER,hasOwnProperty:mR,hasOwnProp:mR,reduceDescriptors:SR,freezeMethods:e=>{SR(e,((t,i)=>{if(JT(e)&&-1!==["arguments","caller","callee"].indexOf(i))return!1;const n=e[i];JT(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 KT(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)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:lR,global:uR,isContextDefined:hR,isSpecCompliantForm:function(e){return!!(e&&JT(e.append)&&"FormData"===e[BT]&&e[FT])},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(ZT(e)){if(t.indexOf(e)>=0)return;if(zT(e))return e;if(!("toJSON"in e)){t[n]=e;const r=KT(e)?[]:{};return dR(e,((e,t)=>{const o=i(e,n+1);!YT(o)&&(r[t]=o)})),t[n]=void 0,r}}return e};return i(e,0)},isAsyncFn:gR,isThenable:e=>e&&(ZT(e)||JT(e))&&JT(e.then)&&JT(e.catch),setImmediate:TR,asap:IR,isIterable:e=>null!=e&&JT(e[FT])};class bR extends Error{static from(e,t,i,n,r,o){const s=new bR(e.message,t||e.code,i,n,r);return s.cause=e,s.name=e.name,o&&Object.assign(s,o),s}constructor(e,t,i,n,r){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status)}toJSON(){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:AR.toJSONObject(this.config),code:this.code,status:this.status}}}bR.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",bR.ERR_BAD_OPTION="ERR_BAD_OPTION",bR.ECONNABORTED="ECONNABORTED",bR.ETIMEDOUT="ETIMEDOUT",bR.ERR_NETWORK="ERR_NETWORK",bR.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",bR.ERR_DEPRECATED="ERR_DEPRECATED",bR.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",bR.ERR_BAD_REQUEST="ERR_BAD_REQUEST",bR.ERR_CANCELED="ERR_CANCELED",bR.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",bR.ERR_INVALID_URL="ERR_INVALID_URL";var wR=bR;function OR(e){return AR.isPlainObject(e)||AR.isArray(e)}function NR(e){return AR.endsWith(e,"[]")?e.slice(0,-2):e}function DR(e,t,i){return e?e.concat(t).map((function(e,t){return e=NR(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}const PR=AR.toFlatObject(AR,{},null,(function(e){return/^is[A-Z]/.test(e)}));function LR(e,t,i){if(!AR.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(i=AR.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!AR.isUndefined(t[e])}))).metaTokens,r=i.visitor||d,o=i.dots,s=i.indexes,a=(i.Blob||"undefined"!=typeof Blob&&Blob)&&AR.isSpecCompliantForm(t);if(!AR.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(AR.isDate(e))return e.toISOString();if(AR.isBoolean(e))return e.toString();if(!a&&AR.isBlob(e))throw new wR("Blob is not supported. Use a Buffer instead.");return AR.isArrayBuffer(e)||AR.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(AR.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(AR.isArray(e)&&function(e){return AR.isArray(e)&&!e.some(OR)}(e)||(AR.isFileList(e)||AR.endsWith(i,"[]"))&&(a=AR.toArray(e)))return i=NR(i),a.forEach((function(e,n){!AR.isUndefined(e)&&null!==e&&t.append(!0===s?DR([i],n,o):null===s?i:i+"[]",c(e))})),!1;return!!OR(e)||(t.append(DR(r,i,o),c(e)),!1)}const l=[],u=Object.assign(PR,{defaultVisitor:d,convertValue:c,isVisitable:OR});if(!AR.isObject(e))throw new TypeError("data must be an object");
vendor: 4,401 bytes, line 5
5return function e(i,n){if(!AR.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),AR.forEach(i,(function(i,o){!0===(!(AR.isUndefined(i)||null===i)&&r.call(t,i,AR.isString(o)?dg(o).call(o):o,n,u))&&e(i,n?n.concat(o):[o])})),l.pop()}}(e),t}function kR(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function MR(e,t){this._pairs=[],e&&LR(e,this,t)}const UR=MR.prototype;function VR(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function xR(e,t,i){if(!t)return e;const n=i&&i.encode||VR,r=AR.isFunction(i)?{serialize:i}:i,o=r&&r.serialize;let s;if(s=o?o(t,r):AR.isURLSearchParams(t)?t.toString():new MR(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}UR.append=function(e,t){this._pairs.push([e,t])},UR.toString=function(e){const t=e?function(t){return e.call(this,t,kR)}:kR;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var FR=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){AR.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},BR={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},jR={exports:{}},GR=wi,WR=N,HR=Qt.f;GR({target:"Object",stat:!0,forced:Object.defineProperty!==HR,sham:!WR},{defineProperty:HR});var KR=ie.Object,YR=jR.exports=function(e,t,i){return KR.defineProperty(e,t,i)};KR.defineProperty.sham&&(YR.sham=!0);var zR=i(jR.exports),qR=TypeError,XR=Qn,JR=Gc,QR=te,ZR=ht("species"),$R=Array,eC=function(e){var t;return XR(e)&&(t=e.constructor,(JR(t)&&(t===$R||XR(t.prototype))||QR(t)&&null===(t=t[ZR]))&&(t=void 0)),void 0===t?$R:t},tC=function(e,t){return new(eC(e))(0===t?0:t)},iC=n,nC=Ee,rC=ht("species"),oC=function(e){return nC>=51||!iC((function(){var t=[];return(t.constructor={})[rC]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},sC=wi,aC=n,cC=Qn,dC=te,lC=Xe,uC=Gi,hC=function(e){if(e>9007199254740991)throw qR("Maximum allowed index exceeded");return e},pC=rp,_C=tC,EC=oC,mC=Ee,fC=ht("isConcatSpreadable"),SC=mC>=51||!aC((function(){var e=[];return e[fC]=!1,e.concat()[0]!==e})),gC=function(e){if(!dC(e))return!1;var t=e[fC];return void 0!==t?!!t:cC(e)};sC({target:"Array",proto:!0,arity:1,forced:!SC||!EC("concat")},{concat:function(e){var t,i,n,r,o,s=lC(this),a=_C(s,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(gC(o=-1===t?s:arguments[t]))for(r=uC(o),hC(c+r),i=0;i<r;i++,c++)i in o&&pC(a,c,o[i]);else hC(c+1),pC(a,c++,o);return a.length=c,a}});var TC={},RC=R,CC=Z,vC=Nr.f,yC=lp,IC="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];TC.f=function(e){return IC&&"Window"==RC(e)?function(e){try{return vC(e)}catch(e){return yC(IC)}}(e):vC(CC(e))};var AC={},bC=ht;AC.f=bC;var wC=ie,OC=Ze,NC=AC,DC=Qt.f,PC=function(e){var t=wC.Symbol||(wC.Symbol={});OC(t,e)||DC(t,e,{value:NC.f(e)})},LC=L,kC=ae,MC=ht,UC=pa,VC=function(){var e=kC("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,n=MC("toPrimitive");t&&!t[n]&&UC(t,n,(function(e){return LC(i,this)}),{arity:1})},xC=Jt,FC=K,BC=Xe,jC=Gi,GC=tC,WC=d([].push),HC=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,d,l,u){for(var h,p,_=BC(c),E=FC(_),m=xC(d,l),f=jC(E),S=0,g=u||GC,T=t?g(c,f):i||s?g(c,0):void 0;f>S;S++)if((a||S in E)&&(p=m(h=E[S],S,_),e))if(t)T[S]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return S;case 2:WC(T,h)}else switch(e){case 4:return!1;case 7:WC(T,h)}return o?-1:n||r?r:T}},KC={forEach:HC(0),map:HC(1),filter:HC(2),some:HC(3),every:HC(4),find:HC(5),findIndex:HC(6),filterReject:HC(7)},YC=wi,zC=h,qC=L,XC=d,JC=N,QC=ge,ZC=n,$C=Ze,ev=l,tv=ii,iv=Z,nv=Ct,rv=mn,ov=B,sv=yo,av=to,cv=Nr,dv=TC,lv=jr,uv=O,hv=Qt,pv=Zr,_v=k,Ev=pa,mv=pc,fv=Ye,Sv=Dr,gv=nt,Tv=ht,Rv=AC,Cv=PC,vv=VC,yv=Pa,Iv=oa,Av=KC.forEach,bv=ur("hidden"),wv="Symbol",Ov="prototype",Nv=Iv.set,Dv=Iv.getterFor(wv),Pv=Object[Ov],Lv=zC.Symbol,kv=Lv&&Lv[Ov],Mv=zC.TypeError,Uv=zC.QObject,Vv=uv.f,xv=hv.f,Fv=dv.f,Bv=_v.f,jv=XC([].push),Gv=fv("symbols"),Wv=fv("op-symbol
5s"),Hv=fv("wks"),Kv=!Uv||!Uv[Ov]||!Uv[Ov].findChild,Yv=JC&&ZC((function(){return 7!=sv(xv({},"a",{get:function(){return xv(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=Vv(Pv,t);n&&delete Pv[t],xv(e,t,i),n&&e!==Pv&&xv(Pv,t,n)}:xv,zv=function(e,t){var i=Gv[e]=sv(kv);return Nv(i,{type:wv,tag:e,description:t}),JC||(i.description=t),i},qv=function(e,t,i){e===Pv&&qv(Wv,t,i),tv(e);var n=nv(t);return tv(i),$C(Gv,n)?(i.enumerable?($C(e,bv)&&e[bv][n]&&(e[bv][n]=!1),i=sv(i,{enumerable:ov(0,!1)})):($C(e,bv)||xv(e,bv,ov(1,{})),e[bv][n]=!0),Yv(e,n,i)):xv(e,n,i)},Xv=function(e,t){tv(e);var i=iv(t),n=av(i).concat($v(i));return Av(n,(function(t){JC&&!qC(Jv,i,t)||qv(e,t,i[t])})),e},Jv=function(e){var t=nv(e),i=qC(Bv,this,t);return!(this===Pv&&$C(Gv,t)&&!$C(Wv,t))&&(!(i||!$C(this,t)||!$C(Gv,t)||$C(this,bv)&&this[bv][t])||i)},Qv=function(e,t){var i=iv(e),n=nv(t);if(i!==Pv||!$C(Gv,n)||$C(Wv,n)){var r=Vv(i,n);return!r||!$C(Gv,n)||$C(i,bv)&&i[bv][n]||(r.enumerable=!0),r}},Zv=function(e){var t=Fv(iv(e)),i=[];return Av(t,(function(e){$C(Gv,e)||$C(Sv,e)||jv(i,e)})),i},$v=function(e){var t=e===Pv,i=Fv(t?Wv:iv(e)),n=[];return Av(i,(function(e){!$C(Gv,e)||t&&!$C(Pv,e)||jv(n,Gv[e])})),n};QC||(Lv=function(){if(ev(kv,this))throw Mv("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?rv(arguments[0]):void 0,t=gv(e),i=function(e){this===Pv&&qC(i,Wv,e),$C(this,bv)&&$C(this[bv],t)&&(this[bv][t]=!1),Yv(this,t,ov(1,e))};return JC&&Kv&&Yv(Pv,t,{configurable:!0,set:i}),zv(t,e)},Ev(kv=Lv[Ov],"toString",(function(){return Dv(this).tag})),Ev(Lv,"withoutSetter",(function(e){return zv(gv(e),e)})),_v.f=Jv,hv.f=qv,pv.f=Xv,uv.f=Qv,cv.f=dv.f=Zv,lv.f=$v,Rv.f=function(e){return zv(Tv(e),e)},JC&&mv(kv,"description",{configurable:!0,get:function(){return Dv(this).description}})),YC({global:!0,constructor:!0,wrap:!0,forced:!QC,sham:!QC},{Symbol:Lv}),Av(av(Hv),(function(e){Cv(e)})),YC({target:wv,stat:!0,forced:!QC},{useSetter:function(){Kv=!0},useSimple:function(){Kv=!1}}),YC({target:"Object",stat:!0,forced:!QC,sham:!JC},{create:function(e,t){return void 0===t?sv(e):Xv(sv(e),t)},defineProperty:qv,defineProperties:Xv,getOwnPropertyDescriptor:Qv}),YC({target:"Object",stat:!0,forced:!QC},{getOwnPropertyNames:Zv}),vv(),yv(Lv,wv),Sv[bv]=!0;var ey=ge&&!!Symbol.for&&!!Symbol.keyFor,ty=wi,iy=ae,ny=Ze,ry=mn,oy=Ye,sy=ey,ay=oy("string-to-symbol-registry"),cy=oy("symbol-to-string-registry");ty({target:"Symbol",stat:!0,forced:!sy},{for:function(e){var t=ry(e);if(ny(ay,t))return ay[t];var i=iy("Symbol")(t);return ay[t]=i,cy[i]=t,i}});var dy=wi,ly=Ze,uy=Ie,hy=be,py=ey,_y=Ye("symbol-to-string-registry");dy({target:"Symbol",stat:!0,forced:!py},{keyFor:function(e){if(!uy(e))throw TypeError(hy(e)+" is not a symbol");if(ly(_y,e))return _y[e]}});var Ey=Qn,my=w,fy=R,Sy=mn,gy=d([].push),Ty=wi,Ry=ae,Cy=f,vy=L,yy=d,Iy=n,Ay=w,by=Ie,wy=Qc,Oy=function(e){if(my(e))return e;if(Ey(e)){for(var t=e.length,i=[],n=0;n<t;n++){var r=e[n];"string"==typeof r?gy(i,r):"number"!=typeof r&&"Number"!=fy(r)&&"String"!=fy(r)||gy(i,Sy(r))}var o=i.length,s=!0;return function(e,t){if(s)return s=!1,t;if(Ey(this))return t;for(var n=0;n<o;n++)if(i[n]===e)return t}}},Ny=ge,Dy=String,Py=Ry("JSON","stringify"),Ly=yy(/./.exec),ky=yy("".charAt),My=yy("".charCodeAt),Uy=yy("".replace),Vy=yy(1..toString),xy=/[\uD800-\uDFFF]/g,Fy=/^[\uD800-\uDBFF]$/,By=/^[\uDC00-\uDFFF]$/,jy=!Ny||Iy((function(){var e=Ry("Symbol")();return"[null]"!=Py([e])||"{}"!=Py({a:e})||"{}"!=Py(Object(e))})),Gy=Iy((function(){return'"\\udf06\\ud834"'!==Py("\udf06\ud834")||'"\\udead"'!==Py("\udead")})),Wy=function(e,t){var i=wy(arguments),n=Oy(t);if(Ay(n)||void 0!==e&&!by(e))return i[1]=function(e,t){if(Ay(n)&&(t=vy(n,this,Dy(e),t)),!by(t))return t},Cy(Py,null,i)},Hy=function(e,t,i){var n=ky(i,t-1),r=ky(i,t+1);return Ly(Fy,e)&&!Ly(By,r)||Ly(By,e)&&!Ly(Fy,n)?"\\u"+Vy(My(e,0),16):e};Py&&Ty({target:"JSON",stat:!0,arity:3,forced:jy||Gy},{stringify:function(e,t,i){var n=wy(arguments),r=Cy(jy?Wy:Py,null,n);return Gy&&"string"==typeof r?Uy(r,xy,Hy):r}});var Ky=jr,Yy=Xe;wi({target:"Object",stat:!0,forced:!ge||n((function(){Ky.f(1)}))},{getOwnPropertySymbols:function(e){var t=Ky.f;return t?t(Yy(e)):[]}}),PC("asyncIterator"),PC("hasInstance"),PC("isConcatSpreadable"),PC("iterator"),PC("match"),PC("matchAll"),PC("replace"),PC("search"),PC("species"),PC("split");var zy=VC;PC("toPrimitive"),zy();var qy=ae,Xy=Pa;PC("toStringTag"),Xy(qy("Symbol"),"Symbol"),PC("unscopables"),Pa(h.JSON,"JSON",!0);var Jy=ie.Symbol,Qy=ht,Zy=Qt.f,$y=Qy("metadata"),eI=Function.prototype;void 0===eI[$y]&&Zy(eI,$y,{value:null}),PC("dispose"),PC("metadata");var tI=Jy;PC("asyncDispose");var iI=d,nI=ae("Symbol"),rI=nI.keyFor,oI=iI(nI.prototype.valueOf),sI=nI.isRegisteredSymbol||function(e){try{return void 0!==rI(oI(e))}catch(e){return!1}};wi({target:"Symbol",stat:!0},{isRegisteredSymbol:sI});for(var aI=Ye,cI=ae,dI=d,lI=Ie,uI=ht,hI=cI("Symbol"),pI=hI.isWellKnownSymbol,_I=cI("Object","getOwnPropertyNames"),EI=dI(hI.prototype.valueOf),mI=aI("wks"),fI=0,SI=_I(hI),gI=SI.length;fI<gI;fI++)try{var TI=SI[fI];lI(hI[TI])&&uI(TI)}catch(e){}var RI=function(e){if(pI&&pI(e))return!0;try{for(var t=EI(e),i=0,n=_I(mI),r=n.length;i<r;i++)if(mI[n[i]]==t)return!0}catch(e){}return!1};wi({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:RI}),PC("matcher"),PC("observable"),wi({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:sI}),wi({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:RI}),PC("metadataKey"),PC("patternMatch"),PC("replaceAll");var CI=i(tI),vI=i(AC.f("iterator"));function yI(e){return yI="function"==typeof CI&&"symbol"==typeof vI?function(e){return typeof e}:function(e){return e&&"function"==typeof CI&&e.constructor===CI&&e!==CI.prototype?"symbol":typeof e},yI(e)}var II=i(AC.f("toPrimitive"));function AI(e){var t=function(e,t){if("object"!==yI(e)||null===e)return e;var i=e[II];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==yI(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===yI(t)?t:String(t)}function bI(e,t,i){return(t=AI(t))in e?zR(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}
5var wI=i(EE),OI={isBrowser:!0,classes:{URLSearchParams:void 0!==wI?wI:MR,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const NI="undefined"!=typeof window&&"undefined"!=typeof document,DI="object"==typeof navigator&&navigator||void 0,PI=NI&&(!DI||["ReactNative","NativeScript","NS"].indexOf(DI.product)<0),LI="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,kI=NI&&window.location.href||"http://localhost";function MI(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 UI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?MI(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):MI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var VI=UI(UI({},Object.freeze({__proto__:null,hasBrowserEnv:NI,hasStandardBrowserEnv:PI,hasStandardBrowserWebWorkerEnv:LI,navigator:DI,origin:kI})),OI);function xI(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 FI(e,t){return LR(e,new VI.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xI(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({visitor:function(e,t,i,n){return VI.isNode&&AR.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}var BI=vh.charAt,jI=L,GI=ii,WI=w,HI=R,KI=/./.exec,YI=TypeError,zI=wi,qI=L,XI=y,JI=Fa,QI=nc,ZI=X,$I=Bi,eA=mn,tA=ii,iA=Y,nA=R,rA=tn,oA=Og,sA=ke,aA=n,cA=Jc,dA=function(e,t,i){return t+(i?BI(e,t).length:1)},lA=function(e,t){var i=e.exec;if(WI(i)){var n=jI(i,e,t);return null!==n&&GI(n),n}if("RegExp"===HI(e))return jI(KI,e,t);throw YI("RegExp#exec called on incompatible receiver")},uA=oa,hA=ht("matchAll"),pA="RegExp String",_A=pA+" Iterator",EA=uA.set,mA=uA.getterFor(_A),fA=TypeError,SA=XI("".indexOf),gA=XI("".matchAll),TA=!!gA&&!aA((function(){gA("a",/./)})),RA=JI((function(e,t,i,n){EA(this,{type:_A,regexp:e,string:t,global:i,unicode:n,done:!1})}),pA,(function(){var e=mA(this);if(e.done)return QI(void 0,!0);var t=e.regexp,i=e.string,n=lA(t,i);return null===n?(e.done=!0,QI(void 0,!0)):e.global?(""===eA(n[0])&&(t.lastIndex=dA(i,$I(t.lastIndex),e.unicode)),QI(n,!1)):(e.done=!0,QI(n,!1))})),CA=function(e){var t,i,n,r=tA(this),o=eA(e),s=cA(r,RegExp),a=eA(oA(r));return t=new s(s===RegExp?r.source:r,a),i=!!~SA(a,"g"),n=!!~SA(a,"u"),t.lastIndex=$I(r.lastIndex),new RA(t,o,i,n)};zI({target:"String",proto:!0,forced:TA},{matchAll:function(e){var t,i,n,r,o=ZI(this);if(iA(e)){if(TA)return gA(o,e)}else{if(rA(e)&&(t=eA(ZI(oA(e))),!~SA(t,"g")))throw fA("`.matchAll` does not allow non-global regexes");if(TA)return gA(o,e);if(void 0===(n=sA(e,hA))&&"RegExp"==nA(e)&&(n=CA),n)return qI(n,e,o)}return i=eA(o),r=new RegExp(e,"g"),qI(CA,r,i)}});var vA=Ji("String").matchAll,yA=l,IA=vA,AA=String.prototype,bA=function(e){var t=e.matchAll;return"string"==typeof e||e===AA||yA(AA,e)&&t===AA.matchAll?IA:t},wA=i(bA);function OA(e){function t(e,i,n,r){let o=e[r++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=r>=e.length;if(o=!o&&AR.isArray(n)?n.length:o,a)return AR.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!s;n[o]&&AR.isObject(n[o])||(n[o]=[]);return t(e,i,n[o],r)&&AR.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<r;n++)o=i[n],t[o]=e[o];return t}(n[o])),!s}if(AR.isFormData(e)&&AR.isFunction(e.entries)){const i={};return AR.forEachEntry(e,((e,n)=>{t(function(e){return wA(AR).call(AR,/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const NA={transitional:BR,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=AR.isObject(e);r&&AR.isHTMLForm(e)&&(e=new FormData(e));if(AR.isFormData(e))return n?JSON.stringify(OA(e)):e;if(AR.isArrayBuffer(e)||AR.isBuffer(e)||AR.isStream(e)||AR.isFile(e)||AR.isBlob(e)||AR.isReadableStream(e))return e;if(AR.isArrayBufferView(e))return e.buffer;if(AR.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")>
vendor: 4,629 bytes, line 5
5-1)return FI(e,this.formSerializer).toString();if((o=AR.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return LR(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if(AR.isString(e))try{return(t||JSON.parse)(e),dg(AR).call(AR,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||NA.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(AR.isResponse(e)||AR.isReadableStream(e))return e;if(e&&AR.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,this.parseReviver)}catch(e){if(i){if("SyntaxError"===e.name)throw wR.from(e,wR.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:VI.classes.FormData,Blob:VI.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};AR.forEach(["delete","get","head","post","put","patch"],(e=>{NA.headers[e]={}}));var DA=NA;const PA=AR.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 LA=Symbol("internals");function kA(e){var t;return e&&dg(t=String(e)).call(t).toLowerCase()}function MA(e){return!1===e||null==e?e:AR.isArray(e)?e.map(MA):String(e)}function UA(e,t,i,n,r){return AR.isFunction(n)?n.call(this,t,i):(r&&(t=i),AR.isString(t)?AR.isString(n)?-1!==t.indexOf(n):AR.isRegExp(n)?n.test(t):void 0:void 0)}class VA{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=kA(t);if(!r)throw new Error("header name must be a non-empty string");const o=AR.findKey(n,r);(!o||void 0===n[o]||!0===i||void 0===i&&!1!==n[o])&&(n[o||t]=MA(e))}const o=(e,t)=>AR.forEach(e,((e,i)=>r(e,i,t)));if(AR.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(AR.isString(e)&&(e=dg(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(dg(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=dg(o=e.substring(0,r)).call(o).toLowerCase(),n=dg(s=e.substring(r+1)).call(s),!i||t[i]&&PA[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t);else if(AR.isObject(e)&&AR.isIterable(e)){let i,n,r={};for(const t of e){if(!AR.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[n=t[0]]=(i=r[n])?AR.isArray(i)?[...i,t[1]]:[i,t[1]]:t[1]}o(r,t)}else null!=e&&r(t,e,i);var s;return this}get(e,t){if(e=kA(e)){const i=AR.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(AR.isFunction(t))return t.call(this,e,i);if(AR.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=kA(e)){const i=AR.findKey(this,e);return!(!i||void 0===this[i]||t&&!UA(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=kA(e)){const r=AR.findKey(i,e);!r||t&&!UA(0,i[r],r,t)||(delete i[r],n=!0)}}return AR.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&&!UA(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return AR.forEach(this,((n,r)=>{var o;const s=AR.findKey(i,r);if(s)return t[s]=MA(n),void delete t[r];const a=e?function(e){return dg(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):dg(o=String(r)).call(o);a!==r&&delete t[r],t[a]=MA(n),i[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return this.constructor.concat(this,...t)}toJSON(e){const t=Object.create(null);return AR.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&AR.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")}getSetCookie(){return this.get("set-cookie")||[]}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;r<i;r++)n[r-1]=arguments[r];
vendor: 8,410 bytes, line 5
5return n.forEach((e=>t.set(e))),t}static accessor(e){const t=(this[LA]=this[LA]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=kA(e);t[n]||(!function(e,t){const i=AR.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 AR.isArray(e)?e.forEach(n):n(e),this}}VA.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),AR.reduceDescriptors(VA.prototype,((e,t)=>{let{value:i}=e,n=t[0].toUpperCase()+t.slice(1);return{get:()=>i,set(e){this[n]=e}}})),AR.freezeMethods(VA);var xA=VA;function FA(e,t){const i=this||DA,n=t||i,r=xA.from(n.headers);let o=n.data;return AR.forEach(e,(function(e){o=e.call(i,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function BA(e){return!(!e||!e.__CANCEL__)}var jA=class extends wR{constructor(e,t,i){super(null==e?"canceled":e,wR.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}};function GA(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new wR("Request failed with status code "+i.status,[wR.ERR_BAD_REQUEST,wR.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}const WA=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0;const r=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<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let i,n,r=0,o=1e3/t;const s=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,i=null,n&&(clearTimeout(n),n=null),e(...t)};return[function(){const e=Date.now(),t=e-r;for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];t>=o?s(c,e):(i=c,n||(n=setTimeout((()=>{n=null,s(i)}),o-t)))},()=>i&&s(i)]}((i=>{const o=i.loaded,s=i.lengthComputable?i.total:void 0,a=o-n,c=r(a);n=o;e({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:i,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),i)},HA=(e,t)=>{const i=null!=e;return[n=>t[0]({lengthComputable:i,total:e,loaded:n}),t[1]]},KA=e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return AR.asap((()=>e(...i)))};var YA=VI.hasStandardBrowserEnv?((e,t)=>i=>(i=new Zf(i,VI.origin),e.protocol===i.protocol&&e.host===i.host&&(t||e.port===i.port)))(new Zf(VI.origin),VI.navigator&&/(msie|trident)/i.test(VI.navigator.userAgent)):()=>!0,zA=VI.hasStandardBrowserEnv?{write(e,t,i,n,r,o,s){if("undefined"==typeof document)return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];AR.isNumber(i)&&a.push("expires=".concat(new Date(i).toUTCString())),AR.isString(n)&&a.push("path=".concat(n)),AR.isString(r)&&a.push("domain=".concat(r)),!0===o&&a.push("secure"),AR.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function qA(e,t,i){let n=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(n||0==i)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}function XA(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 JA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?XA(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):XA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const QA=e=>e instanceof xA?JA({},e):e;function ZA(e,t){t=t||{};const i={};function n(e,t,i,n){return AR.isPlainObject(e)&&AR.isPlainObject(t)?AR.merge.call({caseless:n},e,t):AR.isPlainObject(t)?AR.merge({},t):AR.isArray(t)?t.slice():t}function r(e,t,i,r){return AR.isUndefined(t)?AR.isUndefined(e)?void 0:n(void 0,e,0,r):n(e,t,0,r)}function o(e,t){if(!AR.isUndefined(t))return n(void 0,t)}function s(e,t){return AR.isUndefined(t)?AR.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(i,r,o){return o in t?n(i,r):o in e?n(void 0,i):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,i)=>r(QA(e),QA(t),0,!0)};return AR.forEach(Object.keys(JA(JA({},e),t)),(function(n){const o=c[n]||r,s=o(e[n],t[n],n);AR.isUndefined(s)&&o!==a||(i[n]=s)})),i}var $A=e=>{const t=ZA({},e);let{data:i,withXSRFToken:n,xsrfHeaderName:r,xsrfCookieName:o,headers:s,auth:a}=t;if(t.headers=s=xA.from(s),t.url=xR(qA(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),AR.isFormData(i))if(VI.hasStandardBrowserEnv||VI.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(AR.isFunction(i.getHeaders)){const e=i.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach((e=>{let[i,n]=e;Dn(t).call(t,i.toLowerCase())&&s.set(i,n)}))}if(VI.hasStandardBrowserEnv&&(n&&AR.isFunction(n)&&(n=n(t)),n||!1!==n&&YA(t.url))){const e=r&&o&&zA.read(o);e&&s.set(r,e)}return t};var eb="undefined"!=typeof XMLHttpRequest&&function(e){return new Wh((function(t,i){const n=$A(e);let r=n.data;const o=xA.from(n.headers).normalize();let s,a,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=n;function _(){d&&d(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let E=new XMLHttpRequest;function m(){if(!E)return;const n=xA.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders());GA((function(e){t(e),_()}),(function(e){i(e),_()}),{data:u&&"text"!==u&&"json"!==u?E.response:E.responseText,status:E.status,statusText:E.statusText,headers:n,config:e,request:E}),E=null}E.open(n.method.toUpperCase(),n.url,!0),E.timeout=n.timeout,"onloadend"in E?E.onloadend=m:E.onreadystatechange=function(){E&&4===E.readyState&&(0!==E.status||E.responseURL&&0===E.responseURL.indexOf("file:"))&&setTimeout(m)},E.onabort=function(){E&&(i(new wR("Request aborted",wR.ECONNABORTED,e,E)),E=null)},E.onerror=function(t){const n=t&&t.message?t.message:"Network Error",r=new wR(n,wR.ERR_NETWORK,e,E);r.event=t||null,i(r),E=null},E.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const r=n.transitional||BR;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),i(new wR(t,r.clarifyTimeoutError?wR.ETIMEDOUT:wR.ECONNABORTED,e,E)),E=null},void 0===r&&o.setContentType(null),"setRequestHeader"in E&&AR.forEach(o.toJSON(),(function(e,t){E.setRequestHeader(t,e)})),AR.isUndefined(n.withCredentials)||(E.withCredentials=!!n.withCredentials),u&&"json"!==u&&(E.responseType=n.responseType),p&&([c,l]=WA(p,!0),E.addEventListener("progress",c)),h&&E.upload&&([a,d]=WA(h),E.upload.addEventListener("progress",a),E.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(s=t=>{E&&(i(!t||t.type?new jA(null,e,E):t),E.abort(),E=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const f=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);f&&-1===VI.protocols.indexOf(f)?i(new wR("Unsupported protocol "+f+":",wR.ERR_BAD_REQUEST,e)):E.send(r||null)}))};var tb=(e,t)=>{const{length:i}=e=e?e.filter(Boolean):[];if(t||i){let i,n=new AbortController;const r=function(e){if(!i){i=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof wR?t:new jA(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>
vendor: 4,302 bytes, line 5
5{o=null,r(new wR("timeout of ".concat(t,"ms exceeded"),wR.ETIMEDOUT))}),t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)})),e=null)};e.forEach((e=>e.addEventListener("abort",r)));const{signal:a}=n;return a.unsubscribe=()=>AR.asap(s),a}},ib=Gh,nb=Tl;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=nb.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var rb=Tl,ob=tl;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=rb.f(this),i=ob(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var sb=i(ib),ab=AC.f("asyncIterator"),cb=i(ab);function db(e,t){this.v=e,this.k=t}function lb(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof db;sb.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 sb((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 ub(e){return function(){return new lb(e.apply(this,arguments))}}function hb(e){return new db(e,0)}function pb(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new db(n=new sb((function(i){i(e[t](n))})),1)}}return t[void 0!==CI&&vI||"@@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}lb.prototype["function"==typeof CI&&cb||"@@asyncIterator"]=function(){return this},lb.prototype.next=function(e){return this._invoke("next",e)},lb.prototype.throw=function(e){return this._invoke("throw",e)},lb.prototype.return=function(e){return this._invoke("return",e)};var _b=i(ab);function Eb(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=_b,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new mb(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function mb(e){function t(e){if(Object(e)!==e)return Wh.reject(new TypeError(e+" is not an object."));var t=e.done;return Wh.resolve(e.value).then((function(e){return{value:e,done:t}}))}return mb=function(e){this.s=e,this.n=e.next},mb.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Wh.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Wh.reject(e):t(i.apply(this.s,arguments))}},new mb(e)}const fb=function*(e,t){let i=e.byteLength;if(!t||i<t)return void(yield e);let n,r=0;for(;r<i;)n=r+t,yield e.slice(r,n),r=n},Sb=function(){var e=ub((function*(e,t){var i,n=!1,r=!1;try{for(var o,s=Eb(gb(e));n=!(o=yield hb(s.next())).done;n=!1){const e=o.value;yield*pb(Eb(fb(e,t)))}}catch(e){r=!0,i=e}finally{try{n&&null!=s.return&&(yield hb(s.return()))}finally{if(r)throw i}}}));return function(t,i){return e.apply(this,arguments)}}(),gb=function(){var e=ub((function*(e){if(e[_b])return void(yield*pb(Eb(e)));const t=e.getReader();try{for(;;){const{done:e,value:i}=yield hb(t.read());if(e)break;yield i}}finally{yield hb(t.cancel())}}));return function(t){return e.apply(this,arguments)}}(),Tb=(e,t,i,n)=>{const r=Sb(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await r.next();if(t)return a(),void e.close();let o=n.byteLength;if(i){let e=s+=o;i(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})};function Rb(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 Cb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
vendor: 9,023 bytes, line 5
5t%2?Rb(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Rb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const{isFunction:vb}=AR,yb=(e=>{let{Request:t,Response:i}=e;return{Request:t,Response:i}})(AR.global),{ReadableStream:Ib,TextEncoder:Ab}=AR.global,bb=function(e){try{for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return!!e(...i)}catch(e){return!1}},wb=e=>{e=AR.merge.call({skipUndefined:!0},yb,e);const{fetch:t,Request:i,Response:n}=e,r=t?vb(t):"function"==typeof fetch,o=vb(i),s=vb(n);if(!r)return!1;const a=r&&vb(Ib),c=r&&("function"==typeof Ab?(d=new Ab,e=>d.encode(e)):async e=>new Uint8Array(await new i(e).arrayBuffer()));var d;const l=o&&a&&bb((()=>{let e=!1;const t=new i(VI.origin,{body:new Ib,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),u=s&&a&&bb((()=>AR.isReadableStream(new n("").body))),h={stream:u&&(e=>e.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!h[e]&&(h[e]=(t,i)=>{let n=t&&t[e];if(n)return n.call(t);throw new wR("Response type '".concat(e,"' is not supported"),wR.ERR_NOT_SUPPORT,i)})}));const p=async(e,t)=>{const n=AR.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(AR.isBlob(e))return e.size;if(AR.isSpecCompliantForm(e)){const t=new i(VI.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return AR.isArrayBufferView(e)||AR.isArrayBuffer(e)?e.byteLength:(AR.isURLSearchParams(e)&&(e+=""),AR.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:r,method:s,data:a,signal:c,cancelToken:d,timeout:_,onDownloadProgress:E,onUploadProgress:m,responseType:f,headers:S,withCredentials:g="same-origin",fetchOptions:T}=$A(e),R=t||fetch;f=f?(f+"").toLowerCase():"text";let C=tb([c,d&&d.toAbortSignal()],_),v=null;const y=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let I;try{if(m&&l&&"get"!==s&&"head"!==s&&0!==(I=await p(S,a))){let e,t=new i(r,{method:"POST",body:a,duplex:"half"});if(AR.isFormData(a)&&(e=t.headers.get("content-type"))&&S.setContentType(e),t.body){const[e,i]=HA(I,WA(KA(m)));a=Tb(t.body,65536,e,i)}}AR.isString(g)||(g=g?"include":"omit");const t=o&&"credentials"in i.prototype,c=Cb(Cb({},T),{},{signal:C,method:s.toUpperCase(),headers:S.normalize().toJSON(),body:a,duplex:"half",credentials:t?g:void 0});v=o&&new i(r,c);let d=await(o?R(v,T):R(r,c));const _=u&&("stream"===f||"response"===f);if(u&&(E||_&&y)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=d[t]}));const t=AR.toFiniteNumber(d.headers.get("content-length")),[i,r]=E&&HA(t,WA(KA(E),!0))||[];d=new n(Tb(d.body,65536,i,(()=>{r&&r(),y&&y()})),e)}f=f||"text";let A=await h[AR.findKey(h,f)||"text"](d,e);return!_&&y&&y(),await new Wh(((t,i)=>{GA(t,i,{data:A,headers:xA.from(d.headers),status:d.status,statusText:d.statusText,config:e,request:v})}))}catch(t){if(y&&y(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new wR("Network Error",wR.ERR_NETWORK,e,v),{cause:t.cause||t});throw wR.from(t,t&&t.code,e,v)}}},Ob=new Map,Nb=e=>{let t=e&&e.env||{};const{fetch:i,Request:n,Response:r}=t,o=[n,r,i];let s,a,c=o.length,d=Ob;for(;c--;)s=o[c],a=d.get(s),void 0===a&&d.set(s,a=c?new Map:wb(t)),d=a;return a};Nb();const Db={http:null,xhr:eb,fetch:{get:Nb}};AR.forEach(Db,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const Pb=e=>"- ".concat(e),Lb=e=>AR.isFunction(e)||null===e||!1===e;var kb={getAdapter:function(e,t){e=AR.isArray(e)?e:[e];const{length:i}=e;let n,r;const o={};for(let s=0;s<i;s++){let i;if(n=e[s],r=n,!Lb(n)&&(r=Db[(i=String(n)).toLowerCase()],void 0===r))throw new wR("Unknown adapter '".concat(i,"'"));if(r&&(AR.isFunction(r)||(r=r.get(t))))break;o[i||"#"+s]=r}if(!r){const e=Object.entries(o).map((e=>{let[t,i]=e;return"adapter ".concat(t," ")+(!1===i?"is not supported by the environment":"is not available in the build")}));let t=i?e.length>1?"since :\n"+e.map(Pb).join("\n"):" "+Pb(e[0]):"as no adapter specified";throw new wR("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r},adapters:Db};function Mb(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new jA(null,e)}function Ub(e){Mb(e),e.headers=xA.from(e.headers),e.data=FA.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return kb.getAdapter(e.adapter||DA.adapter,e)(e).then((function(t){return Mb(e),t.data=FA.call(e,e.transformResponse,t),t.headers=xA.from(t.headers),t}),(function(t){return BA(t)||(Mb(e),t&&t.response&&(t.response.data=FA.call(e,e.transformResponse,t.response),t.response.headers=xA.from(t.response.headers))),Wh.reject(t)}))}const Vb="1.13.4",xb={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{xb[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const Fb={};xb.transitional=function(e,t,i){function n(e,t){return"[Axios v"+Vb+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,r,o)=>{if(!1===e)throw new wR(n(r," has been removed"+(t?" in "+t:"")),wR.ERR_DEPRECATED);return t&&!Fb[r]&&(Fb[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)}},xb.spelling=function(e){return(t,i)=>(console.warn("".concat(i," is likely a misspelling of ").concat(e)),!0)};var Bb={assertOptions:function(e,t,i){if("object"!=typeof e)throw new wR("options must be an object",wR.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 wR("option "+o+" must be "+i,wR.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new wR("Unknown option "+o,wR.ERR_BAD_OPTION)}},validators:xb};const jb=Bb.validators;let Gb=class{constructor(e){this.defaults=e||{},this.interceptors={request:new FR,response:new FR}}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/,""):"";try{e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=ZA(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&Bb.assertOptions(i,{silentJSONParsing:jb.transitional(jb.boolean),forcedJSONParsing:jb.transitional(jb.boolean),clarifyTimeoutError:jb.transitional(jb.boolean)},!1),null!=n&&(AR.isFunction(n)?t.paramsSerializer={serialize:n}:Bb.assertOptions(n,{encode:jb.function,serialize:jb.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Bb.assertOptions(t,{baseUrl:jb.spelling("baseURL"),withXsrfToken:jb.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&AR.merge(r.common,r[t.method]);r&&AR.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete r[e]})),t.headers=xA.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=[Ub.bind(this),void 0];for(e.unshift(...s),e.push(...c),l=e.length,d=Wh.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=s.length;let h=t;for(;u<l;){const e=s[u++],t=s[u++];try{h=e(h)}catch(e){t.call(this,e);break}}try{d=Ub.call(this,h)}catch(e){return Wh.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return xR(qA((e=ZA(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};AR.forEach(["delete","get","head","options"],(function(e){Gb.prototype[e]=function(t,i){return this.request(ZA(i||{},{method:e,url:t,data:(i||{}).data}))}})),AR.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(ZA(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}Gb.prototype[e]=t(),Gb.prototype[e+"Form"]=t(!0)}));var Wb=Gb;class Hb{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Wh((function(e){t=e}));const i=this;this.promise.then((e=>{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 Wh((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 jA(e,n,r),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}
vendor: 9,239 bytes, line 5
5subscribe(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)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new Hb((function(t){e=t}));return{token:t,cancel:e}}}var Kb=Hb;const Yb={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Yb).forEach((e=>{let[t,i]=e;Yb[i]=t}));var zb=Yb;const qb=function e(t){const i=new Wb(t),n=UT(Wb.prototype.request,i);return AR.extend(n,Wb.prototype,i,{allOwnKeys:!0}),AR.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(ZA(t,i))},n}(DA);qb.Axios=Wb,qb.CanceledError=jA,qb.CancelToken=Kb,qb.isCancel=BA,qb.VERSION=Vb,qb.toFormData=LR,qb.AxiosError=wR,qb.Cancel=qb.CanceledError,qb.all=function(e){return Wh.all(e)},qb.spread=function(e){return function(t){return e.apply(null,t)}},qb.isAxiosError=function(e){return AR.isObject(e)&&!0===e.isAxiosError},qb.mergeConfig=ZA,qb.AxiosHeaders=xA,qb.formToJSON=e=>OA(AR.isHTMLForm(e)?new FormData(e):e),qb.getAdapter=kb.getAdapter,qb.HttpStatusCode=zb,qb.default=qb;var Xb=qb;const Jb=()=>{};function Qb(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:Jb};return e.promise=new Wh(((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 Zb=new Map,$b=new Map,ew=new Map;let tw=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}({}),iw=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 nw=new uT;let rw=nw.getResult(),ow=null;function sw(e){if(!ow){e&&nw.setUA(e),rw=nw.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return iw.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return iw.CHROME;case"Safari":case"Mobile Safari":return iw.SAFARI;case"Edge":return iw.EDGE;case"Firefox":return iw.FIREFOX;case"QQ":case"QQBrowser":return iw.QQ;case"Opera":return iw.OPERA;case"WeChat":return iw.WECHAT;default:return e.browser.name||""}}(rw),i=aw(rw),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(rw),r=rw.os.version,o=aw(rw,!1),s=rw.device.type;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s};ow={name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s}}return ow}function aw(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 cw(){return sw().os}function dw(){const e=sw();return"".concat(e.os," ").concat(e.osVersion)}function lw(){const e=sw();return!!("WebKit"===rw.engine.name&&e.os===tw.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==iw.SAFARI||Ew()&&e.name!==iw.SAFARI)}function uw(){return sw().name===iw.CHROME}function hw(){return sw().name===iw.SAFARI}function pw(){return sw().name===iw.EDGE}function _w(){return sw().name===iw.FIREFOX}function Ew(){return sw().os===tw.IOS}function mw(e){const t=sw();return!(t.name!==iw.CHROME||!t.osVersion)&&Number(t.version)>=e}function fw(e){const t=sw();return!(t.name!==iw.CHROME||!t.osVersion)&&Number(t.version)<e}function Sw(e,t,i){const n=sw();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}function gw(e){const t=sw();return!(t.name!==iw.EDGE||!t.osVersion)&&Number(t.version)>=e}function Tw(e){const t=sw();return!(t.name!==iw.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function Rw(e){const t=sw();return!(t.name!==iw.SAFARI||!t.osVersion)&&Number(t.version)>=e}function Cw(e,t,i){const n=sw();if(n.os!==tw.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])>t||Number(r[0])>e:t?Number(r[0])===e&&Number(r[1])>=t||Number(r[0])>e:Number(r[0])>=e}function vw(e,t,i){const n=sw();if(n.os!==tw.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function yw(e,t,i){const n=sw();if(n.name!==iw.SAFARI||!n.osVersion||!n.browserVersion)return!1;const r=n.browserVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function Iw(e){const t=sw();return!(t.name!==iw.OPERA||!t.osVersion)&&Number(t.version)>=e}function Aw(){const e=sw();if(e.os!==tw.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function bw(){const e=sw();if(e.os!==tw.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function ww(){const e=sw();if(e.os!==tw.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function Ow(){const e=sw();if(e.os!==tw.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function Nw(){return hw()&&navigator.maxTouchPoints>0}function Dw(){return sw().name===iw.WECHAT}function Pw(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function Lw(){const e=cw();return function(){const{deviceType:e}=sw();return"mobile"===e||"tablet"===e}()||e===tw.ANDROID||e===tw.IOS||e===tw.HARMONY_OS}function kw(){const e=sw();return e.name!==iw.EDGE&&e.name!==iw.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function Mw(){return cw()===tw.ANDROID}function Uw(){const e=sw();return Mw()&&(e.name===iw.CHROME||e.name===iw.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function Vw(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 xw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Vw(Object(i),!0).forEach((function(t){Fw(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Vw(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Fw(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===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:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let Bw=function(e){return e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_E
5RROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",e}({}
vendor: 121,265 bytes, line 5
5),jw=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),Fw(this,"code",void 0),Fw(this,"message",void 0),Fw(this,"data",void 0),Fw(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"".concat(this.message,"\ndata: ").concat(JSON.stringify(this.data)):this.message}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 Gw(e,t){if("boolean"!=typeof e)throw new jw(Bw.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Ww(e,t,i){if(!Dn(i).call(i,e))throw new jw(Bw.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function Hw(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(e<i||e>n||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new jw(Bw.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function Kw(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new jw(Bw.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&Hw(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&Hw(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&Hw(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&Hw(e.ideal,"".concat(t,".ideal"),1,1/0)}else Hw(e,t,1,1/0)}function Yw(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 jw(Bw.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!Xw(e,i,n,r))throw new jw(Bw.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function zw(e,t){if(!Array.isArray(e))throw new jw(Bw.INVALID_PARAMS,"".concat(t," should be an array"))}function qw(e){return null==e}function Xw(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;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return!1}return!0}(e))}function Jw(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),o=Number(!!i),s=Number(!i);return BigInt(n*s+r*o)<<BigInt(32)|BigInt(n*o+r*s)}function Qw(e,t,i,n){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,n);const r=Number(i>>BigInt(32)),o=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,o,n)):(e.setUint32(t,r,n),e.setUint32(t+4,o,n))}var Zw=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(Zw||{}),$w=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}($w||{});const eO=new class{constructor(){Fw(this,"_clientSize",null),Fw(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),Fw(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),Fw(this,"getStyle",(e=>window.getComputedStyle(e,null))),Fw(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)})),Fw(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})),Fw(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),Fw(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)}})),Fw(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),Fw(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),Fw(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),Fw(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]})),Fw(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),Fw(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),Fw(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<o))return!1;a=e}if(t<0)return!1;if(c=t<o?t:o,i<0)d=0;else{if(!(i<r))return!1;d=i}if(n<0)return!1;l=n<r?n:r;const u=c-a,h=l-d;return this.checkSizeIsVisible(u,h,s)})),Fw(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),Fw(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(Zw.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(Zw.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(Zw.SIZE)}}return this.returnHiddenResult(Zw.STYLE)}return this.returnHiddenResult($w.UNMOUNTED)}return this.returnHiddenResult($w.INVALID_HTML_ELEMENT)})),Fw(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function tO(e){return(new TextEncoder).encode(e)}const iO=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 nO=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",tO(e)),16);let rO=class{constructor(){Fw(this,"_events",{}),Fw(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;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[])}}safeEmit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];[...this._events[e]||[]].forEach((t=>{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 oO=null;function sO(){if(oO)return oO;if(window.electron)return oO=window.electron;if(!window.require)return null;try{return oO=window.require("electron"),oO}catch(e){return null}}let aO=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.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",e.PRELOAD_MEDIA_FAILED="preloadMediaFailed",e.MISMATCH_DTLS_PARAMETERS="mismatchDtlsParameters",e.VOS_FALLBACK_CN="vosFallbackCN",e.DATACHANNEL_FAILBACK="datachannelFailback",e}({}),cO=function(e){return e.TRACER="tracer",e}({});function dO(e){return Hw(e.timeout,"config.timeout",0,1e5),Hw(e.timeoutFactor,"config.timeoutFactor",0,100,!1),Hw(e.maxRetryCount,"config.maxRetryConfig",0,1/0),Hw(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let lO=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}({}),uO=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.FALLBACK_TO_HLS="FALLBACK_TO_HLS",e.UID_CONFLICT="UID_CONFLICT",e}({});function hO(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 pO(e){return Yw(e.turnServerURL,"turnServerURL"),Yw(e.username,"username"),Yw(e.password,"password"),e.udpport&&Hw(e.udpport,"udpport",1,99999,!0),e.forceturn&&Gw(e.forceturn,"forceturn"),e.security&&Gw(e.security,"security"),e.tcpport&&Hw(e.tcpport,"tcpport",1,99999,!0),!0}let _O=function(e){return e[e.AUTO_SIMULCAST_STREAM=-1]="AUTO_SIMULCAST_STREAM",e[e.DISABLE_SIMULCAST_STREM=0]="DISABLE_SIMULCAST_STREM",e[e.ENABLE_SIMULCAST_STREAM=1]="ENABLE_SIMULCAST_STREAM",e}({});function EO(e){return void 0!==e.level&&Ww(e.level,"level",[1,2,3]),void 0!==e.delay&&Hw(e.delay,"delay",0,3e3,!0),!0}let mO=function(e){return e.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",e.AUDIO_METADATA="audio-metadata",e.AUDIO_PTS="audio-pts",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.FALLBACK_TO_HLS="fallback-to-hls",e.FIRST_VIDEO_BUFFER_READY="first-video-buffer-ready",e.FIRST_VIDEO_PRE_RENDER="first-video-pre-render",e.AV1_DECODABLE_RESULT="av1-decodable-result",e}({}),fO=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}),SO=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.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",e}({}),gO=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),TO=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function RO(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?Wh.reject(new jw(Bw.UNEXPECTED_ERROR,"can not emit promise")):new Wh(((i,r)=>{e.emit(t,...n,i,r)}))}function CO(e,t){if(0===e.getListeners(t).length)return Wh.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return RO(e,t,...n)}function vO(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return yO(e,t,...n)}function yO(e,t){let i=null,n=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,(e=>{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new jw(Bw.UNEXPECTED_ERROR,"handler is not sync");return i}const IO=new class extends rO{set networkState(e){this.emit(TO.NETWORK_STATE_CHANGE,e,this._networkState),e===gO.ONLINE?this.emit(TO.ONLINE):e===gO.OFFLINE&&(this.onlineWaiter=new Wh((e=>{this.once(TO.ONLINE,(()=>{this.onlineWaiter=void 0,e(gO.ONLINE)}))})),this.emit(TO.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===gO.ONLINE}constructor(){super(),Fw(this,"_moduleName","network-indicator"),Fw(this,"_networkState",gO.ONLINE),Fw(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=gO.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=gO.OFFLINE}))}},AO=[];for(let e=0;e<256;++e)AO.push((e+256).toString(16).slice(1));const bO="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let wO;const OO=new Uint8Array(16);function NO(){return bO?bO():function(e,t,i){var n,r,o,s;const a=null!==(n=null!==(r=(e=e||{}).random)&&void 0!==r?r:null===(o=(s=e).rng)||void 0===o?void 0:o.call(s))&&void 0!==n?n:function(){if(!wO){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");wO=crypto.getRandomValues.bind(crypto)}return wO(OO)}();if(a.length<16)throw new Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((i=i||0)<0||i+16>t.length)throw new RangeError("UUID byte range ".concat(i,":").concat(i+15," is out of buffer bounds"));for(let e=0;e<16;++e)t[i+e]=a[e];return t}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(AO[e[t+0]]+AO[e[t+1]]+AO[e[t+2]]+AO[e[t+3]]+"-"+AO[e[t+4]]+AO[e[t+5]]+"-"+AO[e[t+6]]+AO[e[t+7]]+"-"+AO[e[t+8]]+AO[e[t+9]]+"-"+AO[e[t+10]]+AO[e[t+11]]+AO[e[t+12]]+AO[e[t+13]]+AO[e[t+14]]+AO[e[t+15]]).toLowerCase()}(a)}(e,t,undefined);var e,t}function DO(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function PO(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function LO(e){void 0!==Wh?Wh.resolve().then(e):setTimeout(e,0)}function kO(e){return JSON.parse(JSON.stringify(e))}function MO(e){try{return kO(e)}catch(t){return e}}const UO={};function VO(e,t){UO[t]||(UO[t]=!0,e())}function xO(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}function FO(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}function BO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=(new TextEncoder).encode(e);if(i.length>t)i=i.slice(0,t);else if(i.length<t){const e=new Uint8Array(t);e.set(i),i=e}return i}function jO(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=Xn(t).call(t,((e,t)=>e+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 GO(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function WO(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?GO(e):e.size})),t+138}function HO(e){const t=new jw(Bw.TIMEOUT,"timeout");return new Wh(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function KO(e){return new Wh((t=>{window.setTimeout(t,e)}))}function YO(){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)+YO(e-i.length,"")}function zO(){let e,t=!1;try{var i;e=aT(i=NO()).call(i,"-","")}catch(e){t=!0}return!t&&e&&32===e.length||(e=YO(32,"")),e.toUpperCase()}const qO=()=>{},XO=new class{constructor(){Fw(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<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const s=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:s,args:o,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,xw(xw({},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})}}},JO=XO.throttleByKey.bind(XO);function QO(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function ZO(e,t){if(!QO(e)||!QO(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;n<t.length;n++)i[n]=ZO(e[n],t[n]);return i}{const i=xw({},e);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)?i[n]=ZO(e[n],t[n]):i[n]=t[n]);return i}}function $O(e,t){let i=[0];if(t&&(i=new Array(t).fill(0)),0===e)return i;let n=0;for(;e>0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i}function eN(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function tN(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function iN(e){return Xn(e).call(e,((e,t)=>e+t),0)}function nN(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<<t|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<e.length;t++)n[t>>2]|=e.charCodeAt(t)<<t%4*8;return n[t>>2]|=128<<t%4*8,n[16*i-2]=8*e.length,n}(e);let l,u,h,p,_,E=1732584193,m=-271733879,f=-1732584194,S=271733878;for(l=0;l<d.length;l+=16)u=E,h=m,p=f,_=S,E=o(E,m,f,S,d[l+0],7,-680876936),S=o(S,E,m,f,d[l+1],12,-389564586),f=o(f,S,E,m,d[l+2],17,606105819),m=o(m,f,S,E,d[l+3],22,-1044525330),E=o(E,m,f,S,d[l+4],7,-176418897),S=o(S,E,m,f,d[l+5],12,1200080426),f=o(f,S,E,m,d[l+6],17,-1473231341),m=o(m,f,S,E,d[l+7],22,-45705983),E=o(E,m,f,S,d[l+8],7,1770035416),S=o(S,E,m,f,d[l+9],12,-1958414417),f=o(f,S,E,m,d[l+10],17,-42063),m=o(m,f,S,E,d[l+11],22,-1990404162),E=o(E,m,f,S,d[l+12],7,1804603682),S=o(S,E,m,f,d[l+13],12,-40341101),f=o(f,S,E,m,d[l+14],17,-1502002290),m=o(m,f,S,E,d[l+15],22,1236535329),E=s(E,m,f,S,d[l+1],5,-165796510),S=s(S,E,m,f,d[l+6],9,-1069501632),f=s(f,S,E,m,d[l+11],14,643717713),m=s(m,f,S,E,d[l+0],20,-373897302),E=s(E,m,f,S,d[l+5],5,-701558691),S=s(S,E,m,f,d[l+10],9,38016083),f=s(f,S,E,m,d[l+15],14,-660478335),m=s(m,f,S,E,d[l+4],20,-405537848),E=s(E,m,f,S,d[l+9],5,568446438),S=s(S,E,m,f,d[l+14],9,-1019803690),f=s(f,S,E,m,d[l+3],14,-187363961),m=s(m,f,S,E,d[l+8],20,1163531501),E=s(E,m,f,S,d[l+13],5,-1444681467),S=s(S,E,m,f,d[l+2],9,-51403784),f=s(f,S,E,m,d[l+7],14,1735328473),m=s(m,f,S,E,d[l+12],20,-1926607734),E=a(E,m,f,S,d[l+5],4,-378558),S=a(S,E,m,f,d[l+8],11,-2022574463),f=a(f,S,E,m,d[l+11],16,1839030562),m=a(m,f,S,E,d[l+14],23,-35309556),E=a(E,m,f,S,d[l+1],4,-1530992060),S=a(S,E,m,f,d[l+4],11,1272893353),f=a(f,S,E,m,d[l+7],16,-155497632),m=a(m,f,S,E,d[l+10],23,-1094730640),E=a(E,m,f,S,d[l+13],4,681279174),S=a(S,E,m,f,d[l+0],11,-358537222),f=a(f,S,E,m,d[l+3],16,-722521979),m=a(m,f,S,E,d[l+6],23,76029189),E=a(E,m,f,S,d[l+9],4,-640364487),S=a(S,E,m,f,d[l+12],11,-421815835),f=a(f,S,E,m,d[l+15],16,530742520),m=a(m,f,S,E,d[l+2],23,-995338651),E=c(E,m,f,S,d[l+0],6,-198630844),S=c(S,E,m,f,d[l+7],10,1126891415),f=c(f,S,E,m,d[l+14],15,-1416354905),m=c(m,f,S,E,d[l+5],21,-57434055),E=c(E,m,f,S,d[l+12],6,1700485571),S=c(S,E,m,f,d[l+3],10,-1894986606),f=c(f,S,E,m,d[l+10],15,-1051523),m=c(m,f,S,E,d[l+1],21,-2054922799),E=c(E,m,f,S,d[l+8],6,1873313359),S=c(S,E,m,f,d[l+15],10,-30611744),f=c(f,S,E,m,d[l+6],15,-1560198380),m=c(m,f,S,E,d[l+13],21,1309151649),E=c(E,m,f,S,d[l+4],6,-145523070),S=c(S,E,m,f,d[l+11],10,-1120210379),f=c(f,S,E,m,d[l+2],15,718787259),m=c(m,f,S,E,d[l+9],21,-343485551),E=n(E,u),m=n(m,h),f=n(f,p),S=n(S,_);return i(E)+i(m)+i(f)+i(S)}let rN=1,oN=console,sN=class{static setLogger(e){oN=e}constructor(e,t){Fw(this,"id",void 0),Fw(this,"lockingPromise",Wh.resolve()),Fw(this,"locks",0),Fw(this,"name",""),Fw(this,"lockId",void 0),this.lockId=rN++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const i=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),n="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");oN.debug("".concat(i," ").concat(n))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const i=new Wh((i=>{t=()=>{this.locks-=1,this.logger("unlocked",e),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}};function aN(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<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{r()}},r}}const cN={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function dN(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function lN(e,t,i,n){const r=Object.assign({},cN,n);let o=r.timeout;const s=async()=>{await function(e){return new Wh((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new Wh((async(n,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new jw(Bw.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await s()}catch(e){if(!i(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}}));return c.cancel=()=>a=!0,c}let uN,hN=class{constructor(e){Fw(this,"input",[]),Fw(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:Xn(e=this.input).call(e,((e,t)=>e+t))/this.input.length}},pN=0,_N=0;function EN(e,t,i,n){return new Wh(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),pN+=GO(t.data)):i&&(t.data.size?pN+=t.data.size:t.data instanceof FormData?pN+=WO(t.data):pN+=GO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Xb.request(t).then((e=>{"string"==typeof e.data?_N+=GO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?_N+=e.data.byteLength:_N+=GO(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Xb.isCancel(e)?o(new jw(Bw.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new jw(Bw.NETWORK_TIMEOUT,e.message)):e.response?o(new jw(Bw.NETWORK_RESPONSE_ERROR,e.response.status)):o(new jw(Bw.NETWORK_ERROR,e.message))}))}))}async function mN(e,t){const i=new Blob([t.data],{type:"buffer"});return await EN(e,xw(xw({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const fN=()=>void 0!==window.isSecureContext;function SN(e){if(Array.isArray(e))return e.map((e=>e));if(!gN(e))return e;const t={};for(const i in e){const n=e[i];gN(n)||Array.isArray(n)?t[i]=SN(n):t[i]=n}return t}function gN(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let TN=class{constructor(e){Fw(this,"input",[]),Fw(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 RN={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},CN={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],transport:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0},selectedCandidatePair:{id:"unknown",localCandidate:RN,remoteCandidate:RN},updateInterval:0},vN={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,packetsDiscarded:0,framesAssembledFromMultiplePackets:0,totalProcessingDelay:0,avgDecodeMs:0,avgFramesAssembledFromMultiplePacketsMs:0,avgProcessingDelayMs:0,avgInterFrameDelayMs:0,totalAssemblyTime:0},yN={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},IN={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},AN={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0,silentConcealedSamples:0,concealmentEvents:0,freezeMs80:0,freezeMs200:0,freezeSamples80:0,freezeSamples200:0};let bN=class{constructor(e,t){Fw(this,"onFirstVideoReceived",void 0),Fw(this,"onFirstVideoDecoded",void 0),Fw(this,"onFirstAudioReceived",void 0),Fw(this,"onFirstVideoDecodedTimeout",void 0),Fw(this,"onFirstAudioDecoded",void 0),Fw(this,"onSelectedLocalCandidateChanged",void 0),Fw(this,"onSelectedRemoteCandidateChanged",void 0),Fw(this,"videoIsReady",!1),Fw(this,"videoIsReady2",{}),Fw(this,"pc",void 0),Fw(this,"options",void 0),Fw(this,"intervalTimer",void 0),Fw(this,"stats",SN(CN)),Fw(this,"isFirstVideoReceived",{}),Fw(this,"isFirstVideoDecoded",{}),Fw(this,"isFirstAudioReceived",{}),Fw(this,"isFirstAudioDecoded",{}),Fw(this,"isFirstVideoDecodedTimeout",{}),Fw(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval((async()=>{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new Wh((e=>{e({local:xw({},RN),remote:xw({},RN)})}))}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)}},wN=class extends bN{constructor(){super(...arguments),Fw(this,"_stats",CN),Fw(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=SN(CN);const i=t.filter((e=>"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=SN(yN);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=SN(vN),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.framesDecodeCount<i.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:xw({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=SN(AN);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!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=SN(IN);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 Wh(((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}},ON=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),NN=function(e){return e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L1T3_KEY="L1T3_KEY",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY",e}({}),DN=function(e){return e[e.new=0]="new",e[e.connecting=1]="connecting",e[e.connected=2]="connected",e[e.disconnected=3]="disconnected",e[e.failed=4]="failed",e[e.closed=5]="closed",e}({}),PN=function(e){return e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver",e}({});var LN=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(LN||{});function kN(e,t,i,n){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:LN.kNone;if(!t)return;const o=Number(t[i]);if("number"!=typeof o)return;const s=Number(t[n]);if("number"!=typeof s)return;if(!e)return s?o/s*r:void 0;const a=Number(e[i]);if("number"!=typeof a)return;const c=Number(e[n]);if("number"!=typeof c)return;const d=s-c;return d?(o-a)/d*r:void 0}let MN=class extends bN{constructor(){super(...arguments),Fw(this,"_stats",CN),Fw(this,"report",void 0),Fw(this,"lastDecodeVideoReceiverStats",new Map),Fw(this,"lastVideoFramesRecv",new Map),Fw(this,"lastVideoFramesSent",new Map),Fw(this,"lastVideoFramesDecode",new Map),Fw(this,"lastVideoFramesOutput",new Map),Fw(this,"lastVideoJBDelay",new Map),Fw(this,"lastAudioJBDelay",new Map),Fw(this,"mediaBytesSent",new Map),Fw(this,"mediaBytesRetransmit",new Map),Fw(this,"mediaBytesTargetEncode",new Map),Fw(this,"lastDecodeAudioReceiverStats",new Map),Fw(this,"lastAudioConcealment",new Map),Fw(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=SN(CN),this.report.forEach((e=>{switch(e.type){case PN.OUTBOUND:case PN.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===PN.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===PN.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case PN.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case PN.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:xw({},RN),remote:xw({},RN)};return e.forEach((i=>{let n;if(i.type===PN.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===PN.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===PN.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===PN.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===PN.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(xw({},t),xw({},this.stats.selectedCandidatePair.localCandidate)),e.type===PN.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(xw({},t),xw({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=SN(AN),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,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const i=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=kN(i,t,"totalProcessingDelay","jitterBufferEmittedCount",LN.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,i,e),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),this.lastDecodeAudioReceiverStats.set(t.ssrc,xw({},t))}calculateAudioFreeze(e,t,i){const n=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=n){const r=n.lts,o=i.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=n.nonSilent+a,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;const l=80*d/s,u=200*d/s,h=s/d;let p=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>l&&(n.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*h)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*h)),p=n.plc80+1);let _=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>u&&(n.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*h)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*h)),_=n.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:_})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:i.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=SN(vN),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,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;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.framesDecodeCount<n.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(i.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=kN(null==i?void 0:i.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=kN(null==i?void 0:i.stats,t,"totalProcessingDelay","framesDecodeCount",LN.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=kN(null==i?void 0:i.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",LN.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=kN(null==i?void 0:i.stats,t,"totalInterFrameDelay","framesDecodeCount",LN.kMillisecondsFromSeconds),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})),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:xw({},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=SN(yN),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new TN(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 TN(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 TN(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,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,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,PN.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=SN(IN),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,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,PN.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var i;const n=Array.from(Zh(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,l,u;const h=t?this.report.get(t):void 0,p=null!==(n=null==h?void 0:h.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,_=null!==(r=null==h?void 0:h.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,E=null!==(o=null==h?void 0:h.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,m=null!==(s=null==h?void 0:h.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,f=null!==(a=null==h?void 0:h.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,S=null!==(c=null==h?void 0:h.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,g=null!==(d=null==h?void 0:h.concealedSamples)&&void 0!==d?d:e.concealedSamples,T=null!==(l=null==h?void 0:h.silentConcealedSamples)&&void 0!==l?l:e.silentConcealedSamples,R=null!==(u=null==h?void 0:h.concealmentEvents)&&void 0!==u?u:e.concealmentEvents;if("number"==typeof _&&(i.totalSamplesReceived=_),"number"==typeof T&&(i.silentConcealedSamples=T),"number"==typeof R&&(i.concealmentEvents=R),"number"==typeof g&&(i.concealedSamples=g),p&&_&&(i.accelerateRate=p/_),E&&m){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=m-e.jitterBufferEmittedCount;n>0&&(t=1e3*(E-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:m,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=f;let C=1920;S&&_&&(C=_/S/50,i.receivedFrames=Math.round(_/C)),g&&(i.droppedFrames=Math.round(g/C))}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))}},UN=class extends bN{updateStats(){return Wh.resolve()}};function VN(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 wN(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new MN(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof Wh||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new MN(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new UN(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}const xN="websdk_ng_install_id";function FN(){try{if(JN("INSTALL_ID"))return JN("INSTALL_ID");let e=window.localStorage.getItem(xN);return e||(e=zO(),window.localStorage.setItem(xN,e)),XN("INSTALL_ID",e),e}catch(e){return}}const BN=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}return"4.0.0.999"}("4.24.2-200"),jN=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let GN=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const WN=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=WN;const HN={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,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!0,FORCE_ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,PRE_SUB_NUM:1,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"]},KN={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},YN="v4.24.2-200-0-g58279341-dirty(2/5/2026, 5:51:13 PM)",zN={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,NEW_ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",TURN_DOMAINS:["edge.agora.io"],USE_TURN_IP:!0,NEW_TURN_MODE:4,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!1,FLS_FALLBACK_TIMEOUT:3e4,RTE_DETAIL_REPORT_INTERVAL:6e4,ENCODE_EXCEPTION_TIMES:5,ENABLE_ENCODE_EXCEPTION:!0,ENCODE_EXCEPTION_VALIDATE_CODEC:["h264"],VIDEO_ENCODER_CONFIG_LIST:[{width:240,height:180},{width:320,height:240},{width:400,height:300},{width:480,height:360},{width:560,height:420},{width:640,height:480}],DELETE_NEQ_AFTER_USER_LEAVE:!0,UPDATE_RTP_CAP_IN_HOST:!1,IOS_BG_TAG:!0,IOS_AUTO_RESTART_BG_TAG:!0,IGNORE_UID_CHECK:!1,ENABLE_UP_SPS_PPS:!1,ENABLE_DOWN_SPS_PPS:!1,NO_EDGES_RETRY:!0,BUFFER_READY_FRAMES:3,FLS_SYNC_AV_PLAY_LIMIT:0,FLS_BUFFER_WAIT_TIME:1500,VOS_CONFIGURE:void 0,ENABLE_QUALITY_FALLBACK:!1,QUALITY_FALLBACK_REHEARSAL:!0,ENABLE_FLS_AV1_FIRST:!1,ENABLE_AP_MULTI_IP:!0,FLS_ENABLE_AV1_DETECT:!0,FLS_ENABLE_AV1_DECODE_DETECT:!0},qN=xw(xw(xw(xw({},zN),{},{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",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,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,SHOW_REPORT_USER_INVOKER_LOG:!0,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",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,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,FIRST_H264_PROFILE_LEVEL_ID:"42001f",FIRST_PACKETIZATION_MODE:"",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_MANAGER_WSS:"",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,FINGERPRINT:null,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,ENABLE_AUDIO_TOPN:!1,ENABLE_AUDIO_METADATA:!1,ENABLE_AUDIO_PTS:!1,TOPN_SMOOTH_LEVEL:void 0,TOPN_NEW_SPEAKER_DELAY:void 0,TOPN_SWITCH_HOLD_MS:void 0,TOPN_AUDIO_GAIN:void 0,TOPN_SILENCE_THRESHOLD:250,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_WSS:"",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,ENABLE_AUDIO_RED:!1,OPUS_PTIME:void 0,AUDIO_DUPLICATE_NUM:void 0,ENABLE_ABSSENDTIME_AS_SENTTS:!0,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:[],SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,DC_JOIN_WITH_FAILBACK:4e3,DC_CONNECTION_TIMEOUT:2e3,DC_PINGPONG_INTERVAL:2e3,DC_DEBUG_LOG:!1,UNSUPPORTED_VIDEO_UPLINK_CODEC:[],UNSUPPORTED_VIDEO_DOWNLINK_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:KN,CUSTOM_ADAPTATION_DEFAULT_MODE:"",HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,DISABLE_SCREEN_SHARE_REMB:!1},HN),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,REMOTE_VIDEO_STREAM_TYPE:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1,ENABLE_FORCE_HLS:!1,MAX_WEBAUDIO_VOLUME:300,ENABLE_VOS_FALLBACK:!1,ENABLE_FALLBACK_TO_HLS:!1,ENABLE_PRE_RENDER:!1,FORCE_DISABLE_AUTO_SUB:!1,ENABLE_PRE_SUB_WITH_PRE_PC:!0,PRE_USE_LOCAL_CODECS:!0},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:2,BASELINE_MORE_H264_BITRATE_RATIO:1.1,IGNORE_RTC_DEVICE_CHECK:!1,FLS_AUTOPLAY_EMITS:!1,ENABLE_DUAL_STREAM_FLAG:!1,FORBID_MODIFY_LOCAL_OFFER_SDP:!1,RESERVE_MID_1_MLINE:!1});function XN(e,t,i){var n,r,o;Dn(n=Object.keys(qN)).call(n,e)&&(!i&&Dn(r=Object.keys(ZN)).call(r,e)||(qN[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(qN.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,qN.USE_NEW_NETWORK_CONFIG=o,o&&(qN.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],qN.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],qN.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],qN.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],qN.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",qN.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",qN.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(qN.ENABLE_INSTANT_VIDEO=!0,qN.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(qN.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(qN.NEW_TURN_MODE||(qN.NEW_TURN_MODE=4))))}function JN(e){if("TURN_DOMAINS"===e){const e=qN.TURN_DOMAINS;return Dn(e).call(e,JN("TURN_DOMAIN"))?e:[JN("TURN_DOMAIN")].concat(e)}return qN[e]}jN||(qN.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],qN.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],qN.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],qN.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],qN.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],qN.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],qN.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",qN.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",qN.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",qN.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",qN.AREAS=["NORTH_AMERICA","OVERSEA"]);let QN=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const ZN={};var $N=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_RTE_URL="SET_RTE_URL",e.SET_RTE_SID="SET_RTE_SID",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.KEY_METRIC_PRELOAD_START="KEY_METRIC_PRELOAD_START",e.KEY_METRIC_PRELOAD_END="KEY_METRIC_PRELOAD_END",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_REQUEST_SUA_END="KEY_METRIC_REQUEST_SUA_END",e.KEY_METRIC_BEFORE_CONNECT="KEY_METRIC_BEFORE_CONNECT",e.KEY_METRIC_PEER_RECEIVER="KEY_METRIC_PEER_RECEIVER",e.KEY_METRIC_SIGNAL_CONNECTED="KEY_METRIC_SIGNAL_CONNECTED",e.KEY_METRIC_JOIN_REQ="KEY_METRIC_JOIN_REQ",e.KEY_METRIC_JOIN_REP="KEY_METRIC_JOIN_REP",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_FIRST_VIDEO_FRAME_DECODED="KEY_METRIC_FIRST_VIDEO_FRAME_DECODED",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.RESET_FIRST_VIDEO_FRAME_DECODED="RESET_FIRST_VIDEO_FRAME_DECODED",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}($N||{});let eD=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 tD=128,iD=96,nD=1e3,rD=10;let oD=0;var sD=(()=>{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 m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return h(e)||a(e)||"+"===e||"/"===e}function S(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 g(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?S(Object(i),!0).forEach((function(t){T(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):S(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function T(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(s||(s={}));class R{consumeText(e,t){let i=t;for(;i<e.length;){const t=e[i];if("\0"===t||"\r"===t||t===n)break;i+=1}if(i-t==0)throw new Error("Invalid text, at ".concat(e));return i}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,i){let n=t;for(;i(e[n]);)n++;if(n-t==0)throw new Error("Invalid rule at ".concat(t,"."));return n}consumeSpace(e,t){if(e[t]===o)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let i=t;for(let t=0;t<4;t++)if(i=this.consumeDecimalUChar(e,i),3!==t){if("."!==e[i])throw new Error("Invalid IP4 address.");i++}return i}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw new Error("Invalid decimal uchar.");const n=parseInt(e.slice(t,i));if(n>=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<i.length;n++){if(t+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<e.length&&("string"!=typeof i||e[n]!==i)&&("function"!=typeof i||!i(e[n]));)n++;return n}}class C extends R{constructor(){super(),T(this,"records",[]),T(this,"currentLine",0)}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter((e=>!!dg(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<e.length;t++)if(e[t]===n)return"\r"===e[t-1]?r:n;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new y;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(t,(e=>l(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 I(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(e,(e=>l(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.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const i=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const n=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:n}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==s.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==s.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const o=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:n,nettype:r,addrtype:o,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===s.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==s.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===s.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===s.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:n}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,i+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const n=[];for(n.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,n.push(this.extract(e,this.consumeToken));if(0===n.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:n,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),i=this.parseRepeat(),n=this.parseZone();e.push({time:t,repeats:i,zones:n})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),i=this.parseInformation(),n=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:n,bandwidths:r,key:o,attributes:s})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];const o=t.call(this,e.value,e.cur,...n),s=e.value.slice(e.cur,o);return e.cur=o,s}extractOneOrMore(e,t){const i=this.consumeOneOrMore(e.value,e.cur,t),n=e.value.slice(e.cur,i);return e.cur=i,n}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class v extends R{constructor(){super(...arguments),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,i){const n=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,n),[o,s]=i||[];if("number"==typeof o&&r.length<o)throw new Error("error in length, should be more or equal than ".concat(o," characters."));if("number"==typeof s&&r.length>s)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<i;r++)n[r-2]=arguments[r];const o=t.call(this,e.attValue,e._cur,...n),s=e.attValue.slice(e._cur,o);return e._cur=o,s}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=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;i<t.length;i++)if(t[i]!==e.attValue[e._cur+i])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let i;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),i=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,o),r=g(g({entry:parseInt(t,10)},i&&{direction:i}),{},{extensionName:n});this.peekChar(e)===o&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class y extends v{constructor(){super(...arguments),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session 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")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m)}parseIdentity(e){const t=this.extractOneOrMore(e,f),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const n=this.extractOneOrMore(e,(e=>e!==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 I extends v{constructor(e){super(),T(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=dg(t).call(t);const r="string"==typeof i?dg(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)})();function aD(e){return sD.parse(e)}function cD(e,t){return sD.print(e,t)}var dD=Ji("Array").keys,lD=pn,uD=Ze,hD=l,pD=dD,_D=Array.prototype,ED={DOMTokenList:!0,NodeList:!0},mD=function(e){var t=e.keys;return e===_D||hD(_D,e)&&t===_D.keys||uD(ED,lD(e))?pD:t},fD=i(mD);function SD(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 gD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?SD(Object(i),!0).forEach((function(t){RD(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):SD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function TD(){TD=function(e,t){return new i(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function i(e,n,r){var o=new RegExp(e,n);return t.set(o,r||t.get(e)),CD(o,i.prototype)}function n(e,i){var n,r=t.get(i);return Xn(n=Object.keys(r)).call(n,(function(t,i){var n=r[i];if("number"==typeof n)t[i]=e[n];else{for(var o=0;void 0===e[n[o]]&&o+1<n.length;)o++;t[i]=e[n[o]]}return t}),Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&CD(e,t)}(i,RegExp),i.prototype.exec=function(t){var i=e.exec.call(this,t);if(i){i.groups=n(i,this);var r=i.indices;r&&(r.groups=n(r,this))}return i},i.prototype[Symbol.replace]=function(i,r){if("string"==typeof r){var o=t.get(this);return e[Symbol.replace].call(this,i,r.replace(/\$<([^>]+)>/g,(function(e,t){var i=o[t];return"$"+(Array.isArray(i)?i.join("$"):i)})))}if("function"==typeof r){var s=this;return e[Symbol.replace].call(this,i,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(n(e,s)),r.apply(this,e)}))}return e[Symbol.replace].call(this,i,r)},TD.apply(this,arguments)}function RD(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===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:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function CD(e,t){return CD=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},CD(e,t)}const vD=new class extends rO{constructor(){super(...arguments),RD(this,"currentUploadLogID",0)}reportLogUploadError(e){const{errorRange:t}=e;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};class yD{constructor(e){RD(this,"logger",void 0),RD(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}function ID(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function AD(){const e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const bD={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},wD=Date.now(),OD=e=>{for(const t in bD)if(Object.prototype.hasOwnProperty.call(bD,t)&&bD[t]===e)return t;return"DEFAULT"};const ND=new class{constructor(){RD(this,"proxyServerURL",void 0),RD(this,"logLevel",bD.DEBUG),RD(this,"uploadState","collecting"),RD(this,"uploadLogWaitingList",[]),RD(this,"uploadLogUploadingList",[]),RD(this,"uploadErrorCount",0),RD(this,"currentLogID",0),RD(this,"url",void 0),RD(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[bD.DEBUG].concat(t);this.log.apply(this,n)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[bD.INFO].concat(t);this.log.apply(this,n)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[bD.WARNING].concat(t);this.log.apply(this,n)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[bD.ERROR].concat(t);this.log.apply(this,n)}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[bD.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){XN("UPLOAD_LOG",!0)}disableLogUpload(){XN("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new yD(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-wD<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-wD);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=ID()+" Agora-SDK [".concat(OD(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=ID()+" %cAgora-SDK [".concat(OD(n),"]:");let o=[];if(!JN("USE_NEW_LOG"))switch(n){case bD.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case bD.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case bD.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case bD.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-wD<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-wD);const n=Math.max(0,Math.min(4,t[0]));t[0]=ID()+" Agora-SDK [".concat(OD(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!JN("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=AD()+" Agora-SDK [".concat(OD(e),"]:"):i[0]=AD()+" Agora-SDK [".concat(OD(e),"]:");let r="";i.forEach((e=>{"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:BN,process_id:JN("PROCESS_ID"),payload:JSON.stringify(e)};return lN((async()=>{const e=await Xb.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(JN("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(JN("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),vD.reportLogUploadError(i),!0}),{timeout:JN("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:JN("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,JN("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),JN("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),JN("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),JN("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var DD;function PD(e){return Yw(e.reportId,"params.reportId",0,100,!1),Yw(e.category,"params.category",0,100,!1),Yw(e.event,"params.event",0,100,!1),Yw(e.label,"params.label",0,100,!1),Hw(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(DD={}).FREE="free",DD.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]="P
5UBLIC_API"}({});const LD={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let kD=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.RTE_DETAIL="rte_detail_stats",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.XLA_PEER_FIRST_VIDEO_FRAME="xla_peer_first_video_frame",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.AB_TEST="ab_test",e}({}),MD=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.RTE_DETAIL="io.agora.pb.Wrtc.RteDetailStats",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.XLA_PEER_FIRST_VIDEO_FRAME="io.agora.pb.Wrtc.XLAPeerFirstVideoFrame",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.AB_TEST="io.agora.pb.Wrtc.ABTest",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let UD=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}({});function VD(){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,n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let c=s;if(e.argsMap)try{c=e.argsMap(this,...s)}catch(e){ND.warning(e),c=[]}try{JSON.stringify(c)}catch(e){ND.warning("arguments for method ".concat(o,".").concat(String(i)," not serializable for apiInvoke.")),c=[]}const d=(e.report||xD).reportApiInvoke(this._sessionId||null,{id:this._clientId||(null===(t=this.store)||void 0===t?void 0:t.clientId)||this._ID,name:"".concat(o,".").concat(String(i)),options:c,tag:cO.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,s);return t instanceof Wh?t.then((t=>(d.onSuccess(e.reportResult&&t),t))).catch((e=>{throw d.onError(e),e})):(d.onSuccess(e.reportResult&&t),t)}catch(e){throw d.onError(e),e}}}return n}}const xD=new class{constructor(){RD(this,"baseInfoMap",new Map),RD(this,"proxyServer",void 0),RD(this,"eventUploadTimer",void 0),RD(this,"setSessionIdTimer",void 0),RD(this,"url",void 0),RD(this,"sids",new Set),RD(this,"backupUrl",void 0),RD(this,"_appId",void 0),RD(this,"_aid",0),RD(this,"keyEventUploadPendingItems",[]),RD(this,"normalEventUploadPendingItems",[]),RD(this,"apiInvokeUploadPendingItems",[]),RD(this,"apiInvokeCount",0),RD(this,"apiInvokeLoggedCount",0),RD(this,"ltsList",[]),RD(this,"lastSendNormalEventTime",Date.now()),RD(this,"customReportCounterTimer",void 0),RD(this,"customReportCount",0),RD(this,"extApiInvoke",(async e=>{for(const t of e){const e=gD(gD({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:cO.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),JN("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),JN("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,(e=>{let[t,i]=e;return t+i})),16)||0}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=!!JN("SHOW_REPORT_INVOKER_LOG"),s=!!JN("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(e,i){if(a){let n="[apiInvoke-".concat(c,"]");if(t.id&&(n+="[".concat(t.id,"]")),t.name&&(n+="[".concat(t.name,"]"),t.name===aO.JOIN))return ND.info("".concat(n," ").concat(e));ND.info("".concat(n," ").concat(e),"start"===e?t.options:i||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null});d("start");let u=!1;KO(t.timeout).then((()=>{u||(this.sendApiInvoke(gD(gD({},l()),{},{error:Bw.API_INVOKE_TIMEOUT,success:!1})),d("timeout"))}));const h=new jw(Bw.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>
vendor: 49,945 bytes, line 5
5{if(u)throw h;return u=!0,this.sendApiInvoke(gD(gD({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return i?JO(n,t.name+"Success",i,(()=>u=!0)):n()},onError:e=>{const n=()=>{if(u)throw e;u=!0,this.sendApiInvoke(gD(gD({},l()),{},{success:!1,error:e})),d("onFailure",e.toString())};return i?JO(n,t.name+"Error",i,(()=>u=!0)):n()}}}_send(e,t,i){this.send({type:e,data:t},i)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname,n.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:JN("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:jN?"global":"oversea",areas:JN("AREAS")&&JN("AREAS").join(",")},t.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=gD(gD({},n),{},{eventType:kD.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:YN,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:JN("PROCESS_ID"),appType:JN("APP_TYPE"),success:!0,version:BN,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:Dn(p=window.navigator.userAgent).call(p,"AgoraWebView")?42:20,clientRole:l,serviceId:JN("PROCESS_ID"),extensionID:JN("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid});var p;this.send({type:MD.SESSION,data:h},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const i=t.info,n=Date.now(),r=gD(gD({},i),{},{eventType:kD.RTE_DETAIL,lts:n,success:!0,elapse:n-t.startTime,vid:void 0===i.vid?0:Number(i.vid),ua:navigator.userAgent});this.send({type:MD.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid);const r=Date.now(),o=gD(gD({},n),{},{role:t.role,eventType:kD.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,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:MD.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=gD(gD({},n),{},{eventType:kD.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:MD.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,addr:s,isProxy:a}=t,c=r-i.startTime,d=gD(gD({},n),{},{eventType:kD.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:c,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:FN(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:a?1:0}),l=d.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)if("1"===d.signalChannel){const e=TD(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),t=s.match(e);d.gatewayIp=t&&t.groups?t.groups.ip:"",d.gatewayPort=t&&t.groups?t.groups.port:""}else if(a){const e=s.match(/h=(\d{1,3}-){3}\d{1,3}/g),t=s.match(/p=[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("=")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split("=")[1]:""}else{const e=s.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),t=s.match(/(:|p=)[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("//")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split(/:|p=/g)[1]:""}if(o)this.send({type:MD.JOIN_GATEWAY,data:d},!0);else{let e={isSuccess:l,port:d.gatewayPort};delete d.success,delete d.eventType,delete d.firstSuccess,delete d.gatewayPort,d.vid=Number(d.vid);const t=Object.assign({},d,e,{eventType:kD.REJOIN_GATEWAY});this.send({type:MD.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=gD(gD({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:MD.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=gD(gD({},n),{},{eventType:kD.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:MD.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=gD(gD({},r),{},{eventType:kD.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:MD.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...fD(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=gD(gD({},o),{},{eventType:kD.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:MD.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=t.peerPubStatusMs-(i.lastJoinSuccessTime||r),s=gD(gD({},n),{},{elapse:r-i.startTime,eventType:kD.XLA_PEER_FIRST_VIDEO_FRAME,lts:r,peer:t.peer,width:t.width,height:t.height,ssrc:t.ssrc,p2pid:t.p2pid,peerPublishDuration:t.peerPublishDuration,joinChannelSuccessElapse:o,peerPubStatusMs:t.peerPubStatusMs-t.joinChannelStart,availablePublish:t.peerPublishDuration>o?1:0,preloadStart:Math.max(t.preloadStart-t.joinChannelStart,0),preloadEnd:Math.max(t.preloadEnd-t.joinChannelStart,0),encrypt:Math.max(t.apStart-t.joinChannelStart,0),ap:Math.max(t.apEnd-t.joinChannelStart,0),sua:Math.max(t.suaEnd-t.joinChannelStart,0),beforeConnect:Math.max(t.beforeConnect-t.joinChannelStart,0),peerRecevier:Math.max(t.peerReceiver-t.joinChannelStart,0),ice:Math.max(t.ice-t.joinChannelStart,0),pc:Math.max(t.pc-t.joinChannelStart,0),signalConnected:Math.max(t.signalConnected-t.joinChannelStart,0),joinReq:Math.max(t.joinReq-t.joinChannelStart,0),joinRes:Math.max(t.joinRes-t.joinChannelStart,0),userJoinNotify:Math.max(t.userJoinNotify-t.joinChannelStart,0),videoSsrcNotify:Math.max(t.videoAddNotify-t.joinChannelStart,0),subscribeDelayMs:Math.max(t.subscribeStart-t.videoAddNotify,0),subscribeStart:Math.max(t.subscribeStart-t.joinChannelStart,0),subscribeEnd:Math.max(t.subscribeEnd-t.joinChannelStart,0),firstReceived:Math.max(t.firstReceived-t.joinChannelStart,0),firstDecoded:Math.max(t.firstDecoded-t.joinChannelStart,0),firstPreRender:Math.max(t.firstPreRender-t.joinChannelStart,0),firstRender:Math.max(t.firstRender-t.joinChannelStart,0),playDelayMs:Math.max(t.playStart-t.subscribeEnd,0),playStart:Math.max(t.playStart-t.joinChannelStart,0),playEnd:Math.max(t.playEnd-t.joinChannelStart,0),isPreSub:t.isPreSub?1:0,isPrePc:t.isPrePc?1:0,isPreInstantVideo:t.isPreInstantVideo?1:0,firstReceivedEncodedFrame:t.firstReceivedEncodedFrame?Math.max(t.firstReceivedEncodedFrame-t.joinChannelStart,0):void 0,frameType:t.frameType||"",rtpTimestamp:t.rtpTimestamp||0,framePayloadType:t.framePayloadType||0,frameDataLength:t.frameDataLength||0,mimeType:t.mimeType||""});this.send({type:MD.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=gD(gD(gD({},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=gD(gD(gD({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:i,data:a},!0)}abTest(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=gD(gD(gD({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:kD.AB_TEST,lts:r});this.send({type:MD.AB_TEST,data:o},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=gD(gD(gD({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:kD.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:MD.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=gD(gD(gD({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:kD.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:MD.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=gD(gD(gD({},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=gD(gD({},n),{},{eventType:kD.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:MD.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=gD(gD({},n),{},{eventType:kD.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:MD.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=gD(gD({},n),{},{eventType:kD.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:MD.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?ND.debug("reportProxyServerurl: ".concat(e)):ND.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=gD(gD({},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:MD.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=GO(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(s[s.length]=xw(xw({},e),{},{[t]:n.substring(o,c)}),o=c,a=n.charCodeAt(c)<=127?1:3);return o!==n.length-1&&(s[s.length]=xw(xw({},e),{},{[t]:n.substring(o)})),s})(gD(gD(gD({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach((e=>this.send({type:MD.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=gD(gD(gD({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:MD.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=gD(gD(gD({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:MD.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=gD(gD(gD({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:MD.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>JN("CUSTOM_REPORT_LIMIT"))throw new jw(Bw.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:MD.USER_ANALYTICS,data:gD(gD({sid:e},t),{},{lts:i})})));try{JN("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw ND.error("send custom report message failed",e.toString()),new jw(Bw.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=JN("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 jw){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:MD.API_INVOKE,data:a},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){const e=this.apiInvokeUploadPendingItems;if(0===e.length)return;const t=Array.from(this.sids).find((e=>null!==e));t&&e.forEach((e=>{e&&(e.sid=t,this.sendApiInvoke(Object.assign({},e)))})),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>JN("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),qp(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),JN("ENABLE_EVENT_REPORT")?(i.length&&(JN("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{JN("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>JN("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-JN("NORMAL_EVENT_QUEUE_CAPACITY")),ND.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){IO.networkState===gO.OFFLINE&&await Wh.race([IO.onlineWaiter,KO(2*cN.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=tO(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(MD).forEach((i=>{let[n,r]=i;r===e.type&&(t=UD[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=iO(t,new Uint8Array(n)),t=iO(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(JN("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(JN("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(JN("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(JN("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await EN(n,{timeout:1e4,data:t(e),headers:gD(gD({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=(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),n=i?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:i,aid:n};IO.networkState===gO.OFFLINE&&await Wh.race([IO.onlineWaiter,KO(2*cN.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(JN("EVENT_REPORT_DOMAIN"),"&p=").concat(JN("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(JN("EVENT_REPORT_DOMAIN"),":").concat(JN("STATS_COLLECTOR_PORT")).concat(o));for(let e=0;e<2;e+=1){1===e&&(s=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(JN("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(JN("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(JN("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(JN("STATS_COLLECTOR_PORT")).concat(o)));try{t?await mN(s,{timeout:1e4,data:r}):await EN(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},LD);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:cO.TRACER}).onSuccess()}};vD.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=IO.networkState,xD.reportApiInvoke(null,{name:"logUploadError",options:e,tag:cO.TRACER}).onSuccess("logUploadError")}));let FD=class extends jw{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),RD(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,ND)}throw(){super.throw(ND)}};const BD={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,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function jD(){return BD}function GD(){let e=0;const t=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?e[0].split("/")[1]:null}();return t&&(e=parseInt(t)),mw(87)||function(){const e=sw();if(e.name!==iw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}()||Tw(117)||Dw()&&(Cw(15,4,!1)||e>87)}function WD(){return"setSinkId"in HTMLAudioElement.prototype&&(!JN("RESTRICTION_SET_PLAYBACK_DEVICE")||(uw()||pw())&&!Lw())}function HD(){return!BD.supportUnifiedPlan||JN("CHROME_FORCE_PLAN_B")&&kw()}function KD(e){return!(_w()||fw(87)||HD()||!JN("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||JN("FORCE_DISABLE_AUTO_SUB")))}function YD(e){return JN("ENABLE_INSTANT_VIDEO")?JN("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||JN("FORCE_DISABLE_AUTO_SUB"))}function zD(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function qD(){if(zD()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return mw(141)||gw(141)||Iw(141)}function XD(){if(zD()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return mw(141)||gw(141)||Iw(125)}let JD=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 QD(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function ZD(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function $D(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function eP(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const tP={"90p":ZD(160,90),"90p_1":ZD(160,90),"120p":ZD(160,120,15,30,65),"120p_1":ZD(160,120,15,30,65),"120p_3":ZD(120,120,15,30,50),"120p_4":ZD(212,120),"180p":ZD(320,180,15,30,140),"180p_1":ZD(320,180,15,30,140),"180p_3":ZD(180,180,15,30,100),"180p_4":ZD(240,180,15,30,120),"240p":ZD(320,240,15,40,200),"240p_1":ZD(320,240,15,40,200),"240p_3":ZD(240,240,15,40,140),"240p_4":ZD(424,240,15,40,220),"360p":ZD(640,360,15,80,400),"360p_1":ZD(640,360,15,80,400),"360p_3":ZD(360,360,15,80,260),"360p_4":ZD(640,360,30,80,600),"360p_6":ZD(360,360,30,80,400),"360p_7":ZD(480,360,15,80,320),"360p_8":ZD(480,360,30,80,490),"360p_9":ZD(640,360,15,80,800),"360p_10":ZD(640,360,24,80,800),"360p_11":ZD(640,360,24,80,1e3),"480p":ZD(640,480,15,100,500),"480p_1":ZD(640,480,15,100,500),"480p_2":ZD(640,480,30,100,1e3),"480p_3":ZD(480,480,15,100,400),"480p_4":ZD(640,480,30,100,750),"480p_6":ZD(480,480,30,100,600),"480p_8":ZD(848,480,15,100,610),"480p_9":ZD(848,480,30,100,930),"480p_10":ZD(640,480,10,100,400),"720p":ZD(1280,720,15,120,1130),"720p_auto":ZD(1280,720,30,900,3e3),"720p_1":ZD(1280,720,15,120,1130),"720p_2":ZD(1280,720,30,120,2e3),"720p_3":ZD(1280,720,30,120,1710),"720p_5":ZD(960,720,15,120,910),"720p_6":ZD(960,720,30,120,1380),"1080p":ZD(1920,1080,15,120,2080),"1080p_1":ZD(1920,1080,15,120,2080),"1080p_2":ZD(1920,1080,30,120,3e3),"1080p_3":ZD(1920,1080,30,120,3150),"1080p_5":ZD(1920,1080,60,120,4780),"1440p":ZD(2560,1440,30,120,4850),"1440p_1":ZD(2560,1440,30,120,4850),"1440p_2":ZD(2560,1440,60,120,7350),"4k":ZD(3840,2160,30,120,8910),"4k_1":ZD(3840,2160,30,120,8910),"4k_3":ZD(3840,2160,60,120,13500)},iP={"480p":$D(640,480,5),"480p_1":$D(640,480,5),"480p_2":$D(640,480,30),"480p_3":$D(640,480,15),"720p":$D(1280,720,5),"720p_auto":ZD(1280,720,30,900,3e3),"720p_1":$D(1280,720,5),"720p_2":$D(1280,720,30),"720p_3":$D(1280,720,15),"1080p":$D(1920,1080,5),"1080p_1":$D(1920,1080,5),"1080p_2":$D(1920,1080,30),"1080p_3":$D(1920,1080,15)},nP={"1SL1TL":eP(1,1),"3SL3TL":eP(3,3),"2SL3TL":eP(2,3)};function rP(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},tP[e]):e}function oP(e){return"string"==typeof e?Object.assign({},iP[e]):e}function sP(e){return"string"==typeof e?Object.assign({},nP[e]):e}const aP={speech_low_quality:QD(16e3,!1),speech_standard:QD(32e3,!1,18),music_standard:QD(48e3,!1),standard_stereo:QD(48e3,!0,56),high_quality:QD(48e3,!1,128),high_quality_stereo:QD(48e3,!0,192)};function cP(e){return"string"==typeof e?Object.assign({},aP[e]):e}const dP=[];function lP(e){return Ww(e,"mediaSource",["screen","window","application"]),!0}let uP=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}({}),hP=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});let pP=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),_P=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),EP=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),mP=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}({}),fP=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}({}),SP=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.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),gP=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),TP=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 RP={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},vP={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},yP={uplinkNetworkQuality:0,downlinkNetworkQuality:0},IP={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 AP=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),bP=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),wP=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),OP=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),NP=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}({}),DP=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 PP={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 LP=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function kP(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 MP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?kP(Object(i),!0).forEach((function(t){UP(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):kP(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function UP(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===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:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function VP(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=Xn(o=cr(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}class xP extends rO{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(mP.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),UP(this,"trackMediaType",void 0),UP(this,"_ID",void 0),UP(this,"_rtpTransceiver",void 0),UP(this,"_lowRtpTransceiver",void 0),UP(this,"_hints",[]),UP(this,"_isClosed",!1),UP(this,"_originMediaStreamTrack",void 0),UP(this,"mediaStreamTrack",void 0),UP(this,"_external",{}),this._ID=t||YO(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){Dn(dP).call(dP,e)||dP.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||VO((()=>{var e;xD.reportApiInvoke(null,{name:aO.GET_MEDIA_STREAM_TRACK,options:[],tag:cO.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===pP.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=dP.indexOf(e);-1!==t&&dP.splice(t,1)}(this),this.emit(fP.CLOSED),this.removeAllListeners(mP.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===pP.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(mP.TRANSCEIVER_UPDATED,e,t)}}class FP extends xP{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),UP(this,"_enabled",!0),UP(this,"_muted",!1),UP(this,"_isExternalTrack",!1),UP(this,"_isClosed",!1),UP(this,"_enabledMutex",void 0),UP(this,"processor",void 0),UP(this,"_processorContext",void 0),UP(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new sN("".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,ND.debug("[".concat(this.getTrackId(),"] close")),this.emit(uP.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 CO(this,uP.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){ND.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(fP.TRACK_ENDED)}stateCheck(e,t){if(ND.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Gw(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new jw(Bw.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",ND);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new jw(Bw.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",ND)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Wh.resolve([])}}const BP=window.AudioContext||window.webkitAudioContext;let jP,GP=null;const WP=new class extends rO{constructor(){super(...arguments),UP(this,"prevState",void 0),UP(this,"curState",void 0),UP(this,"currentTime",void 0),UP(this,"currentTimeStuckAt",void 0),UP(this,"interruptDetectorTrack",void 0),UP(this,"onLocalAudioTrackMute",(()=>{ND.info("ios15-interruption-start"),this.emit(JD.IOS_15_16_INTERRUPTION_START)})),UP(this,"onLocalAudioTrackUnmute",(async()=>{ND.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?ND.info("ios15-interruption-end-canceled"):(GP&&await GP.suspend(),this.emit(JD.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){ND.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){ND.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 HP(){if(!GP){if(function(){if(!BP)return void ND.error("your browser is not support web audio");ND.info("create audio context");const e=MP({},JN("WEBAUDIO_INIT_OPTIONS"));ND.debug("audio context init option:",JSON.stringify(e)),GP=new BP(e),WP.curState=GP.state,GP.onstatechange=()=>{WP.prevState=WP.curState,WP.curState=GP?GP.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=sw().osVersion;(Ew()||Nw())&&r&&n&&(ND.info("ios".concat(a,"-interruption-start")),WP.emit(JD.IOS_INTERRUPTION_START)),(Ew()||Nw())&&(o||s)&&i&&(ND.info("ios".concat(a,"-interruption-end")),WP.emit(JD.IOS_INTERRUPTION_END)),e!==t&&WP.emit(JD.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=GP)||void 0===e?void 0:e.currentTime;WP.currentTime!==t?(WP.currentTimeStuckAt&&(ND.debug("AudioContext current time resume at ".concat(t)),WP.currentTimeStuckAt=void 0),WP.currentTime=t):(t!==WP.currentTimeStuckAt&&(xD.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:cO.TRACER}).onSuccess(),ND.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,r=!1,o=!1,s=!1;function a(t){"running"===e.state?c(!1):Ew()||Nw()?"suspended"===e.state&&(c(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(c(!0),t&&e.resume().then(d,d))}function c(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function d(){a(!1)}function l(){a(!0)}function u(){let e;try{e=i.play(),e?e.then(_,_):(i.addEventListener("playing",_),i.addEventListener("abort",_),i.addEventListener("error",_))}catch(e){_()}}function h(e){s||(i.paused?e?(p(!1),s=!0,u()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,E,{capture:!0,passive:!0}):window.removeEventListener(t,E,{capture:!0,passive:!0})}}}function _(){i.removeEventListener("playing",_),i.removeEventListener("abort",_),i.removeEventListener("error",_),s=!1,h(!1)}function E(){h(!0)}if(Ew()&&JN("IOS_BG_TAG")){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=r.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,n=()=>{if(JN("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!s&&(!i.paused||!0!==o)){i.paused||i.pause();try{s=!0,u()}catch(e){s=!1}return!0}},h(!0)}return WP.on(JD.STATE_CHANGE,(function(){a(!0)})),a(!1),n}(GP).then((e=>{jP=e}))}(),!GP)throw new jw(Bw.NOT_SUPPORTED,"can not create audio context");return GP}return GP}function KP(e){if(function(){if(null!==YP)return YP;const e=HP(),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(),YP=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?DO(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let YP=null;function zP(e,t){let i=!1;const n=1/t;if(JN("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=HP();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 qP{constructor(){UP(this,"context",void 0),UP(this,"analyserNode",void 0),UP(this,"sourceNode",void 0),this.context=HP(),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||Ew()||Nw()||"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;i<e.length;++i)e[i]=t[i]/128-1}const t=Xn(e).call(e,((e,t)=>e+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){ND.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class XP extends rO{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(),UP(this,"outputNode",void 0),UP(this,"outputTrack",void 0),UP(this,"isPlayed",!1),UP(this,"sourceNode",void 0),UP(this,"context",void 0),UP(this,"audioBufferNode",void 0),UP(this,"destNode",void 0),UP(this,"audioOutputLevel",0),UP(this,"volumeLevelAnalyser",void 0),UP(this,"_processedNode",void 0),UP(this,"playNode",void 0),UP(this,"isDestroyed",!1),UP(this,"onNoAudioInput",void 0),UP(this,"isNoAudioInput",!1),UP(this,"_noAudioInputCount",0),this.context=HP(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),KP(this.outputNode),this.volumeLevelAnalyser=new qP}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(TP.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!jD().webAudioMediaStreamDest)throw new jw(Bw.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&LO((()=>{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;Ew()||Nw()?"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<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await KO(200),await this.checkHasAudioInput(e?e+1:1)&&n)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}}class JP extends XP{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),UP(this,"sourceNode",void 0),UP(this,"track",void 0),UP(this,"clonedTrack",void 0),UP(this,"audioElement",void 0),UP(this,"isCurrentTrackCloned",!1),UP(this,"isRemoteTrack",!1),UP(this,"originVolumeLevelAnalyser",void 0),UP(this,"rebuildWebAudio",(async()=>{if(ND.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 ND.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>ND.info("resume success"))),ND.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),KP(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),KP(this.outputNode),this.emit(TP.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new jw(Bw.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),KP(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,ND.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]));KP(t),this.originVolumeLevelAnalyser=new qP,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=sw();t&&o.os===tw.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(WP.on(JD.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),KP(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(TP.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),ND.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]));KP(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function QP(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 ZP(e,t){const i=await $P(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Wh(((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;
5 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='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await QP(n,e,r)}
vendor: 50,634 bytes, line 5
5async function $P(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=sO();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new jw(Bw.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 Wh(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new jw(Bw.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const eL=new sN("safari");let tL=!1,iL=!1;async function nL(e,t){let i=0,n=null;for(;i<2;)try{n=await rL(e,t,i>0);break}catch(e){if(e instanceof jw)throw ND.error("[".concat(t,"] ").concat(e.toString())),e;const n=oL(e.name||e.code||e,e.message);if(n.code===Bw.MEDIA_OPTION_INVALID){ND.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await KO(500);continue}throw ND.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new jw(Bw.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function rL(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new jw(Bw.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=jD(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return ND.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(sO())e.screen.sourceId?sL(r,await QP(e.screen.sourceId,e.screen,!!e.screenAudio)):sL(r,await ZP(e.screen,!!e.screenAudio));else if(uw()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new jw(Bw.NOT_SUPPORTED,"This browser does not support screen sharing");ND.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(s=e.screen.extensionId,a=t,new Wh(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(i=>{if(!i||!i.streamId)return ND.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new jw(Bw.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){ND.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new jw(Bw.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,sL(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&lP(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,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l}=e.screen,u={selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l};!n&&delete u.selfBrowserSurface,!s&&delete u.surfaceSwitching,!a&&delete u.systemAudio,!c&&delete u.preferCurrentTab,!d&&delete u.windowAudio,!l&&delete u.monitorTypeSurfaces,ND.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:e.screenAudio,controls:u})),sL(r,await navigator.mediaDevices.getDisplayMedia(MP({video:i,audio:e.screenAudio},u)))}else{if(!_w())throw ND.error("[".concat(t,"] This browser does not support screenSharing")),new jw(Bw.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&lP(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};ND.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),sL(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=JN("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=ZO(c,d)}catch(e){}ND.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),sw();let l,u=null;(hw()||Ew()||lw())&&(u=await eL.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(tL=!0),c.video&&(iL=!0),sL(r,l),u&&u(),r}function oL(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new jw(Bw.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new jw(Bw.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new jw(Bw.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new jw(Bw.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new jw(Bw.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new jw(Bw.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return ND.error("getUserMedia unexpected error",e),new jw(Bw.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function sL(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 aL=new class extends rO{get state(){return this._state}set state(e){e!==this._state&&(this.emit(OP.STATE_CHANGE,e),this._state=e)}constructor(){super(),UP(this,"_state",wP.IDLE),UP(this,"isAccessMicrophonePermission",!1),UP(this,"isAccessCameraPermission",!1),UP(this,"lastAccessMicrophonePermission",!1),UP(this,"lastAccessCameraPermission",!1),UP(this,"checkdeviceMatched",!1),UP(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(JN("ENUMERATE_DEVICES_INTERVAL")||(Mw()||cw()===tw.HARMONY_OS)&&kw())&&this.updateDevicesInfo()}),JN("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>ND.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new jw(Bw.NOT_SUPPORTED,"enumerateDevices() not supported.");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(eL.isLocked&&(ND.debug("[device manager] wait GUM lock"),(await eL.lock())(),ND.debug("[device manager] GUM unlock")),tL&&(o=!1,this.isAccessMicrophonePermission=!0),iL&&(s=!1,this.isAccessCameraPermission=!0),ND.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=oL(e.name||e.code||e,e.message);if(t.code===Bw.PERMISSION_DENIED)throw t;ND.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=oL(e.name||e.code||e,e.message);if(t.code===Bw.PERMISSION_DENIED)throw t;ND.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=oL(e.name||e.code||e,e.message);if(t.code===Bw.PERMISSION_DENIED)throw t;ND.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}ND.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 jw(Bw.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 jw(Bw.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=wP.INITING;try{await this.updateDevicesInfo(),this.state=wP.INITEND}catch(e){if(this.state=wP.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname))throw new jw(Bw.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw ND.warning("Device Detection functionality cannot start properly.",e.toString()),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?ND.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):ND.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):ND.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!==wP.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(OP.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(OP.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(OP.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 cL=!1;const dL=new class extends rO{constructor(){super(...arguments),UP(this,"onAutoplayFailed",void 0),UP(this,"onAudioAutoplayFailed",void 0)}};function lL(){if(cL)return JN("FLS_AUTOPLAY_EMITS")?(dL.onAutoplayFailed&&dL.onAutoplayFailed(),dL.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),cL=!1,Uw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};cL=!0,Uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),ND.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),dL.onAutoplayFailed?dL.onAutoplayFailed():dL.onAudioAutoplayFailed?ND.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 ."):ND.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 ."),dL.emit("autoplay-failed")}}function uL(e,t,i,n){if(!e)return;const r=xD.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=MP(MP({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:dL.onAutoplayFailed||dL.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});xD.send({type:MD.AUTOPLAY_FAILED,data:a},!0)}const hL=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],pL=new class{constructor(){UP(this,"onAutoplayFailed",void 0),UP(this,"elementMap",new Map),UP(this,"elementStateMap",new Map),UP(this,"elementsNeedToResume",[]),UP(this,"sinkIdMap",new Map),UP(this,"autoResumeAfterInterruption",(e=>Wh.all(Array.from(this.elementMap.entries()).map((async t=>{let[i,n]=t;const r=this.elementStateMap.get(i),o=n.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(ND.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(e)),"live"===s){if(e)return n.pause(),n.play();if("running"===WP.curState)return bw()?(n.pause(),n.play()):r&&"paused"===r?n.play():void 0}}))))),UP(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(ND.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),WP.on(JD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),WP.on(JD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),WP.on(JD.STATE_CHANGE,(()=>{Ew()&&"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 jw(Bw.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,NP.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{ND.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){ND.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{n&&uL(n,"audio",e.message,t),ND.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(ND.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),LO((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),lL()})))}))}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)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}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){hL.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(ND.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&ND.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=>{ND.debug("Auto resume audio element success")})).catch((e=>{ND.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new Wh((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{Uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function _L(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new jw(Bw.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",ND);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof Wh?new Wh(((e,t)=>{r.then(e).catch(t)})):r}),i}}class EL extends rO{constructor(e){super(),UP(this,"name","VideoProcessorDestination"),UP(this,"ID","0"),UP(this,"_source",void 0),UP(this,"videoContext",void 0),UP(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new jw(Bw.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new jw(Bw.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(AP.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(AP.ON_TRACK,void 0)}}class mL extends rO{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),UP(this,"constraintsMap",new Map),UP(this,"statsRegistry",[]),UP(this,"usageRegistry",[]),UP(this,"trackId",void 0),UP(this,"direction",void 0),UP(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await RO(this,bP.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return ND.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),CO(this,bP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return ND.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),CO(this,bP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(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){ND.error(new jw(Bw.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 Wh&&(i=await i),e.push(MP(MP({},i),{},{direction:this.direction}))}catch(e){ND.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class fL extends rO{constructor(e){super(),UP(this,"name","AudioProcessorDestination"),UP(this,"ID","0"),UP(this,"inputTrack",void 0),UP(this,"inputNode",void 0),UP(this,"audioProcessorContext",void 0),UP(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new jw(Bw.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new jw(Bw.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(AP.ON_TRACK,void 0),this.emit(AP.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(AP.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(AP.ON_NODE,this.inputNode))}}class SL extends rO{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),UP(this,"constraintsMap",new Map),UP(this,"statsRegistry",[]),UP(this,"audioContext",void 0),UP(this,"trackId",void 0),UP(this,"direction",void 0),UP(this,"usageRegistry",[]),UP(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return RO(this,bP.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return ND.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),CO(this,bP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),CO(this,bP.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(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){ND.error(new jw(Bw.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 Wh&&(i=await i),e.push(MP(MP({},i),{},{direction:this.direction}))}catch(e){ND.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class gL extends rO{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),UP(this,"context",void 0),UP(this,"processSourceNode",void 0),UP(this,"outputTrack",void 0),UP(this,"processedNode",void 0),UP(this,"clonedTrack",void 0),UP(this,"outputNode",void 0),this.outputNode=new TL}setVolume(){}createOutputTrack(){throw new jw(Bw.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 TL{disconnect(){}connect(){}}function RL(e){return new Wh(((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=Ew()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&_w()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(qO),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function CL(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=rP(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Pw()&&i.frameRate&&(t.frameRate=i.frameRate),pw()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),_w()&&(t.frameRate={ideal:30,max:30}),t}function vL(e){const t={};return Pw()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,uw()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function yL(e){const t=vL(e);if(e.encoderConfig){const i=cP(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Mw()&&(t.sampleRate=void 0),t}const IL=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=eN(s),a=eN(a),o=eN(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||ND.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(u,"]"));const{maxFramerate:h}=JN("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}},AL=async(e,t,i)=>await(async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return Uint8Array.from(t)}(nN(""+t+i)).slice(0,16),r=n.slice(0,12),o=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},o,e))})(e.buffer,t,i),bL=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Wh(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await wL(e);i({buffer:n,width:t.width,height:t.height})}else n(new jw(Bw.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},wL=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var OL,NL,DL,PL,LL,kL,ML,UL,VL,xL,FL,BL,jL,GL,WL,HL,KL,YL,zL,qL,XL,JL,QL,ZL,$L,ek,tk,ik,nk,rk,ok,sk,ak,ck,dk,lk,uk,hk,pk,_k;let Ek=(OL=VD({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),NL=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),DL=_L(),PL=aN("LocalAudioTrack","_enabledMutex"),LL=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),kL=_L(),ML=aN("LocalAudioTrack","_enabledMutex"),UL=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),VL=_L(),xL=_L(),FL=_L(),BL=VD({argsMap:e=>[e.getTrackId()]}),jL=_L(),GL=VD({argsMap:e=>[e.getTrackId()]}),WL=_L(),HL=VD({argsMap:e=>[e.getTrackId()]}),KL=VD({argsMap:(e,t)=>[e.getTrackId(),t.name]}),YL=VD({argsMap:e=>[e.getTrackId()]}),VP((zL=class extends FP{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?pL.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n){super(e,i),UP(this,"trackMediaType",gP.AUDIO),UP(this,"_encoderConfig",void 0),UP(this,"_trackSource",void 0),UP(this,"metadata",[]),UP(this,"pts",[]),UP(this,"_enabled",!0),UP(this,"_volume",100),UP(this,"_useAudioElement",!0),UP(this,"_bypassWebAudio",!1),UP(this,"processor",void 0),UP(this,"_processorContext",void 0),UP(this,"_processorDestination",void 0),UP(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new gL,JN("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),JN("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),hw()&&!GP?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){Hw(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&pL.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void ND.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,CO(this,uP.NEED_REPLACE_TRACK,this).then((()=>{ND.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{ND.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||!WD())throw new jw(Bw.NOT_SUPPORTED,"your browser does not support setting the audio output device");await pL.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(ND.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await CO(this,uP.NEED_ENABLE_TRACK,this),ND.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),ND.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await CO(this,uP.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),ND.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,ND.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await CO(this,uP.NEED_MUTE_TRACK,this):await CO(this,uP.NEED_UNMUTE_TRACK,this))}getStats(){VO((()=>{ND.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return vO(this,uP.GET_STATS)||MP({},RP)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(TP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(TP.ON_AUDIO_BUFFER),this._source.on(TP.ON_AUDIO_BUFFER,(t=>e(t)))}play(){ND.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(ND.debug("[".concat(this.getTrackId(),"] start audio playback in element")),pL.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){ND.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?pL.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];ND.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&pL.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 CO(this,uP.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Wh.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new jw(Bw.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new jw(Bw.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(AP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await CO(this,uP.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await CO(this,uP.NEED_REPLACE_TRACK,this))})),e.on(AP.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(AP.ON_TRACK),e.removeAllListeners(AP.ON_NODE)}bindProcessorContextEvents(e){e.on(bP.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(bP.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof gL&&(this._trackSource=new JP(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new SL(this._source.context,this.getTrackId(),"local"),t=new fL(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(TP.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(pL.stop(this.getTrackId()),this._source.play()),CO(this,uP.NEED_REPLACE_MIXING_TRACK,this).then((()=>{ND.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{ND.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[OL],Object.getOwnPropertyDescriptor(zL.prototype,"setVolume"),zL.prototype),VP(zL.prototype,"setPlaybackDevice",[NL,DL],Object.getOwnPropertyDescriptor(zL.prototype,"setPlaybackDevice"),zL.prototype),VP(zL.prototype,"setEnabled",[PL,LL,kL],Object.getOwnPropertyDescriptor(zL.prototype,"setEnabled"),zL.prototype),VP(zL.prototype,"setMuted",[ML,UL,VL],Object.getOwnPropertyDescriptor(zL.prototype,"setMuted"),zL.prototype),VP(zL.prototype,"getStats",[xL],Object.getOwnPropertyDescriptor(zL.prototype,"getStats"),zL.prototype),VP(zL.prototype,"setAudioFrameCallback",[FL],Object.getOwnPropertyDescriptor(zL.prototype,"setAudioFrameCallback"),zL.prototype),VP(zL.prototype,"play",[BL,jL],Object.getOwnPropertyDescriptor(zL.prototype,"play"),zL.prototype),VP(zL.prototype,"stop",[GL,WL],Object.getOwnPropertyDescriptor(zL.prototype,"stop"),zL.prototype),VP(zL.prototype,"close",[HL],Object.getOwnPropertyDescriptor(zL.prototype,"close"),zL.prototype),VP(zL.prototype,"pipe",[KL],Object.getOwnPropertyDescriptor(zL.prototype,"pipe"),zL.prototype),VP(zL.prototype,"unpipe",[YL],Object.getOwnPropertyDescriptor(zL.prototype,"unpipe"),zL.prototype),zL),mk=(qL=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),XL=_L(),JL=aN("MicrophoneAudioTrack","_enabledMutex"),QL=VD({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),ZL=_L(),$L=VD({argsMap:e=>[e.getTrackId()]}),VP((ek=class extends Ek{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?cP(t.encoderConfig):{},n,JN("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),UP(this,"_config",void 0),UP(this,"_deviceName","default"),UP(this,"_constraints",void 0),UP(this,"_originalConstraints",void 0),UP(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(bw()||ww())&&WP.bindInterruptDetectorTrack(this)}async setDevice(e){if(ND.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await aL.getDeviceById(e),i={};i.audio=MP({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await nL(i,this.getTrackId())}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await nL({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 ND.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await aL.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}ND.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return ND.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(ND.info("[".concat(this.getTrackId(),"] start setEnabled"),e),JN("AUTO_RESET_AUDIO_ROUTE")&&(Ew()||Nw())){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 CO(this,uP.NEED_DISABLE_TRACK,this)}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=MP({},this._constraints),o=aL.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await nL({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await CO(this,uP.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),ND.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}ND.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(bw()||ww())&&WP.unbindInterruptDetectorTrack(this),dP.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))||jP&&jP()&&(xD.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:cO.TRACER}).onSuccess(),ND.debug("restart background audio tag success"))}onTrackEnded(){if((Ew()||Nw())&&this._enabled&&!this._isClosed&&WP.duringInterruption){const e=async()=>{WP.off(JD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(ND.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};WP.on(JD.IOS_INTERRUPTION_END,e)}else ND.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(fP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=aL.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await nL({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(bP.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(bP.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[qL,XL],Object.getOwnPropertyDescriptor(ek.prototype,"setDevice"),ek.prototype),VP(ek.prototype,"setEnabled",[JL,QL,ZL],Object.getOwnPropertyDescriptor(ek.prototype,"setEnabled"),ek.prototype),VP(ek.prototype,"close",[$L],Object.getOwnPropertyDescriptor(ek.prototype,"close"),ek.prototype),ek),fk=(tk=VD({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),ik=_L(),nk=VD({argsMap:e=>[e.getTrackId()]}),rk=_L(),ok=VD({argsMap:e=>[e.getTrackId()]}),sk=_L(),ak=VD({argsMap:e=>[e.getTrackId()]}),ck=_L(),dk=VD({argsMap:e=>[e.getTrackId()]}),lk=_L(),uk=VD({argsMap:e=>[e.getTrackId()]}),hk=VD({argsMap:e=>[e.getTrackId()]}),pk=_L(),VP((_k=class extends Ek{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),UP(this,"source",void 0),UP(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(TP.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(fP.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){Hw(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[tk,ik],Object.getOwnPropertyDescriptor(_k.prototype,"startProcessAudioBuffer"),_k.prototype),VP(_k.prototype,"pauseProcessAudioBuffer",[nk,rk],Object.getOwnPropertyDescriptor(_k.prototype,"pauseProcessAudioBuffer"),_k.prototype),VP(_k.prototype,"seekAudioBuffer",[ok,sk],Object.getOwnPropertyDescriptor(_k.prototype,"seekAudioBuffer"),_k.prototype),VP(_k.prototype,"resumeProcessAudioBuffer",[ak,ck],Object.getOwnPropertyDescriptor(_k.prototype,"resumeProcessAudioBuffer"),_k.prototype),VP(_k.prototype,"stopProcessAudioBuffer",[dk,lk],Object.getOwnPropertyDescriptor(_k.prototype,"stopProcessAudioBuffer"),_k.prototype),VP(_k.prototype,"close",[uk],Object.getOwnPropertyDescriptor(_k.prototype,"close"),_k.prototype),VP(_k.prototype,"setAudioBufferPlaybackSpeed",[hk,pk],Object.getOwnPropertyDescriptor(_k.prototype,"setAudioBufferPlaybackSpeed"),_k.prototype),_k);class Sk extends Ek{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=HP().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,YO(8,"track-mix-")),UP(this,"trackList",void 0),UP(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)?(ND.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):ND.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){ND.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}DO(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 Sk?t.emit(mP.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class gk extends XP{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(TP.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(),UP(this,"audioBuffer",void 0),UP(this,"sourceNode",void 0),UP(this,"startPlayTime",0),UP(this,"startPlayOffset",0),UP(this,"pausePlayTime",0),UP(this,"options",void 0),UP(this,"currentLoopCount",0),UP(this,"currentPlaybackSpeed",100),UP(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):ND.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 Tk=new Map;function Rk(e,t){if(0===e.length||0===t.length)return 1/0;const i=iN(e),n=iN(t);return Math.floor(n/i)}class Ck{get rendFrameRate(){const e=Math.max(1,Rk(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:NP.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(ND.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){UP(this,"trackId",void 0),UP(this,"config",void 0),UP(this,"onFirstVideoFrameDecoded",void 0),UP(this,"onFirstVideoFrameRen
5der",void 0),UP(this,"onVideoBufferReady",void 0),UP(this,"onVideoStateChanged",void 0),UP(this,"freezeTimeCounterList",[]),UP(this,"renderFreezeAccTime",0),UP(this,"renderFreezeAccTime2",0),UP(this,"isKeepLastFrame",!1),UP(this,"isDestroyed",!1),UP(this,"timeUpdatedCount",0),UP(this,"freezeTime",0),UP(this,"playbackTime",0),UP(this,"lastTimeUpdatedTime",0),UP(this,"autoplayFailed",!1),UP(this,"videoTrack",void 0),UP(this,"videoElement",void 0),UP(this,"cacheVideoElement",void 0),UP(this,"cancelRVFId",void 0),UP(this,"internal",!1),UP(this,"_render_interframe_delays",[]),UP(this,"_render_interframe_delays_sizes",[]),UP(this,"_videoState",DP.VideoStateStopped),UP(this,"videoElementCheckInterval",void 0),UP(this,"videoElementFreezeTimeout",void 0),UP(this,"_videoElementStatus",NP.NONE),UP(this,"_isInPage",!0),UP(this,"isGettingVideoDimensions",!1),UP(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return ND.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),UP(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===WP.curState&&(ND.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(dw())),Ow()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),UP(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&ND.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=NP.PLAYING;break;case"loadeddata":if(this.videoState=DP.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),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=NP.CANPLAY;break;case"stalled":this.videoElementStatus=NP.STALLED;break;case"suspend":this.videoElementStatus=NP.SUSPEND;break;case"pause":this.videoElementStatus=NP.PAUSED,Ew()||Nw()||hw()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(ND.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=NP.WAITING;break;case"abort":this.videoElementStatus=NP.ABORT;break;case"ended":this.videoElementStatus=NP.ENDED;break;case"emptied":this.videoElementStatus=NP.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=NP.ERROR,ND.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>JN("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,OM.lastVisibleTime<OM.lastHiddenTime||i<OM.lastHiddenTime||i<OM.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())return;for(t>JN("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}}})),UP(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(ND.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(dw())),Ow()?(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(JD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),WP.on(JD.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&&uL(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(ND.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):ND.warning("[".concat(this.trackId,"] play warning: "),t)}));const i=sw();if(("Safari"===i.name&&15===Number(i.version)||bw())&&t&&t.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(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 ND.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 Wh(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await wL(e);n({buffer:t,width:i.width,height:i.height})}else r(new jw(Bw.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await bL(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,WP.off(JD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),WP.off(JD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=DP.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=NP.INIT,!this.videoElementCheckInterval&&(vk.forEac
vendor: 12,876 bytes, line 5
5h((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{this._isInPage=function(e){return e!==document.body&&document.body.contains(e)}(this.videoElement)}),1e3),JN("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,JN("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===DP.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=DP.VideoStateFrozen:document.addEventListener("visibilitychange",n))},o=(e,t)=>{if(this.videoElementStatus===NP.PLAYING){if(i){const e=t.presentationTime-i.presentationTime,n=t.presentedFrames-i.presentedFrames;this._render_interframe_delays_sizes.push(n),this._render_interframe_delays.push(e);const o=iN(this._render_interframe_delays_sizes),s=o-this._render_interframe_delays_sizes[0];if(o>30&&s>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===DP.VideoStateStarting&&(this.videoState=DP.VideoStateDecoding),this.videoState===DP.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,JN("VIDEO_FREEZE_DURATION"))),e<JN("VIDEO_FREEZE_DURATION")&&this.videoState===DP.VideoStateFrozen&&(this.videoState=DP.VideoStateDecoding),e>JN("VIDEO_FREEZE_DURATION")&&OM.lastVisibleTime>=OM.lastHiddenTime&&i.timestamp>OM.lastVisibleTime&&i.timestamp>OM.lastHiddenTime){const t=Math.min(66,Rk(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,e-(n-1)*t);this.renderFreezeAccTime2+=i>t?i:0,this.renderFreezeAccTime+=e}}i=MP(MP({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(i=MP(MP({},t),{},{timestamp:e}));var n,s;JN("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(n=(s=this.videoElement).requestVideoFrameCallback)||void 0===n?void 0:n.call(s,o))};this.cancelRVFId=null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e?void 0:e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Mw()&&!JN("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const i=sw();this.config.noStyle||("Safari"===i.name&&15===Number(i.version)||bw()||!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,_w()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,_w()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{ND.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;vk.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement&&(null===(e=(t=this.videoElement).cancelVideoFrameCallback)||void 0===e||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0),this.videoElementStatus=NP.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===NP.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{ND.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{ND.error(e)})),this.autoplayFailed=!1,Uw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),lL()}}const vk=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class yk extends Ck{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),UP(this,"container",void 0),UP(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var i;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(i=this.slot)||void 0===i||i.appendChild(this.container)):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 bL(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null===(e=this.slot)||void 0===e||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;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",JN("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),null===(e=this.slot)||void 0===e||e.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 Ik,Ak,bk,wk,Ok,Nk,Dk,Pk,Lk,kk,Mk,Uk,Vk,xk,Fk,Bk,jk,Gk,Wk,Hk,Kk,Yk,zk,qk,Xk,Jk,Qk,Zk,$k,eM,tM,iM,nM,rM,oM,sM,aM,cM;let dM=(Ik=VD({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Ak=_L(),bk=VD({argsMap:e=>[e.getTrackId()]}),wk=aN("LocalVideoTrack","_enabledMutex"),Ok=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),Nk=_L(),Dk=aN("LocalVideoTrack","_enabledMutex"),Pk=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),Lk=_L(),kk=VD({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),Mk=_L(),Uk=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),Vk=_L(),xk=_L(),Fk=VD({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Bk=_L(),jk=_L(),Gk=_L(),Wk=VD({argsMap:e=>[e.getTrackId()]}),Hk=_L(),Kk=_L(),Yk=_L(),zk=_L(),qk=_L(),Xk=VD({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Jk=VD({argsMap:e=>[e.getTrackId()]}),Qk=VD({argsMap:e=>[e.getTrackId()]}),Zk=VD({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),$k=class e extends FP{get videoHeight(){if(hw()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(hw()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==NP.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),UP(this,"trackMediaType",gP.VIDEO),UP(this,"_player",void 0),UP(this,"isUseScaleResolutionDownBy",!1),UP(this,"_videoVisibleTimer",null),UP(this,"_previousVideoVisibleStatus",void 0),UP(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),UP(this,"_encoderConfig",void 0),UP(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),UP(this,"_optimizationMode",void 0),UP(this,"_saveEncodeBitrateRatio",1),UP(this,"_videoHeight",void 0),UP(this,"_videoWidth",void 0),UP(this,"_forceBitrateLimit",void 0),UP(this,"_enabled",!0),UP(this,"_processorDestination",void 0),UP(this,"_processorContext",void 0),hw()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=i,this._optimizationMode=n,this._hints=o||[],t&&-1!==this._hints.indexOf(hP.CUSTOM_TRACK)?this._encoderConfig=kO(t):this._encoderConfig=t,-1===this._hints.indexOf(hP.SCREEN_TRACK))this.updateBitrateFromProfile();else if(Sw(iw.CHROME,115)&&-1!==cw().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&jD().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&&(ND.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(hP.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new mL(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:(ND.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}ND.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=MP(MP(MP({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Ck(i):this._player=new yk(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(fP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),JN("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,ND.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(ND.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await CO(this,uP.NEED_DISABLE_TRACK,this)}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setEnabled to fal
5se error"),e.toString()),e}return t||(this._enabled=!1),void ND.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await CO(this,uP.NEED_ENABLE_TRACK,this)}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}ND.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,ND.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await CO(this,uP.NEED_MUTE_TRACK,this):await CO(this,uP.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),ND.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await CO(this,uP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ND)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new jw(Bw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=rP(e),JN("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),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=CL({encoderConfig:e});(hw()||Ew()||Nw())&&(t.deviceId=void 0),ND.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 jw(Bw.UNEXPECTED_ERROR,e.toString());throw ND.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(hP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await CO(this,uP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ND)}}getStats(){VO((()=>{ND.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return vO(this,uP.GET_STATS)||MP({},CP)}async setBeautyEffect(e){ND.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 bL(e)}async findClosestProfile(){const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings(),{width:n,height:r,frameRate:o}=this._encoderConfig||{},s=eN(this._videoWidth||e||n||0),a=eN(this._videoHeight||t||r||0),c=function(e,t,i){if(!Array.isArray(JN("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===JN("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const n=Math.min(e,t);return!(n>=480)&&MP(MP({},JN("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>n))),{},{frameRate:i})}(s,a,eN(i||o||15));if(c)return ND.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(s,"x").concat(a," => ").concat(JSON.stringify(c))),this.setEncoderConfiguration(c)}async setBitrateLimit(e){ND.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<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void ND.error(Bw.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await CO(this,uP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,ND.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}ND.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}
vendor: 13,958 bytes, line 5
5setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return ND.error(Bw.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,ND.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){RL(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(qO)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new jw(Bw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");ND.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=rP(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(hP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await CO(this,uP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ND)}}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=JN("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);if(this._encoderConfig.bitrateMin=s,this._encoderConfig.bitrateMax=o,JN("VIDEO_STANDARD_BITRATE_VERSION")&&null==r&&null==n){const[n,r]=function(e,t,i){const n=4*Math.floor(2e5*Math.pow(i/15,.6)*Math.pow(e*t/230400,.75)),r=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),s=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=Zh(o).call(o).next().value,c=1;if(o.has(r))a=o.get(r);else{var d;const e=qp(d=Array.from(o.entries())).call(d,((e,t)=>{let[i]=e,[n]=t;return i-n})),t=e.find((e=>{let[t]=e;return t>r}));if(t){const i=e.indexOf(t);if(i>0){const n=e[i-1],o=(r-n[0])/(t[0]-n[0]);a=n[1]+o*(t[1]-n[1])}else a=t[1]}else a=e[e.length-1][1]}if(s.has(r))c=s.get(r);else{var l;const e=qp(l=Array.from(s.entries())).call(l,((e,t)=>{let[i]=e,[n]=t;return i-n})),t=e.find((e=>{let[t]=e;return t>r}));if(t){const i=e.indexOf(t);if(i>0){const n=e[i-1],o=(r-n[0])/(t[0]-n[0]);c=n[1]+o*(t[1]-n[1])}else c=t[1]}else c=e[e.length-1][1]}const u=JN("VIDEO_NEW_BITRATE_RATIO");u&&u>0&&(a=u/100);const h=Math.floor(n*a),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(i/15,.69));let _=h;const E=JN("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=n:2===E?_=h:3===E&&(_=p)),[Math.floor(_/1e3),c]}(e,t,i);this._encoderConfig.bitrateMax=n,this._encoderConfig.bitrateMin=s?Math.min(s,n):n,this._saveEncodeBitrateRatio=r,ND.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else ND.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(s,"]")),this._saveEncodeBitrateRatio=1}}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=eO.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=xD.reportApiInvoke(null,{tag:cO.TRACER,name:aO.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 jw(Bw.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new jw(Bw.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=MP(MP({},n),rP(t))),n=MO(n);const r=YO(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,MO(this._scalabilityMode),this._optimizationMode,r,MO(this._hints));return t&&n&&o.setEncoderConfiguration(n),ND.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 jw(Bw.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new jw(Bw.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(VO((()=>{xD.reportApiInvoke(null,{name:aO.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:cO.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!JN("ENABLE_VIDEO_SEI")||!JN("ENABLE_ENCODED_TRANSFORM"))return void ND.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new jw(Bw.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void ND.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||"video/h265"===n?this.safeEmit("sei-to-send",e):ND.warning("SEI is not supported by ".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(AP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await CO(this,uP.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await CO(this,uP.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(AP.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(bP.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(bP.REQUEST_CONSTRAINTS)}},VP($k.prototype,"play",[Ik,Ak],Object.getOwnPropertyDescriptor($k.prototype,"play"),$k.prototype),VP($k.prototype,"stop",[bk],Object.getOwnPropertyDescriptor($k.prototype,"stop"),$k.prototype),VP($k.prototype,"setEnabled",[wk,Ok,Nk],Object.getOwnPropertyDescriptor($k.prototype,"setEnabled"),$k.prototype),VP($k.prototype,"setMuted",[Dk,Pk,Lk],Object.getOwnPropertyDescriptor($k.prototype,"setMuted"),$k.prototype),VP($k.prototype,"setSaveEncodeBitrateRatio",[kk,Mk],Object.getOwnPropertyDescriptor($k.prototype,"setSaveEncodeBitrateRatio"),$k.prototype),VP($k.prototype,"setEncoderConfiguration",[Uk,Vk],Object.getOwnPropertyDescriptor($k.prototype,"setEncoderConfiguration"),$k.prototype),VP($k.prototype,"getStats",[xk],Object.getOwnPropertyDescriptor($k.prototype,"getStats"),$k.prototype),VP($k.prototype,"setBeautyEffect",[Fk,Bk],Object.getOwnPropertyDescriptor($k.prototype,"setBeautyEffect"),$k.prototype),VP($k.prototype,"getCurrentFrameData",[jk],Object.getOwnPropertyDescriptor($k.prototype,"getCurrentFrameData"),$k.prototype),VP($k.prototype,"getCurrentFrameImage",[Gk],Object.getOwnPropertyDescriptor($k.prototype,"getCurrentFrameImage"),$k.prototype),VP($k.prototype,"findClosestProfile",[Wk,Hk],Object.getOwnPropertyDescriptor($k.prototype,"findClosestProfile"),$k.prototype),VP($k.prototype,"setBitrateLimit",[Kk],Object.getOwnPropertyDescriptor($k.prototype,"setBitrateLimit"),$k.prototype),VP($k.prototype,"setOptimizationMode",[Yk],Object.getOwnPropertyDescriptor($k.prototype,"setOptimizationMode"),$k.prototype),VP($k.prototype,"setScalabiltyMode",[zk],Object.getOwnPropertyDescriptor($k.prototype,"setScalabiltyMode"),$k.prototype),VP($k.prototype,"updateMediaStreamTrackResolution",[qk],Object.getOwnPropertyDescriptor($k.prototype,"updateMediaStreamTrackResolution"),$k.prototype),VP($k.prototype,"pipe",[Xk],Object.getOwnPropertyDescriptor($k.prototype,"pipe"),$k.prototype),VP($k.prototype,"unpipe",[Jk],Object.getOwnPropertyDescriptor($k.prototype,"unpipe"),$k.prototype),VP($k.prototype,"close",[Qk],Object.getOwnPropertyDescriptor($k.prototype,"close"),$k.prototype),VP($k.prototype,"replaceTrack",[Zk],Object.getOwnPropertyDescriptor($k.prototype,"replaceTrack"),$k.prototype),$k),lM=(eM=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),tM=_L(),iM=aN("CameraVideoTrack","_enabledMutex"),nM=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),rM=_L(),oM=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),sM=_L(),aM=VD({argsMap:e=>[e.getTrackId()]}),cM=class e extends dM{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,rP(t.encoderConfig),n,r,o),UP(this,"_config",void 0),UP(this,"_originalConstraints",void 0),UP(this,"_constraints",void 0),UP(this,"_enabled",!0),UP(this,"_deviceName","default"),UP(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(bw()||ww())&&!function(){const e=sw();if(e.os!==tw.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&Dw()&&this._enabled&&!this._isClosed&&(ND.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=rP(this._config.encoderConfig),WP.on(JD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),WP.on(JD.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(ND.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await aL.getDeviceById(e),i={};i.video=MP({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await nL(i,this.getTrackId())}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await nL({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 ND.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await aL.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}ND.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){ND.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:MP(MP({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await nL(t,this.getTrackId())}catch(t){throw ND.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await nL({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=MP({},t.video),ND.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(ND.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await nL({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await CO(this,uP.NEED_ENABLE_TRACK,this)}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),ND.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 CO(this,uP.NEED_DISABLE_TRACK,this)}catch(e){throw ND.error("[".concat(this.getTrackId(),"] setEnabled to fal
5se error"),e.toString()),e}ND.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new jw(Bw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=rP(e),JN("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=kO(this._config);i.encoderConfig=e;const n=CL(i);(hw()||Ew()||Nw())&&(n.deviceId=void 0),ND.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 jw(Bw.UNEXPECTED_ERROR,e.toString());throw ND.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(hP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await CO(this,uP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ND)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Ew()||Nw())&&this._enabled&&!this._isClosed&&WP.duringInterruption){const e=async()=>{WP.off(JD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(ND.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};WP.on(JD.IOS_INTERRUPTION_END,e)}else ND.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(fP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=aL.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await nL({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),WP.off(JD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),WP.off(JD.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=MP(MP({},n),rP(t))),n=MO(n);const r=YO(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,MO(MP(MP({},this._config),{},{encoderConfig:n})),MO(this._constraints),MO(this._scalabilityMode),this._optimizationMode,r);return t&&n&&o.setEncoderConfiguration(n),ND.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(bP.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(bP.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},VP(cM.prototype,"setDevice",[eM,tM],Object.getOwnPropertyDescriptor(cM.prototype,"setDevice"),cM.prototype),VP(cM.prototype,"setEnabled",[iM,nM,rM],Object.getOwnPropertyDescriptor(cM.prototype,"setEnabled"),cM.prototype),VP(cM.prototype,"setEncoderConfiguration",[oM,sM],Object.getOwnPropertyDescriptor(cM.prototype,"setEncoderConfiguration"),cM.prototype),VP(cM.prototype,"close",[aM],Object.getOwnPropertyDescriptor(cM.prototype,"close"),cM.prototype),cM);function uM(e){const t=YO(8,"track-cus-"),i=xD.reportApiInvoke(null,{id:t,tag:cO.TRACER,name:aO.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),n=new Ek(e.mediaStreamTrack,e.encoderConfig?cP(e.encoderConfig):{},t,!1);return ND.info("create custom audio track success with config",e,"trackId",n.getTrackId()),i.onSuccess(n.getTrackId()),n}function hM(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=MP(MP({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?ND.debug("[".concat(e,"] set content hint to"),i.optimizationMode):ND.debug("[".concat(e,"] set content hint failed")))):ND.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var pM,_M,EM,mM,fM,SM,gM,TM,RM,CM,vM,yM,IM;class AM extends xP{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(YO(5,""))),UP(this,"_userId",void 0),UP(this,"_uintId",void 0),UP(this,"_isDestroyed",!1),UP(this,"store",void 0),UP(this,"processor",void 0),UP(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,ND.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let bM=(pM=VD({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),_M=VD({argsMap:e=>[e.getTrackId()]}),EM=VD({argsMap:(e,t)=>[e.getTrackId(),t.name]}),mM=VD({argsMap:e=>[e.getTrackId()]}),VP((fM=class extends AM{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==NP.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n,r){super(e,t,i,n),UP(this,"_videoVisibleTimer",null),UP(this,"_previousVideoVisibleStatus",void 0),UP(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),UP(this,"trackMediaType",gP.VIDEO),UP(this,"_videoWidth",void 0),UP(this,"_videoHeight",void 0),UP(this,"_player",void 0),UP(this,"_prePlayer",void 0),UP(this,"processorDestination",void 0),UP(this,"processorContext",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new mL(this.getTrackId(),"remote"),this.processorDestination=new EL(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return VO((()=>{ND.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),vO(this,uP.GET_STATS)||MP({},IP)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(SP.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(ND.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}ND.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=MP(MP({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(i);else{let t=!1,n=!1;e instanceof HTMLVideoElement?(this._player=new Ck(i),this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0,n=!0)):this._prePlayer&&!this._prePlayer.isDestroyed?(this._player=this._prePlayer,this._prePlayer=void 0,t=this._player.videoState>0,this._player.updateConfig(i)):this._player=new yk(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(SP.FIRST_FRAME_DECODED),n&&this.safeEmit(SP.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(SP.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}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(SP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),JN("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(SP.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,ND.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){RL(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(qO)}_updatePlayerSource(){ND.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;
vendor: 12,661 bytes, line 5
5if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=eO.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=xD.reportApiInvoke(null,{tag:cO.TRACER,name:aO.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 jw(Bw.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new jw(Bw.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(AP.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(AP.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(mP.SEI_RECEIVED,e)}}).prototype,"play",[pM],Object.getOwnPropertyDescriptor(fM.prototype,"play"),fM.prototype),VP(fM.prototype,"stop",[_M],Object.getOwnPropertyDescriptor(fM.prototype,"stop"),fM.prototype),VP(fM.prototype,"pipe",[EM],Object.getOwnPropertyDescriptor(fM.prototype,"pipe"),fM.prototype),VP(fM.prototype,"unpipe",[mM],Object.getOwnPropertyDescriptor(fM.prototype,"unpipe"),fM.prototype),fM),wM=(SM=VD({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),gM=VD({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),TM=VD({argsMap:(e,t)=>[e.getTrackId(),t]}),RM=VD({argsMap:e=>[e.getTrackId()]}),CM=VD({argsMap:e=>[e.getTrackId()]}),vM=VD({argsMap:(e,t)=>[e.getTrackId(),t.name]}),yM=VD({argsMap:e=>[e.getTrackId()]}),VP((IM=class extends AM{get isPlaying(){return this._useAudioElement?pL.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),UP(this,"trackMediaType",gP.AUDIO),UP(this,"_source",void 0),UP(this,"_useAudioElement",!0),UP(this,"_volume",100),UP(this,"processorContext",void 0),UP(this,"processorDestination",void 0),UP(this,"_played",!1),UP(this,"_bypassWebAudio",!1),JN("DISABLE_WEBAUDIO")?(this._source=new gL,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new JP(e,!0),JN("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(TP.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(SP.FIRST_FRAME_DECODED)})),this.processorContext=new SL(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new fL(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(TP.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(TP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(TP.ON_AUDIO_BUFFER),this._source.on(TP.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?pL.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(pL.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,JN("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!WD())throw new jw(Bw.NOT_SUPPORTED,"your browser does not support setting the audio output device");await pL.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?pL.getVolume(this.getTrackId()):this._source instanceof JP?this._source.getAudioVolume():0}getStats(){return VO((()=>{ND.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),vO(this,uP.GET_STATS)||MP({},vP)}play(){ND.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(ND.debug("[".concat(this.getTrackId(),"] use audio element to play")),pL.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):(ND.debug("[".concat(this.getTrackId(),"] use audio context to play")),this._source.play())}stop(){ND.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?pL.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];ND.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&pL.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new jw(Bw.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new jw(Bw.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 jw(Bw.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(AP.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(AP.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(AP.ON_TRACK),this.processorDestination.removeAllListeners(AP.ON_NODE)}}).prototype,"setVolume",[SM],Object.getOwnPropertyDescriptor(IM.prototype,"setVolume"),IM.prototype),VP(IM.prototype,"setAmplifiedVolume",[gM],Object.getOwnPropertyDescriptor(IM.prototype,"setAmplifiedVolume"),IM.prototype),VP(IM.prototype,"setPlaybackDevice",[TM],Object.getOwnPropertyDescriptor(IM.prototype,"setPlaybackDevice"),IM.prototype),VP(IM.prototype,"play",[RM],Object.getOwnPropertyDescriptor(IM.prototype,"play"),IM.prototype),VP(IM.prototype,"stop",[CM],Object.getOwnPropertyDescriptor(IM.prototype,"stop"),IM.prototype),VP(IM.prototype,"pipe",[vM],Object.getOwnPropertyDescriptor(IM.prototype,"pipe"),IM.prototype),VP(IM.prototype,"unpipe",[yM],Object.getOwnPropertyDescriptor(IM.prototype,"unpipe"),IM.prototype),IM);const OM=new class extends rO{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),UP(this,"_lastHiddenTime",0),UP(this,"_lastVisibleTime",0),UP(this,"needUploadStats",[]),UP(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push("visible"===document.visibilityState?1:0),ND.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push("visible"===this.visibility?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};class NM extends rO{constructor(e,t){super(),UP(this,"trackMediaType",gP.DATA),UP(this,"_version",1),UP(this,"_type",3),UP(this,"_config",void 0),UP(this,"_originDataChannel",void 0),UP(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),UP(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),UP(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 JN("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 Wh(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new jw(Bw.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 jw(Bw.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new jw(Bw.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),[LP.OPEN,LP.CLOSE,LP.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 DM extends NM{constructor(e){super(e),UP(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(t).getUint8(3);if(i!==this.id)return void(JN("SHOW_DATASTREAM2_LOG")&&ND.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let n=e.data.slice(this._dataStreamPacketHeader.byteLength);n=this._dataStreamPacketHandler.deserialize(n),this.emit(LP.MESSAGE,n)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class PM extends NM{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}function LM(){const e=new Blob([atob("Y29uc3QgdD0idmlkZW8vaDI2NCIsZT0idmlkZW8vaDI2NSI7ZnVuY3Rpb24gbih0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLHI9W10saT0wO2Zvcig7ci5sZW5ndGg8bjspaSszPG4mJjA9PT1hW2ldJiYwPT09YVtpKzFdJiYzPT09YVtpKzJdJiYoMD09PWFbaSszXXx8MT09PWFbaSszXXx8Mj09PWFbaSszXXx8Mz09PWFbaSszXSk/KHIucHVzaChhW2ldLGFbaSsxXSxhW2krM10pLGkrPTQ
5pOihyLnB1c2goYVtpXSksaSsrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocil9ZnVuY3Rpb24gYShhLHIpe3N3aXRjaChyKXtjYXNlIHQ6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IGE9MDtmb3IoO2ErNDx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KGErMCkmJjA9PT1lLmdldFVpbnQ4KGErMSkmJjA9PT1lLmdldFVpbnQ4KGErMikmJjE9PT1lLmdldFVpbnQ4KGErMykmJjY9PT1lLmdldFVpbnQ4KGErNCkpe2xldCByPWErNixpPTAsbz0wO2Zvcig7MjU1PT09KG89ZS5nZXRVaW50OChyKyspKTspaSs9MjU1O2krPW87Y29uc3Qgcz1uKHQuZGF0YSxyLGkpO3JldHVybiBuZXcgVWludDhBcnJheShzKX1hKyt9cmV0dXJuIG51bGx9KGEpO2Nhc2UgZTpyZXR1cm4gZnVuY3Rpb24odCl7Y29uc3QgZT1uZXcgRGF0YVZpZXcodC5kYXRhKTtsZXQgYT0wO2Zvcig7YSs1PHQuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PWUuZ2V0VWludDgoYSswKSYmMD09PWUuZ2V0VWludDgoYSsxKSYmMD09PWUuZ2V0VWludDgoYSsyKSYmMT09PWUuZ2V0VWludDgoYSszKSYmNzg9PT1lLmdldFVpbnQ4KGErNCkmJjE9PT1lLmdldFVpbnQ4KGErNSkmJjEwMT09PWUuZ2V0VWludDgoYSs2KSl7bGV0IHI9YSs3LGk9MCxvPTA7Zm9yKDsyNTU9PT0obz1lLmdldFVpbnQ4KHIrKykpOylpKz0yNTU7aSs9bztjb25zdCBzPW4odC5kYXRhLHIsaSk7cmV0dXJuIG5ldyBVaW50OEFycmF5KHMpfWErK31yZXR1cm4gbnVsbH0oYSk7ZGVmYXVsdDpyZXR1cm4gbnVsbH19ZnVuY3Rpb24gcih0KXtjb25zdCBlPXQubGVuZ3RoO2xldCBuPVtdLGE9MDtmb3IoO2E8ZTspYSsyPGUmJjA9PT10W2FdJiYwPT09dFthKzFdJiYoMD09PXRbYSsyXXx8MT09PXRbYSsyXXx8Mj09PXRbYSsyXXx8Mz09PXRbYSsyXSk/KG4ucHVzaCh0W2FdLHRbYSsxXSwzLHRbYSsyXSksYSs9Myk6KG4ucHVzaCh0W2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShuKX1mdW5jdGlvbiBpKG4sYSxpKXtzd2l0Y2goaSl7Y2FzZSB0OnJldHVybiBmdW5jdGlvbih0LGUpe2NvbnN0IG49cihlKSxhPW4ubGVuZ3RoLGk9TWF0aC5mbG9vcihhLzI1NSksbz1hJTI1NSxzPW5ldyBVaW50OEFycmF5KDYraSsxK2ErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPGk7KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09byxmKysscy5zZXQobiw2K2YpLHMuc2V0KG5ldyBVaW50OEFycmF5KHQpLDYrZithKSxzLmJ1ZmZlcn0obixhKTtjYXNlIGU6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1yKGUpLGE9bi5sZW5ndGgsaT1NYXRoLmZsb29yKGEvMjU1KSxvPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNytpKzErYSsxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPGk7KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09byxmKysscy5zZXQobiw3K2YpLGYrPWEsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0obixhKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBvKG4pe2lmKG4ubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGE9LTE7Zm9yKGxldCB0PTA7dDxuLmxlbmd0aC0zO3QrKyl7aWYoMD09PW5bdF0mJjA9PT1uW3QrMV0mJjE9PT1uW3QrMl0pe2E9dDticmVha31pZih0PG4ubGVuZ3RoLTQmJjA9PT1uW3RdJiYwPT09blt0KzFdJiYwPT09blt0KzJdJiYxPT09blt0KzNdKXthPXQ7YnJlYWt9fWlmKC0xPT09YSlyZXR1cm4iIjtjb25zdCByPWErKDA9PT1uW2ErMl0/NDozKTtpZihyPj1uLmxlbmd0aClyZXR1cm4iIjtjb25zdCBpPW5bcl07aWYoMTI4JmkpcmV0dXJuIiI7aWYoKGk+PjEmNjMpPj0zMilyZXR1cm4gZTtpZihyKzE8bi5sZW5ndGgpe2lmKDA9PSgyNDgmbltyKzFdKSlyZXR1cm4gZX1yZXR1cm4oMzEmaSk8PTMxP3Q6IiJ9Y29uc3Qgcz03MSxmPTEsbD0yLHU9MSxnPTI7dmFyIGM7ZnVuY3Rpb24gZCh0LGU9ITEpe2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09cylyZXR1cm47Y29uc3QgYT10LmdldFVpbnQxNigxKSxyPWYrbCthLGk9bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLXIpO2kuc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHIsdC5ieXRlTGVuZ3RoLXIpKTtjb25zdCBvPXttOm4sdGx2TGVuOmEsdGx2OltdLGZyYW1lOml9O2xldCBkPWYrbDtmb3IoO2Q8cjspe2NvbnN0IG49dC5nZXRVaW50OChkKSxhPXQuZ2V0VWludDE2KGQrdSkscj11K2c7aWYobj09PWMuQVVESU9fTEVWRUwpe2xldCBpPXQuZ2V0VWludDgoZCtyKTtmb3IobGV0IGU9MTtlPGE7ZSsrKWk9aTw8OHx0LmdldFVpbnQ4KGQrcitlKTtvLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6YSx2YWx1ZTplPzEyN15pPj4xOjEyNyZpfSl9ZWxzZSBpZihuPT09Yy5NRVRBREFUQXx8bj09PWMuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShhKTtmb3IobGV0IG49MDtuPGE7bisrKWVbbl09dC5nZXRVaW50OChkK3Irbik7by50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZX0pfWQrPXIrYX1yZXR1cm4gb30hZnVuY3Rpb24odCl7dFt0LkFVRElPX0xFVkVMPTFdPSJBVURJT19MRVZFTCIsdFt0Lk1FVEFEQVRBPTJdPSJNRVRBREFUQSIsdFt0LkFVRElPXzY0X0JJVF9QVFM9M109IkFVRElPXzY0X0JJVF9QVFMifShjfHwoYz17fSkpLHNlbGYub25ydGN0cmFuc2Zvcm09dD0+e2NvbnN0IGU9dC50cmFuc2Zvcm1lcixuPVtdLHI9W10saD1bXTtsZXQgcCxVPW51bGw7ZS5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZuLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZyLnB1c2godC5kYXRhLm1ldGFkYXRhKSx2b2lkIDAhPT10LmRhdGEucHRzJiZoLnB1c2godC5kYXRhLnB0cyl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCB5PWUucmVhZGFibGUuZ2V0UmVhZGVyKCksQT1lLndyaXRhYmxlLmdldFdyaXRlcigpOyJzZWktcngiPT09ZS5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXt5LnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYobi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRWaWRlb0ZyYW1lKXtjb25zdCB0PW8obmV3IFVpbnQ4QXJyYXkobi52YWx1ZS
55kYXRhKSkscj1hKG4udmFsdWUsdCk7aWYociYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3NlaTpyfSksIVUpe2NvbnN0IHQ9bi52YWx1ZS5nZXRNZXRhZGF0YSgpfHx7fTtVPXt0eXBlOm4udmFsdWUudHlwZSxydHBUaW1lc3RhbXA6bi52YWx1ZS50aW1lc3RhbXAscGF5bG9hZFR5cGU6dC5wYXlsb2FkVHlwZXx8MCxzc3JjOnQuc3luY2hyb25pemF0aW9uU291cmNlfHwwLGxlbmd0aDpuLnZhbHVlLmRhdGEuYnl0ZUxlbmd0aCwuLi4ibWltZVR5cGUiaW4gdD97bWltZVR5cGU6dC5taW1lVHlwZX06e319LGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtmaXJzdEZyYW1lSW5mbzpVfSl9fUEud3JpdGUobi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KGUpOiJzZWktdHgiPT09ZS5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXt5LnJlYWQoKS50aGVuKChhPT57aWYoIWEuZG9uZSl7aWYoYS52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRWaWRlb0ZyYW1lKXtjb25zdCB0PW8obmV3IFVpbnQ4QXJyYXkoYS52YWx1ZS5kYXRhKSksZT1uLnNoaWZ0KCk7aWYoZSl7Y29uc3Qgbj1pKGEudmFsdWUuZGF0YSxlLHQpO24mJihhLnZhbHVlLmRhdGE9bil9fUEud3JpdGUoYS52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KGUpOiJhdWRpby1tZXRhZGF0YS1yeCI9PT1lLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe3kucmVhZCgpLnRoZW4oKG49PntpZighbi5kb25lKXtpZihuLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZEF1ZGlvRnJhbWUpe2NvbnN0IHQ9bmV3IERhdGFWaWV3KG4udmFsdWUuZGF0YSksYT1uLnZhbHVlLmdldE1ldGFkYXRhKCk7bGV0IHIsaT0hMTtpZihpPWEmJnZvaWQgMCE9PWEubWltZVR5cGU/ImF1ZGlvL3JlZCI9PT1hLm1pbWVUeXBlOmZ1bmN0aW9uKHQsZSl7aWYodm9pZCAwPT09ZSlyZXR1cm4hMTtjb25zdCBuPXQuZ2V0VWludDgoMCk7cmV0dXJuIDcxIT09biYmISEoMTI4Jm4mJigxMjcmbik9PT1lKX0odCxwKSxpKXtjb25zdCBlPWZ1bmN0aW9uKHQpe2lmKHQuYnl0ZUxlbmd0aDw9MClyZXR1cm5bXTtjb25zdCBlPVtdO2xldCBuPTA7Zm9yKDtuPHQuYnl0ZUxlbmd0aDspe2NvbnN0IGE9KDEyOCZ0LmdldFVpbnQ4KG4pKT4+NyxyPTEyNyZ0LmdldFVpbnQ4KG4pO2lmKCEoYSYmbis0PD10LmJ5dGVMZW5ndGgpKXtuKys7YnJlYWt9e2NvbnN0IGE9dC5nZXRVaW50MzIobiwhMSksaT0oMTY3NzYxOTImYSk+PjEwLG89MTAyMyZhO2UucHVzaCh7cHQ6cix0c19vZmZzZXQ6aSxsZW5ndGg6byxkYXRhOm5ldyBVaW50OEFycmF5fSksbis9NH19bGV0IGE9dC5ieXRlTGVuZ3RoLW47Zm9yKGNvbnN0IHIgb2YgZSl7aWYoci5sZW5ndGg+YSlyZXR1cm4gY29uc29sZS53YXJuKCJCcm9rZW4gcmVkIHBheWxvYWQiKSxbXTtyLmxlbmd0aD4wJiYoci5kYXRhPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLHIubGVuZ3RoKSxuKz1yLmxlbmd0aCxhLT1yLmxlbmd0aCl9aWYoYT4wKXtjb25zdCByPXtwdDplLmxlbmd0aD4wP2VbZS5sZW5ndGgtMV0ucHQ6MCx0c19vZmZzZXQ6MCxsZW5ndGg6YSxkYXRhOm5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLGEpfTtlLnB1c2gocil9cmV0dXJuIGV9KHQpO2lmKGUubGVuZ3RoPjApe2NvbnN0IHQ9ZnVuY3Rpb24odCl7bGV0IGU9MDtmb3IobGV0IG49MDtuPHQubGVuZ3RoO24rKyllKz1uPHQubGVuZ3RoLTE/NDoxLGUrPXRbbl0ubGVuZ3RoO2NvbnN0IG49bmV3IFVpbnQ4QXJyYXkoZSk7bGV0IGE9MDtmb3IobGV0IGU9MDtlPHQubGVuZ3RoO2UrKylpZihlPHQubGVuZ3RoLTEpe2NvbnN0IHI9KDIxNDc0ODM2NDh8KDEyNyZ0W2VdLnB0KTw8MjR8KDI2MjE0MyZ0W2VdLnRzX29mZnNldCk8PDEwfDEwMjMmdFtlXS5sZW5ndGgpPj4+MDtuW2ErK109cj4+MjQmMjU1LG5bYSsrXT1yPj4xNiYyNTUsblthKytdPXI+PjgmMjU1LG5bYSsrXT0yNTUmcn1lbHNlIG5bYSsrXT0xMjcmdFtlXS5wdDtmb3IoY29uc3QgZSBvZiB0KW4uc2V0KGUuZGF0YSxhKSxhKz1lLmxlbmd0aDtyZXR1cm4gbn0oZS5tYXAoKHQ9Pntjb25zdCBlPW5ldyBVaW50OEFycmF5KHQubGVuZ3RoKTtlLnNldCh0LmRhdGEpO2NvbnN0IG49ZChuZXcgRGF0YVZpZXcoZS5idWZmZXIpKTtyZXR1cm4gbj8uZnJhbWUmJih0LmRhdGE9bj8uZnJhbWUpLHI9bix0fSkpKTtuLnZhbHVlLmRhdGE9dC5idWZmZXJ9fWVsc2Ugcj1kKHQpLHImJihuLnZhbHVlLmRhdGE9ci5mcmFtZS5idWZmZXIpO2lmKHIpe2xldCB0PXIudGx2LmZpbmQoKHQ9PnQudGFnPT09Yy5NRVRBREFUQSkpO2lmKHQmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiZlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7bWV0YWRhdGE6dC52YWx1ZX0pLHQ9ci50bHYuZmluZCgodD0+dC50YWc9PT1jLkFVRElPXzY0X0JJVF9QVFMpKSx0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmOD09dC52YWx1ZS
55sZW5ndGgpe2NvbnN0IG49bmV3IERhdGFWaWV3KHQudmFsdWUuYnVmZmVyKS5nZXRCaWdVaW50NjQoMCwhMCk7dCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtwdHM6bn0pfX19QS53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0oZSk6ImF1ZGlvLW1ldGFkYXRhLXR4Ij09PWUub3B0aW9ucy5uYW1lJiZmdW5jdGlvbiB0KGUpe3kucmVhZCgpLnRoZW4oKG49PntpZighbi5kb25lKXtpZihlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7Z2V0TWV0YWRhdGE6ITB9KSxuLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZEF1ZGlvRnJhbWUpe2NvbnN0IHQ9ci5zaGlmdCgpLGU9aC5zaGlmdCgpO2lmKHR8fHZvaWQgMCE9PWUpe2NvbnN0IGE9ZnVuY3Rpb24odCxlKXtpZih2b2lkIDA9PT10JiZ2b2lkIDA9PT1lKXJldHVybiBudWxsO2xldCBuPTAsYT1udWxsLHI9bnVsbDtpZih0KXtjb25zdCBlPXQubGVuZ3RoLHI9dStnK2U7YT1uZXcgVWludDhBcnJheShyKTtjb25zdCBpPW5ldyBEYXRhVmlldyhhLmJ1ZmZlcik7aS5zZXRVaW50OCgwLGMuTUVUQURBVEEpLGkuc2V0VWludDE2KHUsZSksYS5zZXQodCx1K2cpLG4rPXJ9aWYoZSl7Y29uc3QgdD04LGE9dStnK3Q7cj1uZXcgVWludDhBcnJheShhKTtjb25zdCBpPW5ldyBEYXRhVmlldyhyLmJ1ZmZlcik7aS5zZXRVaW50OCgwLGMuQVVESU9fNjRfQklUX1BUUyksaS5zZXRVaW50MTYodSx0KSxpLnNldEJpZ1VpbnQ2NCh1K2csZS52YWx1ZU9mKCksITApLG4rPWF9Y29uc3QgaT1uZXcgVWludDhBcnJheShmK2wrbiksbz1uZXcgRGF0YVZpZXcoaS5idWZmZXIpO28uc2V0VWludDgoMCxzKSxvLnNldFVpbnQxNihmLG4pO2xldCBkPWYrbDtyZXR1cm4gYSYmKGkuc2V0KGEsZCksZCs9YS5sZW5ndGgpLHImJmkuc2V0KHIsZCksaX0odCxlKTtpZihhKXtjb25zdCB0PW5ldyBVaW50OEFycmF5KGEubGVuZ3RoK24udmFsdWUuZGF0YS5ieXRlTGVuZ3RoKTt0LnNldChhLDApLHQuc2V0KG5ldyBVaW50OEFycmF5KG4udmFsdWUuZGF0YSksYS5ieXRlTGVuZ3RoKSxuLnZhbHVlLmRhdGE9dC5idWZmZXJ9fX1BLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKSxwPWUub3B0aW9ucy5wdH0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpOwo=")],{type:"text/javascript"});return setTimeout((()=>Zf.revokeObjectURL(e)),0),new Worker(Zf.createObjectURL(e))}const kM=71,MM=1,UM=2,VM=1,xM=2;var FM=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(FM||{});function BM(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.getUint8(0);if(i!==kM)return;const n=e.getUint16(1),r=MM+UM+n,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:i,tlvLen:n,tlv:[],frame:o};let a=MM+UM;for(;a<r;){const i=e.getUint8(a),n=e.getUint16(a+VM),r=VM+xM;if(i===FM.AUDIO_LEVEL){let o=e.getUint8(a+r);for(let t=1;t<n;t++)o=o<<8|e.getUint8(a+r+t);s.tlv.push({tag:i,length:n,value:t?127^o>>1:127&o})}else if(i===FM.METADATA||i===FM.AUDIO_64_BIT_PTS){const t=new Uint8Array(n);for(let i=0;i<n;i++)t[i]=e.getUint8(a+r+i);s.tlv.push({tag:i,length:n,value:t})}a+=r+n}return s}const jM=new Map;const GM=127,WM=1e-10,HM=139/13,KM=new Map;function YM(e,t,i){const n="".concat(e,"-").concat(t,"-").concat(i);let r=0;if(KM.has(n))r=KM.get(n);else{const o=.5;r=Math.log(function(e,t){const i=e-t;t<i&&(t=i);let n=1;for(let i=e,r=1;i>t;i--,r++)n=n*i/r;return n}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(i)+i*e,KM.set(n,r)}return r<WM&&(r=WM),r}function zM(e,t,i){const n=t.length,r=e.length/n;let o=!1;for(let s=0,a=0;s<n;s++){let n=0;for(let t=a+r;a<t;a++)e[a]>i&&n++;t[s]!==n&&(t[s]=n,o=!0)}return o}window.cache=KM;let qM=0;class XM{constructor(e){UP(this,"id",void 0),UP(this,"immediates",[]),UP(this,"lastNonSilence",-1),UP(this,"immediateSpeechActivityScore",WM),UP(this,"lastLevelChangedTime",Date.now()),UP(this,"levels",[]),UP(this,"longs",[]),UP(this,"longSpeechActivityScore",WM),UP(this,"mediums",[]),UP(this,"mediumSpeechActivityScore",WM),UP(this,"minLevel",0),UP(this,"nextMinLevel",0),UP(this,"nextMinLevelWindowLength",0),UP(this,"energyScore",0),this.id=e||"".concat(qM++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,i=this.minLevel+HM;let n=!1;for(let r=0;r<e.length;++r){let o=t[r];o<i&&(o=0);const s=Math.floor(o/HM);e[r]!==s&&(e[r]=s,n=!0)}return n}computeLongs(){return zM(this.mediums,this.longs,4)}computeMediums(){return zM(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=YM(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=YM(this.longs[0],10,47),this.longSpeechActivityScore>WM&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=YM(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(cr(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let i=e;return e<0&&(i=0),e>GM&&(i=GM),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+HM?i:i/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>GM&&(e=GM),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class JM{constructor(e){UP(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}class QM{constructor(e,t,i){UP(this,"isDominant",void 0),UP(this,"energyRanking",void 0),UP(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class ZM extends rO{constructor(e){super(),UP(this,"dominantId",null),UP(this,"lastDecisionTime",0),UP(this,"lastLevelChangedTime",0),UP(this,"lastLevelIdleTime",0),UP(this,"relativeSpeechActivities",[]),UP(this,"speakers",new Map),UP(this,"enableSilence",!1),UP
vendor: 13,696 bytes, line 5
5(this,"timeoutToSilenceInterval",0),UP(this,"decisionMaker",null),UP(this,"loudest",[]),UP(this,"numLoudestToTrack",3),UP(this,"energyExpireTimeMs",250),UP(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=i&&(this.energyAlphaPct=i),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const i=Date.now(),n=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker());const r=n.levelChanged(t,i);return this.updateLoudestList(n,r,i)}runInDecisionMaker(e){return this.decisionMaker!==e||this.lastDecisionTime>0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new XM(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,i){const n=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new QM(n,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new QM(n,0,e.energyScore);const r=i-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const t=this.loudest[o];if(t.getLastLevelChangedTime()<r&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let s=0;for(;s<this.loudest.length&&!(this.loudest[s].energyScore<e.energyScore);)++s;return s<this.numLoudestToTrack&&(this.loudest.splice(s,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new QM(n,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new JM(this),this.decisionMaker.execute())}makeDecision(e){let t=null,i=null;const n=this.speakers.size;let r=null;if(0===n)r=null;else if(1===n){var o;const t=Zh(o=this.speakers).call(o).next().value;this.enableSilence&&t&&(r=t.id,t.evaluateSpeechActivityScores(e),e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null))}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(r=e.value[0],t=e.value[1])}else r=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const i=this.relativeSpeechActivities;let n=2;for(const o of this.speakers.entries()){const[s,a]=o;if(a===t)continue;a.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){const n=null==t?WM:t.getSpeechActivityScore(e);i[e]=Math.log(a.getSpeechActivityScore(e)/n)}const c=i[0],d=i[1],l=i[2];c>3&&d>2&&l>0&&d>n&&(n=d,r=s)}this.enableSilence&&null!=t&&r===t.id&&e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null)}null==r&&!this.enableSilence||r===this.dominantId||(t=this.dominantId,this.dominantId=r,i=this.dominantId),null==i&&!this.enableSilence||i===t||this.emit("ActiveSpeakerChanged",i)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let i=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):i=t;let n=300-(e-this.lastDecisionTime);return n<=0&&(this.lastDecisionTime=e,this.makeDecision(e),n=300-(Date.now()-e)),n>0&&i>n&&(i=n),i}timeoutIdleLevels(e){const t=[];for(const n of Zh(i=this.speakers).call(i)){var i;const r=e-n.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||n.id!==this.dominantId)?t.push(n.id):300<r&&n.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}}const $M=new Map;let eU=null,tU=null;const iU=3;let nU=[];const rU=new Map,oU=new Map;class sU{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){UP(this,"id",void 0),UP(this,"track",void 0),UP(this,"score",0),UP(this,"active",!0),UP(this,"muted",!1),UP(this,"timer",0),UP(this,"actives",0),UP(this,"inactives",0),this.id=e,this.track=t,this.setActive(rU.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const{actives:t,inactives:i}=function(){const e=[],t=[];return Array.from(Zh(rU).call(rU)).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}();if(t.length>3){let e;t.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(t.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>40&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(Zh(rU).call(rU)).forEach((i=>{!i.active||i.id===e||i.samples<40||(!t||i.score<t.score)&&(t=i)})),t}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(Zh(rU).call(rU)).forEach((i=>{i.active||i.id===e||i.samples<40||(!t||i.score>t.score)&&(t=i)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let aU;function cU(e){const t=rU.get(e);t&&(rU.delete(e),t.clearTimer())}const dU=new Map,lU=new Map;const uU="video/h264",hU="video/h265";function pU(e,t,i){let n=new Uint8Array(e,t,i),r=[],o=0;for(;r.length<i;)o+3<i&&0===n[o]&&0===n[o+1]&&3===n[o+2]&&(0===n[o+3]||1===n[o+3]||2===n[o+3]||3===n[o+3])?(r.push(n[o],n[o+1],n[o+3]),o+=4):(r.push(n[o]),o++);return new Uint8Array(r)}function _U(e){const t=e.length;let i=[],n=0;for(;n<t;)n+2<t&&0===e[n]&&0===e[n+1]&&(0===e[n+2]||1===e[n+2]||2===e[n+2]||3===e[n+2])?(i.push(e[n],e[n+1],3,e[n+2]),n+=3):(i.push(e[n]),n++);return new Uint8Array(i)}function EU(e){if(e.length<5)return"";let t=-1;for(let i=0;i<e.length-3;i++){if(0===e[i]&&0===e[i+1]&&1===e[i+2]){t=i;break}if(i<e.length-4&&0===e[i]&&0===e[i+1]&&0===e[i+2]&&1===e[i+3]){t=i;break}}if(-1===t)return"";const i=t+(0===e[t+2]?4:3);if(i>=e.length)return"";const n=e[i];return 128&n?"":(n>>1&63)>=32||i+1<e.length&&0==(248&e[i+1])?hU:(31&n)<=31?uU:""}const mU=new Map;const fU=new Map;!function(){const e=sw();BD.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),BD.getStreamFromExtension=e.name===iw.CHROME&&Number(e.version)>34,BD.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}(),BD.supportMinBitrate=e.name===iw.CHROME||e.name===iw.EDGE,BD.supportSetRtpSenderParameters=function(){const e=sw();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!kw()||!(!hw()&&!lw())||e.name===iw.FIREFOX&&Number(e.version)>=64)}(),e.name===iw.SAFARI&&(Number(e.version)>=14?BD.supportDualStream=!0:BD.supportDualStream=!1),BD.webAudioMediaStreamDest=function(){const e=sw();return!(e.name===iw.SAFARI&&Number(e.version)<12)}(),BD.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,BD.supportWebGL="undefined"!=typeof WebGLRenderingContext,BD.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,kw()||(BD.webAudioWithAEC=!0),BD.supportShareAudio=function(){const e=sw();return(e.os===tw.WIN_10||e.os===tw.WIN_81||e.os===tw.WIN_7||e.os===tw.LINUX||e.os===tw.MAC_OS||e.os===tw.CHROMIUM_OS)&&e.name===iw.CHROME&&Number(e.version)>=74}(),BD.supportDataChannel=!!(mw(76)||Tw(68)||Rw(14)),BD.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!_w()&&!!e&&e.prototype.setConfiguration instanceof Function}(),BD.supportWebRTCEncodedTransform=GD(),BD.supportWebRTCInsertableStream=function(){const e=sw();return(e.name===iw.CHROME||e.name===iw.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),BD.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,BD.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,BD.supportSuppressLocalAudioPlayback=qD(),BD.supportRestrictOwnAudio=XD(),LO((()=>{BD.supportDualStreamEncoding=function(){const e=sw();return!!JN("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&JN("CHROME_DUAL_STREAM_USE_ENCODING")))}(),ND.debug("browser ua: ",navigator.userAgent),ND.info("browser info: ",e),ND.info("browser compatibility: ",BD)}))}();const SU=["CHINA","GLOBAL"];const gU=[[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]],TU=[],RU=[];function CU(e,t){return!!t&&TU.some((i=>i.uid===e&&i.channelName===t))}function vU(){return RU.length>0}var yU=KC.forEach,IU=Bn("forEach")?[].forEach:function(e){return yU(this,e,arguments.length>1?arguments[1]:void 0)};wi({target:"Array",proto:!0,forced:[].forEach!=IU},{forEach:IU});var AU=Ji("Array").forEach,bU=pn,wU=Ze,OU=l,NU=AU,DU=Array.prototype,PU={DOMTokenList:!0,NodeList:!0},LU=function(e){var t=e.forEach;return e===DU||OU(DU,e)&&t===DU.forEach||wU(PU,bU(e))?NU:t},kU=i(LU),MU=Xe,UU=to;wi({target:"Object",stat:!0,forced:n((function(){UU(1)}))},{keys:function(e){return UU(MU(e))}});var VU=i(ie.Object.keys),xU=i(qn),FU=i(ar),BU=wi,jU=Qn,GU=Gc,WU=te,HU=Vi,KU=Gi,YU=Z,zU=rp,qU=ht,XU=Qc,JU=oC("slice"),QU=qU("species"),ZU=Array,$U=Math.max;BU({target:"Array",proto:!0,forced:!JU},{slice:function(e,t){var i,n,r,o=YU(this),s=KU(o),a=HU(e,s),c=HU(void 0===t?s:t,s);if(jU(o)&&(i=o.constructor,(GU(i)&&(i===ZU||jU(i.prototype))||WU(i)&&null===(i=i[QU]))&&(i=void 0),i===ZU||void 0===i))return XU(o,a,c);for(n=new(void 0===i?ZU:i)($U(c-a,0)),r=0;a<c;a++,r++)a in o&&zU(n,r,o[a]);return n.length=r,n}});var eV=Ji("Array").slice,tV=l,iV=eV,nV=Array.prototype,rV=function(e){var t=e.slice;return e===nV||tV(nV,e)&&t===nV.slice?iV:t},oV=i(rV);function sV(e,t,i,n,r){var o,s,a,c={};return kU(o=VU(n)).call(o,(function(e){c[e]=n[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=xU(s=FU(a=oV(i).call(i)).call(a)).call(s,(function(i,n){return n(e,t,i)||i}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer&&(zR(e,t,c),c=null),c}let aV=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),cV=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),dV=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),lV=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),uV
vendor: 3,308 bytes, line 5
5=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_
vendor: 95,800 bytes, line 5
5LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),hV=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),pV=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.PRE_CONNECT_PC="pre_connect_pc",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",e.RECOVER_NOTIFICATION="recover_notification",e.VOS_FALLBACK="vos_fallback",e.VOS_FALLBACK_PROMISE="vos_fallback_promise",e}({}),_V=function(e){return e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SET_DUAL_STREAM_MODE="set_dual_stream_mode",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.CONFIGURE="configure",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag",e.DOWNGRADE_CODEC="downgrade_codec",e}({}),EV=function(e){return e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats",e}({}),mV=function(e){return e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list",e.ENABLE_MULTI_STREAM="enable_multi_stream",e}({}),fV=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),SV=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({});function gV(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw ND.error("Invalid Channel Name ".concat(e)),new FD(Bw.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function TV(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||Xw(e,1,255)))throw new FD(Bw.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&ND.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 RV=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const CV={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},vV={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function yV(e,t){Yw(e.url,"".concat(t,".url"),1,1e3,!1),qw(e.x)||Hw(e.x,"".concat(t,".x"),0,1e4),qw(e.y)||Hw(e.y,"".concat(t,".y"),0,1e4),qw(e.width)||Hw(e.width,"".concat(t,".width"),0,1e4),qw(e.height)||Hw(e.height,"".concat(t,".height"),0,1e4),qw(e.zOrder)||Hw(e.zOrder,"".concat(t,".zOrder"),0,255),qw(e.alpha)||Hw(e.alpha,"".concat(t,".alpha"),0,1,!1)}const IV={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 AV=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}({}),bV=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),wV=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 OV(e){if(!e.channelName)throw new FD(Bw.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new FD(Bw.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Yw(e.token,"info.token",1,2047),TV(e.uid),gV(e.channelName),!0}let NV=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}({}),DV=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}({}),PV=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}({}),LV=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}({}),kV=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),MV=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.UPDATE_GATEWAY_CONFIG="update-gateway-config",e.VOS_FALLBACK="vos-fallback",e.VOS_FALLBACK_PROMISE="vos-fallback-promise",e.RESET_SIGNAL="reset-signal",e.DATACHANNEL_FAILBACK="datachannel-failback",e}({}),UV=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}({}),VV=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}({}),xV=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 FV=[xV.AFRICA,xV.ASIA,xV.CHINA,xV.EUROPE,xV.GLOBAL,xV.INDIA,xV.JAPAN,xV.NORTH_AMERICA,xV.OCEANIA,xV.OVERSEA,xV.SOUTH_AMERICA];let BV=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 jV={CHINA:{},ASIA:{CODE:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:BV.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:{}};jN&&(jV.CHINA={CODE:BV.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 GV=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",e.FALLBACK_TO_HLS="fallback_to_hls",e.UPDATE_VOS_CONFIGURE="update_vos_configure",e}({});function WV(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class HV extends rO{constructor(e,t){super(),bI(this,"onICEConnectionStateChange",void 0),bI(this,"onConnectionStateChange",void 0),bI(this,"onDTLSTransportStateChange",void 0),bI(this,"onDTLSTransportError",void 0),bI(this,"onICETransportStateChange",void 0),bI(this,"onFirstAudioReceived",void 0),bI(this,"onFirstVideoReceived",void 0),bI(this,"onFirstAudioDecoded",void 0),bI(this,"onFirstVideoDecoded",void 0),bI(this,"onFirstVideoRender",void 0),bI(this,"onFirstVideoBufferReady",void 0),bI(this,"onFirstVideoDecodedTimeout",void 0),bI(this,"onSelectedLocalCandidateChanged",void 0),bI(this,"onSelectedRemoteCandidateChanged",void 0),bI(this,"onICECandidateError",void 0),bI(this,"getLocalVideoStats",void 0)}}class KV extends HV{constructor(e,t){super(e,t),bI(this,"establishPromise",void 0)}}let YV=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),zV=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),qV=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_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}({});const XV=["disconnected","failed"];let JV=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),QV=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),ZV=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",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.FirstVideoPreRender="FirstVideoPreRender",e.FirstVideoBufferReady="FirstVideoBufferReady",e}({}),$V=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),ex=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}({}),tx=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}({}),ix=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}({}),nx=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_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}({}),rx=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}({}),ox=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),sx=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}({}),ax=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}({}),cx=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}({}),dx=function(e){return e.ABORT="abort",e}({}),lx=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}({}),ux=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const hx={[aV.ACCESS_POINT]:{[lV.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[lV.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[lV.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[lV.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[lV.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[lV.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[lV.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[aV.UNILBS]:{[dV.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[dV.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[dV.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[dV.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[dV.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[dV.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[dV.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[dV.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[dV.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[dV.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[dV.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[dV.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[dV.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[aV.STRING_UID_ALLOCATOR]:{[cV.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[cV.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[cV.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function px(e){const t=hx[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===aV.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 _x={[uV.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[uV.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[uV.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[uV.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[uV.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[uV.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[uV.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[uV.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[uV.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[uV.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[uV.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[uV.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[uV.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[uV.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[uV.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[uV.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[uV.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[uV.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[uV.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[uV.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[uV.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[uV.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[uV.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[uV.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[uV.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[uV.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[uV.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[uV.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[uV.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[uV.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[uV.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[uV.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[uV.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[uV.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[uV.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[uV.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[uV.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[uV.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[uV.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[uV.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[uV.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[uV.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[uV.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[uV.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[uV.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[uV.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[uV.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[uV.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[uV.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[uV.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[uV.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[uV.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[uV.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[uV.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[uV.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[uV.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[uV.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[uV.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[uV.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[uV.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[uV.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[uV.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[uV.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[uV.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[uV.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function Ex(e){const t=_x[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function mx(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 fx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mx(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mx(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Sx(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=JN("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 gx=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Tx=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,Rx=/wss:\/\/(.+):([0-9]+)\/?/,Cx=/wss:\/\/(.[^\/]+)\/?/;let vx=0;class yx{constructor(e,t){bI(this,"id",0),bI(this,"store",void 0),bI(this,"recordIndex",void 0),bI(this,"websockets",[]),bI(this,"try443PortDuration",2e3),bI(this,"forceCloseWSDuration",5e3),bI(this,"try443PortTimeout",null),bI(this,"forceCloseTimeout",null),bI(this,"isTry443PortFailed",!1),bI(this,"isNormalPortFailed",!1),bI(this,"useDoubleDomain",!1),bI(this,"useProxy",!1),bI(this,"startTime",Date.now()),this.id=++vx,this.try443PortDuration=JN("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),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];ND.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=JN("GATEWAY_DOMAINS"),r=Date.now(),o=[],s=n.find((t=>{var i;return Dn(i=e.host).call(i,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(Sx(fx(fx({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=fx({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}a.push(Sx(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 FD(Bw.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=Qb();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));const n=o.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(n)),n&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:UV.A_ROUND_WS_FAILED})):!t&&n&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=n:this.isNormalPortFailed=n},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...o);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();sw().os===tw.MAC_OS&&_w()&&d(),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((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),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(gx)||[],t||([,i,n]=e.match(Tx)||[]),i&&n||([,i,n]=e.match(Rx)||[]),i&&n||([,i]=e.match(Cx)||[]),i||ND.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(ND.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function Ix(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 Ax extends rO{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}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(SV.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(SV.CONNECTED):"closed"===this._state?this.emit(SV.CLOSED):"failed"===this._state&&this.emit(SV.FAILED))}resetReconnectCount(e){ND.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(),bI(this,"_websocketUrl",null),bI(this,"connectionID",0),bI(this,"currentURLIndex",0),bI(this,"urls",[]),bI(this,"_reconnectMode","tryNext"),bI(this,"reconnectReason",void 0),bI(this,"_initMutex",void 0),bI(this,"name",void 0),bI(this,"_state","closed"),bI(this,"reconnectInterrupter",void 0),bI(this,"websocket",void 0),bI(this,"retryConfig",void 0),bI(this,"reconnectCount",0),bI(this,"forceCloseTimeout",5e3),bI(this,"onlineReconnectListener",void 0),bI(this,"useCompress",void 0),bI(this,"tryDoubleDomain",!1),bI(this,"use443PortOnly",!1),bI(this,"wsInflateLength",0),bI(this,"wsDeflateLength",0),bI(this,"closeEstablishingWs",(()=>{})),bI(this,"store",void 0),bI(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ix(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ix(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=r,this._initMutex=new sN("websocket",o?o.clientId:void 0);const{timeout:s,timeoutFactor:a}=t,c=Math.max(300,Math.floor(3*s/5)),d=Math.max(1.2,Math.floor(8*a)/10);gO.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),IO.on(TO.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gO.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._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{var n;const e=Qb(),t=this.urls[this.currentURLIndex];null===(n=this.store)||void 0===n||n.beforeConnect(),function(e){return!(HD()||JN("USE_NEW_TOKEN")||!JN("ENABLE_PREALLOC_PC")&&(null==e||!e.autoSubscribe||JN("FORCE_DISABLE_AUTO_SUB")))}(this.store)&&this.emit(nx.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(SV.CLOSED,(()=>{e.reject(new jw(Bw.WS_DISCONNECT))})),this.once(SV.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._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void ND.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),ND.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 jw(Bw.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new jw(Bw.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=Qb();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),ND.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(ND.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 jw(Bw.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=vO(this,SV.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void ND.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new jw(Bw.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},o=e=>{this.emit(SV.ON_MESSAGE,e)},s=e=>{ND.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),JN("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=JN("GATEWAY_WSS_ADDRESS")),ND.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;this._websocketUrl=Sx(e);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 jw,o=n&&e.code===Bw.WS_ABORT,s=n&&e.code===Bw.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());ND.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 jw(Bw.WS_DISCONNECT,"websocket is closed: ".concat(c)):new jw(Bw.WS_ERR,"init websocket failed: ".concat(c))),s&&ND.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;ND.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||IO.isOnline||!IO.onlineWaiter||(this.onlineReconnectListener=IO.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=dN(this.reconnectCount,this.retryConfig);ND.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Wh.race([KO(t),this.onlineReconnectListener||new Wh((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(SV.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===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);ND.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(ND.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await RO(this,SV.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;ND.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;if(Array.isArray(n)){if(Dn(n).call(n,"dynamic key expired"))return this.emit(SV.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(Dn(n).call(n,"request downgrade fallback"))return this.emit(SV.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class bx extends Ax{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=Qb(),n=function(e,t){return new yx(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{ND.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new jw(Bw.WS_ABORT,"choose best websocket aborted"))};const r=JN("GATEWAY_DOMAINS");return ND.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 wx extends Ax{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 Wh(((i,n)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{ND.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new jw(Bw.WS_ABORT,"choose best websocket aborted"))};const s=JN("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)));ND.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),ND.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(ND.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;ND.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{ND.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)))||(ND.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a))},e.onmessage=t=>{ND.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),KO(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;ND.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 jw(Bw.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return ND.error("[".concat(this.name,"]").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{ND.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},KO(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 Ox extends rO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===hV.CONNECTED?this.emit(pV.WS_CONNECTED):e===hV.RECONNECTING?this.emit(pV.WS_RECONNECTING,this._websocketReconnectReason):e===hV.CLOSED&&this.emit(pV.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(),bI(this,"__name__","AgoraRTCSignal"),bI(this,"_disconnectedReason",void 0),bI(this,"_websocketReconnectReason",void 0),bI(this,"_connectionState",hV.CLOSED),bI(this,"reconnectToken",void 0),bI(this,"websocket",void 0),bI(this,"openConnectionTime",void 0),bI(this,"clientId",void 0),bI(this,"lastMsgTime",Date.now()),bI(this,"uploadCache",[]),bI(this,"uploadCacheInterval",void 0),bI(this,"rttRolling",new hN(5)),bI(this,"pingpongTimer",void 0),bI(this,"wsInflateDataTimer",void 0),bI(this,"pingpongTimeoutCount",0),bI(this,"ortc",void 0),bI(this,"joinResponse",void 0),bI(this,"multiIpOption",void 0),bI(this,"initError",void 0),bI(this,"spec",void 0),bI(this,"store",void 0),bI(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(pV.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===mV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===mV.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(uO.UID_BANNED);break;case 15:this.close(uO.IP_BANNED);break;case 16:this.close(uO.CHANNEL_BANNED)}if(t._type===mV.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case uV.ERR_LICENSE_MISSING:this.close(uO.LICENSE_MISSING);break;case uV.ERR_LICENSE_EXPIRED:this.close(uO.LICENSE_EXPIRED);break;case uV.ERR_LICENSE_MINUTES_EXCEEDED:this.close(uO.LICENSE_MINUTES_EXCEEDED);break;case uV.ERR_LICENSE_PERIOD_INVALID:this.close(uO.LICENSE_PERIOD_INVALID);break;case uV.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(uO.LICENSE_MULTIPLE_SDK_SERVICE);break;case uV.ERR_LICENSE_ILLEGAL:this.close(uO.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new bx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,JN("JOIN_GATEWAY_USE_DUAL_DOMAIN"),JN("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===hV.CONNECTED&&this.reconnect("retry",SO.OFFLINE)}))}async request(e,t,i,n){const r=YO(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((t,i)=>{if(this.connectionState===hV.CONNECTED)return t();const n=()=>{this.off(pV.WS_CLOSED,r),t()},r=()=>{this.off(pV.WS_CONNECTED,n),i(new FD(Bw.WS_ABORT))};this.once(pV.WS_CONNECTED,n),this.once(pV.WS_CLOSED,r),e!==_V.PUBLISH&&e!==_V.PUBLISH_DATASTREAM&&e!==_V.SUBSCRIBE&&e!==_V.SUBSCRIBE_DATASTREAM&&e!==_V.UNSUBSCRIBE&&e!==_V.UNSUBSCRIBE_DATASTREAM&&e!==_V.UNPUBLISH&&e!==_V.UNPUBLISH_DATASTREAM&&e!==_V.CONTROL&&e!==_V.RESTART_ICE||this.once(pV.DISCONNECT_P2P,(()=>{i(new FD(Bw.DISCONNECT_P2P))})),e!==_V.PUBLISH&&e!==_V.RESTART_ICE||this.once(pV.ABORT_P2P_EXECUTION,(()=>{i(new FD(Bw.DISCONNECT_P2P))}))}));if(this.connectionState!==hV.CONNECTING&&this.connectionState!==hV.RECONNECTING||e===_V.JOIN||e===_V.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Wh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.emit(pV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new FD(Bw.WS_ABORT,"type: ".concat(e))),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(pV.WS_CLOSED,c),this.once(pV.WS_RECONNECTING,c),KO(JN("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(ND.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(pV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===hV.CLOSED||e===_V.LEAVE)throw new FD(Bw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===_V.JOIN||e===_V.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=Ex(l),h=new FD(Bw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(ND.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===uV.ERR_TOO_MANY_BROADCASTERS?e===_V.JOIN||e===_V.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===uV.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,ND.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",SO.MULTI_IP)):this.reconnect(u.action,SO.SERVER_ERROR),e===_V.JOIN||e===_V.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((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 ND.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(EV.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=JN("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!==hV.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)}),JN("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(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 Wh(((t,i)=>{this.once(pV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(pV.WS_CLOSED,(e=>i(this.initError||new FD(Bw.WS_ABORT,e)))),this.connectionState=hV.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||uO.LEAVE,this.connectionState=hV.CLOSED,ND.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(pV.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await RO(this,pV.REQUEST_JOIN_INFO);this.store.joinReq();const t=await this.request(_V.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(pV.REPORT_JOIN_GATEWAY,UV.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(pV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=hV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new FD(Bw.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=yO(this,pV.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(_V.REJOIN,e);return!!t&&(this.connectionState=hV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(mV.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(mV.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(mV.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(mV.MUTE_AUDIO,{uid:e.uid}):this.emit(mV.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(mV.MUTE_VIDEO,{uid:e.uid}):this.emit(mV.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(mV.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(mV.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(mV.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(mV.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(mV.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)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(_V.DOWNGRADE_CODEC,t)}handleNotification(e){ND.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Ex(e.code);if(28===e.code&&"detail"in e&&(ND.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(pV.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===uV.ERR_REPEAT_JOIN_CHANNEL&&JN("IGNORE_UID_CHECK")?void this.close(uO.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(uO.UID_BANNED),void this.close()):e.code===uV.K_VOS_FALLBACK&&"detail"in e?(ND.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&JN("ENABLE_QUALITY_FALLBACK")?void RO(this,pV.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{ND.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&JN("ENABLE_FALLBACK_TO_HLS")?(this.emit(pV.VOS_FALLBACK,e.detail),void this.close(uO.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,SO.SERVER_ERROR);ND.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=JN("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(ND.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>JN("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",SO.TIMEOUT):this.request(_V.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),JN("REPORT_STATS")&&this.send(_V.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(EV.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(SV.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(pV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(SV.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SV.CLOSED,(()=>{this.connectionState=hV.CLOSED})),this.websocket.on(SV.FAILED,(()=>{this._disconnectedReason=uO.NETWORK_ERROR,this.connectionState=hV.CLOSED})),this.websocket.on(SV.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===hV.CONNECTED?this.connectionState=hV.RECONNECTING:this.connectionState=hV.CONNECTING})),this.websocket.on(SV.WILL_RECONNECT,((e,t,i)=>{const n=yO(this,pV.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(ND.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=UV.P2P_DISCONNECTED),r&&(ND.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(pV.REPORT_JOIN_GATEWAY,t||UV.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(pV.DISCONNECT_P2P)),i(e)})),this.websocket.on(SV.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{ND.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",SO.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(pV.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof FD){if(e.code===Bw.UNEXPECTED_RESPONSE&&e.data.code===uV.ERR_NO_AUTHORIZED)return this.initError=new FD(Bw.TOKEN_EXPIRE,"dynamic key expired"),void this.close(uO.TOKEN_EXPIRE);ND.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",SO.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(SV.REQUEST_NEW_URLS,((e,t)=>{RO(this,pV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(SV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(mV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(nx.PRE_CONNECT_PC,(()=>{this.emit(pV.PRE_CONNECT_PC)})),this.websocket.on(SV.ON_FALLBACK,(()=>{JN("ENABLE_FALLBACK_TO_HLS")&&this.emit(pV.VOS_FALLBACK,"fallback_hls")}))}}let Nx=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),Dx=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 Px(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 Lx(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Px(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Px(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let kx=0;function Mx(e){const t=JN("TURN_DOMAINS");kx=(kx+1)%t.length;const i=t[kx]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(i):(ND.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function Ux(e){try{const t=JN("TURN_DOMAINS"),i=JN("GATEWAY_DOMAINS").concat(t).find((t=>Dn(e).call(e,t)));if(i){return e.split(".".concat(i))[0].replace(/-/g,".")}return e}catch(t){return ND.debug("serverUrlToIp error, fallback to url",e),e}}function Vx(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(JN("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}}));const i=JN("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||ND.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{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<e.length;t++){var r;const n=dg(r=e[t]).call(r);i[t]&&n&&(i[t].ip6=n)}}const o=e.detail&&e.detail.candidate;let s;if(o){const[e,t]=o.split(":");e&&t&&(s={port:Number(t),ip:e,address:"".concat(e,":").concat(t)})}return{gatewayAddrs:i,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function xx(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function Fx(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(xx(t.width),"x").concat(xx(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function Bx(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function jx(e,t){let i,n,r;switch(t){case Dx.CHOOSE_SERVER:n=4096,r="choose server";break;case Dx.CLOUD_PROXY:n=1048576,r="proxy";break;case Dx.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case Dx.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new FD(Bw.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=>Lx(Lx({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:Lx(Lx({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new FD(Bw.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function Gx(e,t){return await Wh.all(e.addresses.map((async e=>({address:Mx(e.ip),tcpport:e.port,udpport:e.port,username:t&&JN("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():WN.username,password:t&&JN("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await nO(t.toString()):WN.password}))))}function Wx(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(xx(e.height),xx(e.width)),1):(ND.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function Hx(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:o,protocol:s}=e;const a={candidateType:t,relayProtocol:i,protocol:s};if("local-candidate"!==n){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),a.address=e.join("."),a.port=o}return a}function Kx(e){const t=e.split(":"),i=e.split(/[-.]/),n=Dn(e).call(e,"-")?"-":".";let r=e;return t.length>1?i.length>1?(i[1]="**",r=i[0]+n+"**:"+t[t.length-1]):r=t.length>2?t[0]+n+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(r=i[0]+n+"**"),r}function Yx(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function zx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:JN("SVC_MODE");if(JN("ENABLE_SVC"))return function(e){return e in NN}(e)?e:NN.L1T3}const qx={[YV.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[YV.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function Xx(e){e.send&&(Zx(YV.VIDEO,e.send.videoExtensions),Zx(YV.AUDIO,e.send.audioExtensions)),e.recv&&(Zx(YV.VIDEO,e.recv.videoExtensions),Zx(YV.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(Zx(YV.VIDEO,e.sendrecv.videoExtensions),Zx(YV.AUDIO,e.sendrecv.audioExtensions))}function Jx(e,t){e.send&&(Qx(YV.VIDEO,e.send.videoExtensions,t.send.videoExtensions),Qx(YV.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(Qx(YV.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),Qx(YV.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function Qx(e,t,i){t.forEach((t=>{var n;const r=qx[e].find((e=>{var i;let{key:n}=e;return Dn(i=t.extensionName).call(i,n)}));if(!r)return;const o=i.find((e=>{let{extensionName:t}=e;return Dn(t).call(t,r.key)}));o&&Dn(n=o.extensionName).call(n,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function Zx(e,t){t.forEach((t=>{var i;const n=qx[e].find((e=>{var i;let{key:n}=e;return Dn(i=t.extensionName).call(i,n)}));Dn(i=t.extensionName).call(i,"gdpr_forbidden")&&n&&(t.extensionName=n.extensionName)}))}function $x(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Dn(e).call(e,"abs-send-time")}function eF(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Dn(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}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;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?tF(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):tF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function nF(e){let t=arguments.length>1&&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,unsupportedVideoUplinkCodec:d,unsupportedVideoDownlinkCodec:l}=t,{useXR:u}=i;let h=[],p=[],_=[],E=[],m=!1,f=!1;if(aD(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||m||(p=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||f||(h=e.attributes.payloads,_=e.attributes.extmaps,f=!0))})),!E||0===p.length)throw new Error("Cannot get video capabilities from SDP.");if(!_||0===h.length)throw new Error("Cannot get audio capabilities from SDP.");if(p.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),p=p.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o){const e=p.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=CF(e,p).map((e=>e.payloadType)),i=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!Dn(i).call(i,e.payloadType)))}if(s&&(h=h.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&&(h=h.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=p.filter((e=>{var t;return Dn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(r?[]:CF(e,p))}const S=JN("UNSUPPORTED_VIDEO_CODEC");if(S&&S.length>0){const e=p.filter((e=>e.rtpMap&&Dn(S).call(S,e.rtpMap.encodingName.toLowerCase()))),t=CF(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Dn(i).call(i,e.payloadType))),ND.debug("unsupportedVideoCodec: ".concat(S,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===n){const e=p.filter((e=>e.rtpMap&&Dn(d).call(d,e.rtpMap.encodingName.toLowerCase()))),t=CF(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Dn(i).call(i,e.payloadType))),ND.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===n){const e=p.filter((e=>e.rtpMap&&Dn(l).call(l,e.rtpMap.encodingName.toLowerCase()))),t=CF(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Dn(i).call(i,e.payloadType))),ND.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function rF(e){const t=aD(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 oF(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 sF(e,t,i){const{cname:n}=e;let r=[];t&&(r=aF(t)),0===r.length&&(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:{}}))),ND.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=gF(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach((e=>{d.push({kind:YV.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:YV.AUDIO,ssrcMsg:[{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 aF(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:{}}],ND.debug("Using remote candidate from AP ".concat(Kx(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:{}}),ND.debug("Using IPV6 remote candidate from AP ".concat(Kx(e.ip6),":").concat(e.port)))),t}function cF(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=YO(8,"track-"),c={ssrcId:o,attributes:iF({label:a,mslabel:i=i||YO(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:iF({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 dF(e,t){t instanceof Ek&&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:{}}),"opus"===n&&"number"==typeof JN("OPUS_PTIME")?e.fmtp.parameters.ptime=JN("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&("pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!_w()&&(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")),t instanceof mk&&"opus"===n&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function lF(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 uF(e,t){var i;if(e.attributes.payloads.forEach((e=>{var t;"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&JN("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof dM&&t._encoderConfig&&-1===t._hints.indexOf(hP.SCREEN_TRACK)))return;const n=t._encoderConfig;jD().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))})),jD().supportMinBitrate&&!Dn(i=t._hints).call(i,hP.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(JN("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))}))}function hF(e){if("video"!==e.media.mediaType)return;const t=sw();if(t.name!==iw.SAFARI&&t.os!==tw.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function pF(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=>eF(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>eF(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=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);n.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=>eF(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=>$x(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===i))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=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);n.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=>$x(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 _F(e,t,i){if(_w())return;if("video"!==e.media.mediaType)return;if(!(t instanceof dM))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!JN("SIMULCAST"))return;if("vp9"===i&&JN("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;t<n;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:kO(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:kO(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function EF(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:NN.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=aD(t.sdp).mediaDescriptions[0];if(!i)return;const n=i.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),n}catch(e){return}}async function mF(){let e=arguments.length>0&&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=nF(i,e,t,"sendonly"),r=nF(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(SF(n,r,"videoExtensions",o,s,a),SF(n,r,"videoCodecs",o,s,a),SF(n,r,"audioExtensions",o,s,a),SF(n,r,"audioCodecs",o,s,a),JN("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(a.videoCodecs.forEach(((i,n)=>{var r;if("h264"===(null===(r=i.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){var o,s;const r=a.videoCodecs[n+1],c=r&&wF(i,r),d=null===(o=i.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(s=i.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==JN("FIRST_H264_PROFILE_LEVEL_ID")||JN("FIRST_PACKETIZATION_MODE")&&l!==JN("FIRST_PACKETIZATION_MODE")?c?t.push([i,r]):t.push([i]):c?e.push([i,r]):e.push([i])}})),e.length>0&&t.length>0){ND.debug("raising H264 baseline profile priority"),a.videoCodecs.forEach(((i,n)=>{var r;if("h264"===(null===(r=i.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){const r=wF(i,a.videoCodecs[n+1]),o=e.shift()||t.shift()||[];o.length>0&&(r?a.videoCodecs.splice(n,2,...o):a.videoCodecs.splice(n,1,...o))}}));const i=s.videoCodecs.filter((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==JN("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=CF(i,s.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!Dn(t).call(t,e.payloadType)))}JN("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())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==JN("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:s,sendrecv:a}}return{send:o,recv:s,sendrecv:a}}(e,t,n);try{i.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function fF(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=nF(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(SF(e,t,"videoExtensions",i,n,r),SF(e,t,"videoCodecs",i,n,r),SF(e,t,"audioExtensions",i,n,r),SF(e,t,"audioCodecs",i,n,r),JN("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){ND.debug("raising H264 baseline profile priority");const i=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,i)}-1!==t&&(n.videoCodecs=n.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:r}}function SF(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 gF(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=kO(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=kO(n),{send:r,recv:o}}function TF(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 RF(e,t,i,n){let r=[];if(e===YV.VIDEO){if(JN("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"]===JN("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"),ND.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&&(ND.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),JN("USE_PUB_RTX")||JN("USE_SUB_RTX")){const e=CF(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)}));const e=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")}));0===r.length&&(ND.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")}))),JN("ENABLE_AUDIO_RED")&&0!==e.length&&(r=[...e,...r])}return r}function CF(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 vF(e,t,i){const n=t.toString(),r=IF(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=yF(s,i||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function yF(e,t,i){if(JN("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=aD(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&&TF(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!JN("ENABLE_DOWN_SPS_PPS"))return;e.attributes.payloads.filter((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}
vendor: 5,432 bytes, line 5
5)).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(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"})}))))})),cD(n)}function IF(e,t,i,n){if(JN("SDP_LOGGING"))return ND.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{IF(e,"answer","local"===i?"remote":"local",n)}:void 0}async function AF(e,t,i){try{var n;if(!jD().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!JN("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];o.scalabilityMode=zx(i),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),ND.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){ND.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function bF(e){const t=JN("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Dn(e).call(e,t)))}function wF(e,t){try{var i;return(null===(i=e.fmtp)||void 0===i?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}function OF(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 NF(e,t){return typeof JN(e)===t?JN(e):void 0}function DF(){try{const e=JN("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OF(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},e)}catch(e){return ND.debug("handle gateway attributes failed: ",e),{}}}const PF={};function LF(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&ND.debug("install service ".concat(e.name)),PF[e.name]=e}function kF(e){const t=PF[e];if(!t)throw new jw(Bw.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function MF(e,t){return kF("DataStream").create(e,t)}function UF(){return kF("InterceptFrame").create()}function VF(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 xF(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?VF(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):VF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const FF=new Map;class BF extends rO{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(MV.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(MV.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){ND.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var i,n,r;super(),bI(this,"store",void 0),bI(this,"joinInfo",void 0),bI(this,"key",void 0),bI(this,"ntpOffset",0),bI(this,"usingProxy",!1),bI(this,"signal",void 0),bI(this,"role",void 0),bI(this,"isPreallocation",void 0),bI(this,"isPreSub",void 0),bI(this,"inChannelInfo",{joinAt:null,duration:0}),bI(this,"spec",void 0),bI(this,"_state","DISCONNECTED"),bI(this,"_statsCollector",void 0),bI(this,"_disconnectedReason",void 0),bI(this,"isSignalRecover",!1),bI(this,"hasChangeBGPAddress",!1),bI(this,"trafficStatsInterval",void 0),bI(this,"networkQualityInterval",void 0),bI(this,"_joinGatewayStartTime",0),bI(this,"_signalTimeout",!1),bI(this,"_clientRoleOptions",void 0),bI(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?(i={spec:xF(xF({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(n=(r=kF("P2PChannel")).createSubmodule)||void 0===n?void 0:n.call(r,i)):this.store.useDcSignal?function(e){return kF("DataChannelSignal").create(e)}({spec:xF(xF({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new Ox(xF(xF({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}setUsingProxy(e){this.usingProxy=e}async join(e,t,i){if(this.store.useDcSignal){let t=!1;"disabled"!==e.cloudProxyServer?(ND.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length>255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(ND.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.ap
vendor: 17,198 bytes, line 5
5Response.addresses.some((e=>e.fingerprint))||JN("FINGERPRINT")||(ND.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=FF.get(e.cname);if(r||(r=new Map,FF.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new FD(Bw.UID_CONFLICT);throw xD.joinGateway(e.sid,{lts:n,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let o=0;this.joinGatewayStartTime=n;const s=e.proxyServer,a=this.store.useDcSignal?"datachannel":"websocket";try{ND.debug("[".concat(this.store.clientId,"] use ").concat(a," join uid ").concat(o));const t=e.gatewayAddrs.map((t=>{let{address:i}=t;const[n,r]=i.split(":"),o={host:n,port:r};return e.proxyServer&&(o.proxy=e.proxyServer),o}));let i;i=this.store.useDcSignal?await this.signal.init(e.apResponse.addresses):await this.signal.init(t),o=i.uid,ND.debug("[".concat(this.store.clientId,"] ").concat(a," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var c;if(t.code===Bw.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else xD.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(c=t.data)||void 0===c?void 0:c.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!s||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload});if(t&&t.code===Bw.INIT_DATACHANNEL_TIMEOUT)throw ND.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw ND.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),ND.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{ND.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(MV.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(MV.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(MV.NETWORK_QUALITY,{uplinkNetworkQuality:Bx(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Bx(this._statsCollector.trafficStats.B_dnq)}):this.emit(MV.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!==uO.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==hV.CONNECTED||await function(e,t){return t===1/0?e:Wh.race([e,HO(t)])}(this.signal.request(_V.LEAVE,void 0,!0),3e3)}catch(e){ND.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==uO.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new FD(Bw.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:JN("PUB_EXTEND"),twcc:!!JN("PUBLISH_TWCC"),rtx:!!JN("USE_PUB_RTX")};try{return(await this.signal.request(_V.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===uV.ERR_PUBLISH_REQUEST_INVALID)return ND.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 FD(Bw.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(_V.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===uV.ERR_PUBLISH_REQUEST_INVALID)return ND.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 FD(Bw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(_V.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){ND.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new FD(Bw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(_V.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){ND.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new FD(Bw.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:!!JN("SUBSCRIBE_TWCC"),rtx:!!JN("USE_SUB_RTX")||void 0,extend:JN("SUB_EXTEND"),svc:Array.isArray(JN("SVC"))&&0!==JN("SVC").length?JN("SVC"):void 0};try{return await this.signal.request(_V.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===uV.ERR_SUBSCRIBE_REQUEST_INVALID)return ND.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 FD(Bw.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:!!JN("SUBSCRIBE_TWCC"),rtx:!!JN("USE_SUB_RTX"),extend:JN("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(JN("SVC"))&&0!==JN("SVC").length?JN("SVC"):void 0};try{return(await this.signal.request(_V.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===uV.ERR_SUBSCRIBE_REQUEST_INVALID)return ND.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 FD(Bw.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(_V.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===uV.ERR_SUBSCRIBE_REQUEST_INVALID)return ND.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 FD(Bw.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!JN("USE_SUB_RTX"),twcc:!!JN("SUBSCRIBE_TWCC"),svc:Array.isArray(JN("SVC"))&&0!==JN("SVC").length?JN("SVC"):void 0};try{return await this.signal.request(_V.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===uV.ERR_SUBSCRIBE_REQUEST_INVALID)return ND.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(_V.SET_VIDEO_PROFILE,t);ND.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(_V.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){ND.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new FD(Bw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(_V.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){ND.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(_V.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){ND.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(_V.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(_V.GATEWAY_INFO)}async renewToken(e){await this.signal.request(_V.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),JN("CLIENT_ROLE_OPTIONS")&&(ND.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(JN("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},JN("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),JN("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},JN("CLIENT_ROLE_OPTIONS")),ND.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(JN("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"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;const r=Object.assign({},t);delete r.delay,delete r.level,await this.signal.request(_V.SET_CLIENT_ROLE,xF(xF({role:e,level:n,delay:i},r),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,i){await this.signal.request(_V.SET_DUAL_STREAM_MODE,{mode:e},i,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(_V.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(_V.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(_V.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(_V.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(_V.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),xF({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(_V.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(_V.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=FF.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),this.usingProxy=!1}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:WN.username,password:WN.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(xF(xF({},WN),{},{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(_V.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&&LO((()=>{this.emit(MV.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,i,n,r;if(!this.joinInfo||!this.key)throw new FD(Bw.UNEXPECTED_ERROR,"can not generate join message, no join info");const o=Object.assign({},this.joinInfo.apResponse);let s=JN("REPORT_APP_SCENARIO");if("string"!=typeof s)try{s=JSON.stringify(s)}catch(e){s=void 0}var a;s&&s.length>128&&(s=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(MV.UPDATE_GATEWAY_CONFIG),a=this.store.clientId,Dn(RU).call(RU,a)||RU.push(a);const c=KD(this.store),d=!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),l=YD(this.store),u=DF(),h=GD(),p=(function(){const e=sw();if(e.name!==iw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}()||Cw(18,4,!1))&&yw(18,6,!0)&&"h264"===this.spec.codec&&JN("ENABLE_ABSSENDTIME_AS_SENTTS"),_=!("CN"!==(null===(i=o.detail)||void 0===i?void 0:i[3])||!JN("ENABLE_QUALITY_FALLBACK"))&&JN("ENABLE_QUALITY_FALLBACK"),E=!!JN("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(n=o.detail)||void 0===n?void 0:n[5]),m=xF({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:BN,browser:navigator.userAgent,process_id:JN("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:E||this.hasChangeBGPAddress,ap_response:o,extend:JN("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:s,attributes:{userAttributes:xF(xF({enableEncodedTransform:(!!JN("ENABLE_AUDIO_METADATA")||!!JN("ENABLE_AUDIO_PTS"))&&h||!!JN("ENABLE_AUDIO_TOPN")&&Sw(iw.CHROME,87,116)||void 0,enableAudioMetadata:!!JN("ENABLE_AUDIO_METADATA")&&h,enableAudioPts:!!JN("ENABLE_AUDIO_PTS")&&h,topnSmoothLevel:JN("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:JN("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:JN("TOPN_SWITCH_HOLD_MS"),topnAudioGain:JN("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:this.store.networkQualityProbe,enablePublishedUserList:JN("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:JN("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:NF("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:NF("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:NF("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===JN("USE_PUB_RTX")||!0===JN("USE_SUB_RTX")||void 0,disableFEC:JN("DISABLE_FEC"),enableNTPReport:!!JN("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:l,enableFulllinkAvSync:!!JN("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:NF("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!JN("FORCE_ENABLE_AUT_CC")||!HD()&&(!!JN("ENABLE_AUT_FEEDBACK")||void 0),rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!JN("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:NF("USE_XR","boolean"),enableLossbasedBwe:NF("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!JN("FORCE_ENABLE_AUT_CC")||!HD()&&(!!JN("ENABLE_AUT_CC")||void 0),enableCCF
5allback:NF("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:d,preSubNum:c?NF("PRE_SUB_NUM","number"):void 0,enablePubTWCC:NF("PUBLISH_TWCC","boolean"),enableSubTWCC:NF("SUBSCRIBE_TWCC","boolean"),enablePubRTX:NF("USE_PUB_RTX","boolean"),enableSubRTX:NF("USE_SUB_RTX","boolean"),enableSubSVC:JN("ENABLE_SVC")?JN("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(JN("SVC"))&&0!==JN("SVC").length?JN("SVC"):void 0,enableSvcExtended:JN("ENABLE_SVC")&&Array.isArray(JN("SVC_EXTENDED"))&&0!==JN("SVC_EXTENDED").length?JN("SVC_EXTENDED"):void 0,enableVosFallback:JN("ENABLE_VOS_FALLBACK"),enableQualityFallback:_},u),{},{audioDuplicate:NF("ENABLE_AUDIO_RED","boolean")?null!==(r=NF("AUDIO_DUPLICATE_NUM","number"))&&void 0!==r?r:2:void 0,senttsUsesAbsSendTime:!!p||void 0,enableDualStreamFlag:NF("ENABLE_DUAL_STREAM_FLAG","boolean")})},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(m.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(m.aes_mode=this.joinInfo.aesmode,JN("ENCRYPT_AES")?(m.aes_secret=this.joinInfo.aespassword,m.aes_encrypt=!0):m.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(m.aes_salt=this.joinInfo.aessalt)),o.addresses[this.signal.websocket.currentURLIndex]&&(m.ap_response.ticket=o.addresses[this.signal.websocket.currentURLIndex].ticket,delete o.addresses),void 0!==this.joinInfo.defaultVideoStream&&(m.default_video_stream=this.joinInfo.defaultVideoStream),m}getRejoinMessage(){if(!this.joinInfo)throw new FD(Bw.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(pV.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(pV.WS_RECONNECTING,(e=>{this.joinInfo&&xD.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||SO.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",xD.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0}
vendor: 113,724 bytes, lines 5-6
5,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(pV.WS_CLOSED,(e=>{let t;switch(e){case uO.LEAVE:t=SO.LEAVE;break;case uO.UID_BANNED:case uO.IP_BANNED:case uO.CHANNEL_BANNED:case uO.SERVER_ERROR:t=SO.SERVER_ERROR;break;case uO.FALLBACK:t=SO.FALLBACK;break;case uO.LICENSE_MISSING:case uO.LICENSE_EXPIRED:case uO.LICENSE_MINUTES_EXCEEDED:case uO.LICENSE_PERIOD_INVALID:case uO.LICENSE_MULTIPLE_SDK_SERVICE:case uO.LICENSE_ILLEGAL:case uO.TOKEN_EXPIRE:t=e;break;default:t=SO.NETWORK_ERROR}ND.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+SO.NETWORK_ERROR)),this.joinInfo&&xD.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===uO.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==uO.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(pV.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=JN("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(ND.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(xD.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,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),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 ND.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));XN("EVENT_REPORT_DOMAIN",e[1]),XN("EVENT_REPORT_BACKUP_DOMAIN",e[1]),XN("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(mV.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(pV.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new FD(Bw.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,RO(this,MV.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(pV.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n,r,o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const s=kO(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(JN("NEW_TURN_MODE")&&s&&"disabled"===(null===(r=this.joinInfo)||void 0===r?void 0:r.cloudProxyServer)){var a;let e=s.servers.map((e=>"turnServerURL"in e&&JN("USE_TURN_IP")?xF(xF({},e),{},{turnServerURL:Ux(e.turnServerURL)}):e)),t=null===(a=s.serversFromGateway)||void 0===a?void 0:a.map((e=>JN("USE_TURN_IP")?xF(xF({},e),{},{turnServerURL:Ux(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),ND.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const{iceParameters:c,dtlsParameters:d,rtpCapabilities:l}=await RO(this,MV.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer});try{e(this.getJoinMessage({ortc:{iceParameters:c,dtlsParameters:d,rtpCapabilities:l,version:"2"}}))}catch(e){t(e)}})),this.signal.on(pV.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(pV.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var r;e instanceof FD?(i=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,n=e.message):i=e;xD.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,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})})),this.signal.on(pV.IS_P2P_DISCONNECTED,(e=>{e(yO(this,MV.IS_P2P_DISCONNECTED))})),this.signal.on(pV.DISCONNECT_P2P,(()=>{this.emit(MV.DISCONNECT_P2P)})),this.signal.on(pV.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(pV.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(pV.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(MV.JOIN_RESPONSE,e,t)})),this.signal.on(pV.PRE_CONNECT_PC,(async(e,t)=>{if(this.joinInfo){var i,n;this.updateTurnConfigFromSignal();const o=this.getCurrentGatewayAddress(),s=kO(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(JN("NEW_TURN_MODE")&&s&&"disabled"===(null===(n=this.joinInfo)||void 0===n?void 0:n.cloudProxyServer)){var r;let e=s.servers.map((e=>"turnServerURL"in e&&JN("USE_TURN_IP")?xF(xF({},e),{},{turnServerURL:Ux(e.turnServerURL)}):e)),t=null===(r=s.serversFromGateway)||void 0===r?void 0:r.map((e=>JN("USE_TURN_IP")?xF(xF({},e),{},{turnServerURL:Ux(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),ND.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i,",in pre pc"))}const a=JN("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(o&&a){const i=aF(o);RO(this,MV.PRE_CONNECT_PC,{candidates:i,fingerprint:a,turnServer:s}).then((t=>{null==e||e(t)})).catch(t||(()=>{}))}}})),this.signal.on(pV.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof JN("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(JN("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(pV.VOS_FALLBACK,(e=>{this.emit(MV.VOS_FALLBACK,e)})),this.signal.on(pV.DATACHANNEL_FAILBACK,(e=>{ND.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(MV.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(_V.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(_V.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw ND.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(_V.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(_V.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw ND.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(_V.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===kV.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(_V.CONTROL,i,!0,!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===kV.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(_V.CONTROL,i,!0,!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===YV.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(_V.CONTROL,i,!0,!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===YV.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(_V.CONTROL,i,!0,!0)}catch(e){throw ND.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(_V.RESTART_ICE,t,!0)}catch(e){throw ND.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||SO.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!JN("GATEWAY_WSS_ADDRESS"))return JN("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(ND.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(_V.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(uO.FALLBACK)),this.store.useDcSignal=!1,this.signal=new Ox(xF(xF({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(MV.RESET_SIGNAL)}}let jF=0,GF=0;function WF(e,t,i,n){return new Wh(((r,o)=>{t.timeout=t.timeout||JN("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),jF+=GO(t.data)):i&&(t.data.size?jF+=t.data.size:t.data instanceof FormData?jF+=WO(t.data):jF+=GO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Xb.request(t).then((e=>{"string"==typeof e.data?GF+=GO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?GF+=e.data.byteLength:GF+=GO(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Xb.isCancel(e)?o(new FD(Bw.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new FD(Bw.NETWORK_TIMEOUT,e.message)):e.response?o(new FD(Bw.NETWORK_RESPONSE_ERROR,e.response.status)):o(new FD(Bw.NETWORK_ERROR,e.message))}))}))} 6/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function i(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e};var r,o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var i=0;i<e.length;++i){var n=e[i];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var i=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in i))break e;i=i[s]}(t=t(r=i[e=e[e.length-1]]))!=r&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t})}}function a(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:i(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,n(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var i="jscomp_symbol_"+(1e9*Math.random()>>>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<t.length;r++){var s=o[t[r]];"function"==typeof s&&"function"!=typeof s.prototype[e]&&n(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(i(this))}})}return e})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var d;e:{var l={};try{l.__proto__={a:!0},d=l.a;break e}catch(e){}d=!1}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var u=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function _(e,t){return e.h=3,{value:t}}function E(e){this.g=new h,this.G=e}function m(e,t,i,n){try{var r=t.call(e.g.j,i);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var o=r.value}catch(t){return e.g.j=null,e.g.s(t),f(e)}return e.g.j=null,n.call(e.g,o),f(e)}function f(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function S(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){p(e.g);var i=e.g.j;return i?m(e,"return"in i?i.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),f(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function g(e,t){return t=new S(new E(t)),u&&e.prototype&&u(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},E.prototype.o=function(e){return p(this.g),this.g.j?m(this,this.g.j.next,e,this.g.o):(this.g.o(e),f(this))},E.prototype.s=function(e){return p(this.g),this.g.j?m(this,this.g.j.throw,e,this.g.o):(this.g.s(e),f(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var i=0,n=!1,r={next:function(){if(!n&&i<e.length){var r=i++;return{value:t(r,e[r]),done:!1}}return n=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var T=function(e,t){for(var i=0;i<e.length;i++)t(e[i])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},C=function(e,t,i){return t instanceof Blob?(i=void 0!==i?String(i+""):"string"==typeof t.name?t.name:"blob",t.name===i&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],i)),[String(e),t]):[String(e),String(t)]},v=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},y="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,I=y.FormData,A=y.XMLHttpRequest&&y.XMLHttpRequest.prototype.send,b=y.Request&&y.fetch,w=y.navigator&&y.navigator.sendBeacon,O=y.Element&&y.Element.prototype,N=y.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in y&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){y.File=function(e,t,i){return e=new Blob(e,i||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),N&&Object.defineProperty(e,N,{value:"File"}),e}}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},P=function(e){this.i=[];var t=this;e&&T(e.elements,(function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var i=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];T(i,(function(i){t.append(e.name,i)}))}else"select-multiple"===e.type||"select-one"===e.type?T(e.options,(function(i){!i.disabled&&i.selected&&t.append(e.name,i.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(i="textarea"===e.type?R(e.value):e.value,t.append(e.name,i))}))};if((e=P.prototype).append=function(e,t,i){v(arguments,2),this.i.push(C(e,t,i))},e.delete=function(e){v(arguments,1);var t=[];e=String(e),T(this.i,(function(i){i[0]!==e&&t.push(i)})),this.i=t},e.entries=function e(){var t,i=this;return g(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=_(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){v(arguments,1);for(var i=c(this),n=i.next();!n.done;n=i.next()){var r=c(n.value);n=r.next().value,r=r.next().value,e.call(t,r,n,this)}},e.get=function(e){v(arguments,1);var t=this.i;e=String(e);for(var i=0;i<t.length;i++)if(t[i][0]===e)return t[i][1];return null},e.getAll=function(e){v(arguments,1);var t=[];return e=String(e),T(this.i,(function(i){i[0]===e&&t.push(i[1])})),t},e.has=function(e){v(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,i,n,r,o=this;return g(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,r=c(n),_(e,r.next().value));i=t.next(),e.h=2}))},e.set=function(e,t,i){v(arguments,2),e=String(e);var n=[],r=C(e,t,i),o=!0;T(this.i,(function(t){t[0]===e?o&&(o=!n.push(r)):n.push(t)})),o&&n.push(r),this.i=n},e.values=function e(){var t,i,n,r,o=this;return g(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,(r=c(n)).next(),_(e,r.next().value));i=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new I,t=c(this),i=t.next();!i.done;i=t.next()){var n=c(i.value);i=n.next().value,n=n.next().value,e.append(i,n)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,n){return"string"==typeof e?t.push(i+D(R(n))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(i+D(R(n))+'"; filename="'+D(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")})),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},P.prototype[Symbol.iterator]=function(){return this.entries()},P.prototype.toString=function(){return"[object FormData]"},O&&!O.matches&&(O.matches=O.matchesSelector||O.mozMatchesSelector||O.msMatchesSelector||O.oMatchesSelector||O.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),N&&(P.prototype[N]="FormData"),A){var L=y.XMLHttpRequest.prototype.setRequestHeader;y.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},y.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),A.call(this,e)):A.call(this,e)}}b&&(y.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),b.call(this,e,t)}),w&&(y.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),w.call(this,e,t)}),y.FormData=P}}();const HF=()=>{const e=JN("AREAS");0===e.length&&e.push(xV.GLOBAL);return Xn(e).call(e,((e,t,i)=>{const n=KF(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},KF=e=>e===xV.OVERSEA?"".concat(BV.ASIA,",").concat(BV.EUROPE,",").concat(BV.AFRICA,",").concat(BV.NORTH_AMERICA,",").concat(BV.SOUTH_AMERICA,",").concat(BV.OCEANIA):BV[e],YF=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=jV[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},zF={GLOBAL:{ASIA:[xV.CHINA,xV.JAPAN,xV.INDIA,xV.KOREA,xV.HKMC],EUROPE:[],NORTH_AMERICA:[xV.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},qF=Object.keys(zF[xV.GLOBAL]),XF=[xV.CHINA,xV.NORTH_AMERICA,xV.EUROPE,xV.ASIA,xV.JAPAN,xV.INDIA,xV.OCEANIA,xV.SOUTH_AMERICA,xV.AFRICA,xV.KOREA,xV.HKMC,xV.US],JF=function(e,t){let i=[];if(Dn(e).call(e,xV.GLOBAL)){const o=[xV.GLOBAL,xV.OVERSEA],s=Object.keys(jV);if(t===xV.GLOBAL)throw new FD(Bw.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===xV.CHINA)i=[xV.OVERSEA];else if(r=t,Dn(qF).call(qF,r)){const e=(n=t,zF[xV.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter((e=>!Dn(r).call(r,e)))}else if(function(e){let t=!1;return qF.forEach((i=>{var n;Dn(n=zF[xV.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return qF.forEach((i=>{var n;Dn(n=zF[xV.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 XF.forEach((i=>{Dn(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!Dn(XF).call(XF,e))))}(i)}else i=e;var n,r;return i};function QF(e){var t,i;if(!e&&Dn(t=JN("AREAS")).call(t,xV.EXTENSIONS))return ND.debug("update area from ap : reset"),void ZF(SU,!0);if(!Dn(i=JN("AREAS")).call(i,xV.GLOBAL)||!e)return;let n=jV.EXTENSIONS;n&&(n={CODE:KF(xV.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")]},ND.debug("update area from ap success: ".concat(e,",config is "),n),XN("AREAS",[xV.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){XN(e,n[e][0])}else XN(e,n[e])})))}function ZF(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=xD.reportApiInvoke(null,{name:aO.SET_AREA,options:e,tag:cO.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Dn(FV).call(FV,e))throw new FD(Bw.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new FD(Bw.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?JF(r,i):r}if(!t){if(ZN.AREAS){const e=new FD(Bw.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void ND.warning("setArea is prohibited because of config-distribute")}if(Dn(n).call(n,xV.GLOBAL)&&JN("AREAS")===xV.EXTENSIONS){const e=new FD(Bw.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void ND.warning("setArea is prohibited because of ap extensions")}}XN("AREAS",n,t);const r=YF(n);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){XN(e,r[e][0])}else XN(e,r[e])})),ND.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function $F(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 eB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?$F(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):$F(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let tB=1;function iB(e,t,i,n,r){tB+=1;const o={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:tB,requestId:tB,version:BN,cname:i.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return lN((async()=>{a=Date.now();const e=await WF(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 FD(Bw.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw ND.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new FD(Bw.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw ND.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new FD(Bw.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw ND.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(JN("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return JN("LIVE_STREAMING_ADDRESS")&&(r.addressList=JN("LIVE_STREAMING_ADDRESS")instanceof Array?JN("LIVE_STREAMING_ADDRESS"):[JN("LIVE_STREAMING_ADDRESS")]),eB(eB({},r),{},{responseTime:c})}),((n,r)=>(xD.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)=>(xD.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==Bw.OPERATION_ABORTED&&n.code!==Bw.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let nB=1;function rB(e,t,i,n){let{url:r,areaCode:o}=e;const{clientId:s,sid:a}=t,c=Date.now();let d;const l=t.role,[u,h]=dB(t,o,[Dx.CHOOSE_SERVER]);let p=IO.networkState;return lN((async()=>{p&&IO.networkState===gO.OFFLINE&&IO.onlineWaiter&&await Wh.race([IO.onlineWaiter,KO(n&&n.maxRetryTimeout||cN.maxRetryTimeout)]),p=IO.networkState;const{data:e,headers:o}=await WF(r,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===o.http3?1:-1,xD.reportResourceTiming(r,a),sB(e,r,t,c,[Dx.CHOOSE_SERVER],d);const s=jx(e,Dx.CHOOSE_SERVER);return aB(s),Vx(s,r)}),(e=>(e&&xD.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:h,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[Dx.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==Bw.OPERATION_ABORTED&&(e.code===Bw.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(xD.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:h,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[Dx.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),ND.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function oB(e,t,i,n){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),d=t.role,[l,u]=dB(t,s,a);let h;return lN((async()=>{h&&IO.networkState===gO.OFFLINE&&IO.onlineWaiter&&await Wh.race([IO.onlineWaiter,KO(n&&n.maxRetryTimeout||cN.maxRetryTimeout)]),h=IO.networkState;const{data:e,headers:s}=await WF(o,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,xD.reportResourceTiming(o,t.sid),sB(e,o,t,c,a,r);const d=jx(e,Dx.CHOOSE_SERVER),u=jx(e,"proxy5"===t.cloudProxyServer?Dx.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?Dx.CLOUD_PROXY:Dx.CLOUD_PROXY_FALLBACK),p=performance.getEntriesByName(o),_=p[p.length-1];let E;return _&&(E={name:_.name,protocol:"nextHopProtocol"in _?_.nextHopProtocol:"",dnscost:"domainLookupEnd"in _&&"domainLookupStart"in _&&"number"==typeof _.domainLookupEnd&&"number"==typeof _.domainLookupStart?_.domainLookupEnd-_.domainLookupStart:-1,tcpTlsCost:"connectEnd"in _&&"connectStart"in _&&"number"==typeof _.connectEnd&&"number"==typeof _.connectStart?_.connectEnd-_.connectStart:-1,reqCost:"requestStart"in _&&"number"==typeof _.requestStart&&"responseEnd"in _&&"number"==typeof _.responseEnd?_.responseEnd-_.requestStart:-1,handleCost:"leave_ts"in e&&"enter_ts"in e&&"number"==typeof e.leave_ts&&"number"==typeof e.enter_ts?e.leave_ts-e.enter_ts:-1}),aB(d),{gatewayInfo:Vx(d,o),proxyInfo:u,url:o,resourceTimingInfo:E}}),(e=>{var i;return e.gatewayInfo&&xD.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null===(i=e.gatewayInfo)||void 0===i?void 0:i.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&xD.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!==Bw.OPERATION_ABORTED&&(e.code===Bw.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(xD.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:h})}),ND.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const sB=(e,t,i,n,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=i,d=[],l=a=>{4096===a.flag?xD.joinChooseServer(s,{role:i.role,lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:a.error.message,csIp:a.error.data&&a.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:i.apRequestDetail}):1048576!==a.flag&&4194304!==a.flag&&4194310!==a.flag||xD.joinWebProxyAP(s,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:a.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)ND.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 FD(Bw.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:JN("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=px(i),r={error:new FD(Bw.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?ND.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw ND.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 FD(Bw.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)))]})},aB=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new FD(Bw.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});JN("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?QF(e.detail[23].toLowerCase()):QF());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;t<i.length;t++){var o;const n=dg(o=i[t]).call(o);e.addresses[t]&&i&&(e.addresses[t].fingerprint=n)}}if(JN("GATEWAY_ADDRESS")&&JN("GATEWAY_ADDRESS").length>0){ND.debug("assign gateway address to",JN("GATEWAY_ADDRESS"));const t=JN("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:t.fingerprint||r}}));e.addresses=t}},cB=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=px(t.buffer.code);throw new FD(Bw.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw ND.debug("update ticket request received ap response without response body:",t),new FD(Bw.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},dB=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r="host"===e.role?"1":"audience"===e.role?"2":void 0,o={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:eB(eB(eB({6:e.stringUid,11:t,12:JN("USE_NEW_TOKEN")?"1":void 0},r?{17:r}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};o.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 s=new FormData;return s.append("request",JSON.stringify(o)),[s,n]},lB=(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 uB=0;function hB(e){return Wh.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const pB=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 hB(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},_B=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 EB(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],r=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128],a=await new Wh(((a,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),a(!0)},error:e=>{clearTimeout(d),a(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,i,n,r,o,s];for(let t=0;t<c.length;t++){const i=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(i)}catch(e){return void a(!1)}}}(),d=setTimeout((()=>{a(!1)}),5e3)}));return a}async function mB(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=JN("WEBCS_DOMAIN").slice(0,JN("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:HF()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await pB({fragementLength:JN("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(ND.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),rB(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 KO(1e3),null!==r)return r;const s=JN("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:HF()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await pB({fragementLength:JN("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(ND.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),rB(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 hB([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 fB(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await mB(e,t,i,r);if(JN("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:o}=await CB(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||WN.tcpport,udpport:e.udpport||WN.udpport,username:e.username||WN.username,password:e.password||WN.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 nO(i),c=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||WN.tcpport,udpport:e.udpport||WN.udpport,username:i,password:r,forceturn:!1,security:!0})));a.push(...c)}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:n}}return await mB(e,t,i,r)}const{proxyInfo:a,gatewayInfo:c}=await CB(e,t,i,r),d={gatewayInfo:c},l=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:WN.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:WN.udpport,username:e.username||WN.username,password:e.password||WN.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 nO(i),r=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||WN.tcpport,udpport:"proxy4"===o?void 0:e.udpport||WN.udpport,username:i,password:n,forceturn:"proxy4"!==o,security:"proxy5"===o})));l.push(...r)}return e.turnServer={mode:"manual",servers:l},ND.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),d}async function SB(e,t,i,n,r){const o=JN("ACCOUNT_REGISTER").slice(0,JN("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 lN((()=>WF(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 ND.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),xD.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:Bw.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new FD(Bw.INVALID_UINT_UID_FROM_STRING_UID);return xD.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=px(i.code);return r.retry&&(a=e[(n+1)%e.length]),xD.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!==Bw.OPERATION_ABORTED&&(xD.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=px(c.code);throw new FD(Bw.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 gB(e,t,i){const n=JN("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 _B({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 WF(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=px(t.code);throw new FD(Bw.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new FD(Bw.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===Bw.OPERATION_ABORTED||e.code===Bw.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function TB(e,t,i){const n=JN("CDS_AP").slice(0,JN("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=sw(),o={flag:64,cipher_method:0,features:eB(eB(eB(eB(eB({install_id:FN(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:BN,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:Nx.WEB_RTC,browser_name:r.name,browser_version:r.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),r.os&&{os_name:r.os}),r.osVersion&&{os_version:r.osVersion}),{},{detail:""})};return lN((()=>WF(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==Bw.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,s=null,a={};try{o=await hB(r)}catch(e){if(e.code===Bw.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(xD.reportApiInvoke(e.sid,{name:aO.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=dg(i=e.slice(4)).call(i),o=JSON.parse(t[e]),s=o[1];n[r]={tag:o[0]||"",value:s}})),n}(o)}catch(e){}return a}async function RB(e,t){const i=JN("WEBCS_DOMAIN").concat(JN("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:HF(),serviceIds:[Dx.CHOOSE_SERVER,Dx.CLOUD_PROXY_FALLBACK]})));try{const n=await _B({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,{url:r,areaCode:o,serviceIds:s}=e;const a=Date.now(),[c,d]=dB(t,o,s);let l=IO.networkState;try{l&&IO.networkState===gO.OFFLINE&&IO.onlineWaiter&&await Wh.race([IO.onlineWaiter,KO(cN.maxRetryTimeout)]),l=IO.networkState;const{data:e,headers:t}=await WF(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 FD(Bw.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:JN("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:i.buffer.flag};t.push(n)}if(0!==n){const r=px(n),o={error:new FD(Bw.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?ND.warning(o.error.toString()):t.push(o)}})),t.length)throw new FD(Bw.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=jx(e,Dx.CHOOSE_SERVER),u=jx(e,Dx.CLOUD_PROXY_FALLBACK);return aB(s),{gatewayInfo:Vx(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===Bw.OPERATION_ABORTED||e.code===Bw.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function CB(e,t,i,n){const r=JN("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=JN("WEBCS_DOMAIN").slice(0,JN("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:HF(),serviceIds:[Dx.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Dx.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Dx.CLOUD_PROXY:Dx.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await pB({fragementLength:JN("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(ND.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),oB(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 KO(1e3),null!==s)return s;const r=JN("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:HF(),serviceIds:[Dx.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Dx.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Dx.CLOUD_PROXY:Dx.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await pB({fragementLength:JN("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(ND.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),oB(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 hB([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 FD(Bw.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,ND.setProxyServer(t),xD.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await Gx(u,l.uid)},s}async function vB(e,t,i){const n=JN("UAP_AP").slice(0,JN("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:BN,cname:t.cname,uid:t.uid.toString(),requestId:nB,seq:nB};nB+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return lN((async()=>{const t=await WF(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new FD(Bw.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw ND.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new FD(Bw.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw ND.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new FD(Bw.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw ND.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(JN("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(JN("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==Bw.OPERATION_ABORTED&&e.code!==Bw.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),n)}(n,e,t,i)));try{const e=await hB(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function yB(e,t,i){let n=null;const r=[],o=async o=>{const s=JN(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 KO(1e3),null!==n)?n:await pB({fragementLength:JN("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(ND.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=lB(t,[Dx.CHOOSE_SERVER]);let o=IO.networkState;return lN((async()=>{o&&IO.networkState===gO.OFFLINE&&IO.onlineWaiter&&await Wh.race([IO.onlineWaiter,KO(n&&n.maxRetryTimeout||cN.maxRetryTimeout)]),o=IO.networkState;const t=await WF(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return cB(t,e)}),(()=>!1),(e=>e.code!==Bw.OPERATION_ABORTED&&(e.code===Bw.UPDATE_TICKET_FAILED?e.data.retry:(ND.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 hB([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}function IB(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 AB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?IB(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):IB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class bB extends rO{get isSuccess(){return!!this.configs}constructor(e,t){super(),bI(this,"configs",void 0),bI(this,"store",void 0),bI(this,"joinInfo",void 0),bI(this,"cancelToken",void 0),bI(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),bI(this,"interval",void 0),bI(this,"mutex",void 0),bI(this,"mutableParamsRead",!1),bI(this,"configCache",{}),bI(this,"limit_bitrate",void 0),this.mutex=new sN("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),JN("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),JN("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;xD.reportApiInvoke(null,{options:void 0,name:aO.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:cO.TRACER}).onSuccess(JSON.stringify(ZN))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void ND.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await TB(this.joinInfo,this.cancelToken,this.retryConfig),ND.debug("[config-distribute] get config distribute",JSON.stringify(e));const i=function(e){var t;const i=qp(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<i.length;t++)for(let n=i.length-1;n>t;n--){const t=i[n],r=e[t].value;if("number"==typeof r.__priority){const o=r.__priority,s=i[n-1],a=e[s].value;if("number"==typeof a.__priority){if(!(o>a.__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=Date.now(),r={};return i.forEach((t=>{const i=e[t].value.__expires;i&&i<=n||(r[t]=e[t])})),r}(e);this.cacheGlobalParameterConfig(i),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=i}catch(e){const t=new FD(Bw.NETWORK_RESPONSE_ERROR,e);ND.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){WV(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(GV.UPDATE_BITRATE_LIMIT,e):this.emit(GV.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&AB({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},i=Object.keys(e),n=[];i.forEach((i=>{const r=e[i].value;t[i]=r;const o=r.__id;if(o&&this.configCache[i]&&this.configCache[i].__id===o)return;const s=r.__type,a=e[i].value,c=e[i].tag;let d=0;s?s===QN.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(zN,e)||!vU()&&Object.prototype.hasOwnProperty.call(HN,e)?(d=1,!0):void 0)),n.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(r)})})),n.forEach((e=>{let{tag:t,feature:i,params:n,isApplied:r}=e;this.store.sessionId&&xD.abTest(this.store.sessionId,{intSucc:1,isApplied:r,tag:t,feature:i,params:n,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){ND.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i].value,r=n.__expires,o=n.__type;Object.keys(n).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=AB(AB({value:n[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var i;const n=null===(i=t.LIMIT_BITRATE)||void 0===i?void 0:i.value;delete t.LIMIT_BITRATE,n&&WV(n)&&this.handleBitrateLimit(n),this.limit_bitrate=n,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{const{value:n,type:r,expires:o}=e[i];o&&o<=t||((r===QN.REALTIME||Object.prototype.hasOwnProperty.call(zN,i))&&(ZN[i]=n,qN[i]=n,ND.debug("Update realtime parameters from config distribute",i,n)),r||vU()||!Object.prototype.hasOwnProperty.call(HN,i)||(ZN[i]=n,qN[i]=n,ND.debug("Update gateway parameters from config distribute",i,n)))}))}catch(t){ND.error("Error update config immediately: ".concat(e),t.message)}}(t);const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),ND.debug("Caching global parameters ".concat(r))}catch(e){ND.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(qN,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;tN(qN[i],n)||(ZN[i]=n,qN[i]=n,this.emit(GV.UPDATE_CLIENT_ROLE_OPTIONS,n),ND.debug("Updating client role options: ".concat(JSON.stringify(n))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(qN,i)){var n;const{value:r,expires:o}=e[i];if(o&&o<=t)return;"number"==typeof r&&Dn(n=[0,1,4,5,6,7,8,9]).call(n,r)&&(ZN[i]={value:r},qN[i]=r,this.emit(GV.UPDATE_REMOTE_VIDEO_STREAM_TYPE,r),ND.debug("Updating client remote stream type: ".concat(JSON.stringify(r))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(qN,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;tN(qN[i],n)||(ZN[i]=n,qN[i]=n,this.emit(GV.FALLBACK_TO_HLS,n),ND.debug("Updating enable force hls: ".concat(JSON.stringify(n))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(qN,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;tN(qN[i],n)||(ZN[i]=n,qN[i]=n,this.emit(GV.UPDATE_VOS_CONFIGURE,n),ND.debug("Updating vos configure: ".concat(JSON.stringify(n))))}}}))}catch(e){ND.error("Error handling global parameter config:",e.message)}}}class wB extends rO{constructor(){super(...arguments),bI(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)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(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(JN("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(!n)return;n.result.push(i);const r="VIDEO_ENCODE_FAILED"===e?JN("ENCODE_EXCEPTION_TIMES"):5;if(n.result.length>=r){var o;const i=Dn(o=n.result).call(o,!0);n.isPrevNormal&&!i&&this.emit("exception",OB[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",OB[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 Sk&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=xx(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)}checResolutionSent(e){var t;return!(!e.codecType||Dn(t=JN("ENCODE_EXCEPTION_VALIDATE_CODEC")).call(t,e.codecType.toLocaleLowerCase()))||(!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof Sk&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const OB={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,VIDEO_ENCODE_FAILED:2004};const NB=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 DB(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 PB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?DB(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class LB{constructor(e){bI(this,"store",void 0),bI(this,"onStatsException",void 0),bI(this,"onUploadPublishDuration",void 0),bI(this,"onStatsChanged",void 0),bI(this,"onVideoCodecChanged",void 0),bI(this,"localStats",new Map),bI(this,"remoteStats",new Map),bI(this,"updateStatsInterval",void 0),bI(this,"trafficStats",void 0),bI(this,"trafficStatsPeerList",[]),bI(this,"uplinkStats",void 0),bI(this,"exceptionMonitor",void 0),bI(this,"p2pChannel",void 0),bI(this,"scalabilityMode",NN.L1T1),bI(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new wB,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(JV.LocalAudioTrack)||PB({},RP)}getLocalVideoTrackStats(){return this.localStats.get(JV.LocalVideoTrack)||PB({},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}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=Bx(this.trafficStats.B_unq),t=Bx(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality: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(JV.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(JV.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(JV.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?NB.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?NB.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&&ND.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 JV.LocalVideoTrack:case JV.LocalVideoLowTrack:{const t=n,s=PB({},CP),a=e.getStats(),c=e.getLocalMedia(i);if(a){const i=a.videoSend.find((e=>e.ssrc===(null==c?void 0:c.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),o=e.getEncoderConfig(JV.LocalVideoTrack);var r;if("H264"===i.codec||"H265"===i.codec||"VP8"===i.codec||"VP9"===i.codec||"AV1X"===i.codec||"AV1"===i.codec)if(s.codecType=i.codec,(null==t?void 0:t.codecType)!==i.codec)null===(r=this.onVideoCodecChanged)||void 0===r||r.call(this,i.codec.toLocaleLowerCase());s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),o&&o.bitrateMax?s.targetSendBitrate=1e3*o.bitrateMax:i.targetBitrate&&(s.targetSendBitrate=i.targetBitrate),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(ND.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var o;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(o=this.onStatsChanged)||void 0===o||o.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&c&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,c.track,s);break}case JV.LocalAudioTrack:{const t=n,r=PB({},RP),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(JV.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=PB({},vP),h=PB({},IP),p=PB({},yP),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let S;S=this.store.useP2P?e.getStats(!0):e.getStats();const g=null===(i=S)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===m)),T=null===(n=S)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===f)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(g&&("opus"!==g.codec&&"aac"!==g.codec&&"PCMU"!==g.codec&&"PCMA"!==g.codec&&"G722"!==g.codec||(u.codecType=g.codec),g.outputLevel?u.receiveLevel=Math.round(32767*g.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=g.bytes,u.receivePackets=g.packets,u.receivePacketsLost=g.packetsLost,u.receivePacketsDiscarded=g.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=g.jitterBufferMs,u.totalDuration>10&&LB.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),T){var C;"H264"!==T.codec&&"H265"!==T.codec&&"VP8"!==T.codec&&"VP9"!==T.codec&&"AV1X"!==T.codec&&"AV1"!==T.codec||(h.codecType=T.codec),h.receiveBytes=T.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=T.decodeFrameRate<0?0:T.decodeFrameRate,h.renderFrameRate=T.decodeFrameRate<0?0:T.decodeFrameRate,T.outputFrame&&(h.renderFrameRate=T.outputFrame.frameRate),T.receivedFrame?(h.receiveFrameRate=T.receivedFrame.frameRate,h.receiveResolutionHeight=T.receivedFrame.height,h.receiveResolutionWidth=T.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==T.framesRateFirefox&&(h.receiveFrameRate=Math.round(T.framesRateFirefox)),h.receivePackets=T.packets,h.receivePacketsLost=T.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost);const t=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=null!==(C=T.totalFreezesDuration)&&void 0!==C?C:t||0,h.receiveDelay=T.jitterBufferMs||0;const n=!!f&&e.getRemoteVideoIsReady(f);void 0===T.totalFreezesDuration&&E&&n&&LB.isRemoteVideoFreeze(E,T,l)&&(h.totalFreezeTime+=1),h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-t)/(h.totalDuration-i),1))}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:T,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h)}))}}class kB{constructor(){bI(this,"destChannelMediaInfos",new Map),bI(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){OV(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){OV(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){gV(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function MB(e){if(!(e instanceof kB)){return new FD(Bw.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new FD(Bw.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new FD(Bw.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class UB{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){bI(this,"uid",void 0),bI(this,"_uintid",void 0),bI(this,"_trust_in_room_",!0),bI(this,"_trust_audio_enabled_state_",!0),bI(this,"_trust_video_enabled_state_",!0),bI(this,"_trust_audio_mute_state_",!0),bI(this,"_trust_video_mute_state_",!0),bI(this,"_audio_muted_",!1),bI(this,"_video_muted_",!1),bI(this,"_audio_enabled_",!0),bI(this,"_video_enabled_",!0),bI(this,"_audio_added_",!1),bI(this,"_video_added_",!1),bI(this,"_is_pre_created",!1),bI(this,"_video_pre_subscribed",!1),bI(this,"_audio_pre_subscribed",!1),bI(this,"_trust_video_stream_added_state_",!0),bI(this,"_trust_audio_stream_added_state_",!0),bI(this,"_audioTrack",void 0),bI(this,"_videoTrack",void 0),bI(this,"_dataChannels",[]),bI(this,"_audioSSRC",void 0),bI(this,"_videoSSRC",void 0),bI(this,"_audioOrtc",void 0),bI(this,"_videoOrtc",void 0),bI(this,"_cname",void 0),bI(this,"_rtxSsrcId",void 0),bI(this,"_videoMid",void 0),bI(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function VB(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 xB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?VB(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):VB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const FB=e=>"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1 2\na=msid-semantic: WMS\na=ice-lite".concat(e?"\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\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:2\n"),BB="9",jB=2e4,GB=4e4;let WB=class{get localCapabilities(){return kO(this._localCapabilities)}get rtpCapabilities(){return kO(this._rtpCapabilities)}get candidates(){return kO(this._candidates)}get iceParameters(){return kO(this._iceParameters)}get dtlsParameters(){return kO(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];bI(this,"sessionDesc",void 0),bI(this,"_localCapabilities",void 0),bI(this,"_rtpCapabilities",void 0),bI(this,"_candidates",void 0),bI(this,"_originCandidates",void 0),bI(this,"_iceParameters",void 0),bI(this,"_isUseExtmapAllowMixed",void 0),bI(this,"_isUseLocalCodecs",void 0),bI(this,"_isUseDataChannel",void 0),bI(this,"_dtlsParameters",void 0),bI(this,"setup",void 0),bI(this,"currentMidIndex",void 0),bI(this,"cname",void 0),bI(this,"useLocalCodecsMids",[]),bI(this,"preloadSsrcs",[]),bI(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=i,this._isUseDataChannel=n,e=kO(e);const{iceParameters:r,dtlsParameters:o,candidates:s,rtpCapabilities:a,setup:c,localCapabilities:d,cname:l}=e;this._rtpCapabilities=a,this._candidates=s,this._originCandidates=kO(s),this._iceParameters=r,this._dtlsParameters=o,this._localCapabilities=d,this.setup=c,this.cname=l,[this.sessionDesc]=this.updateRemoteRTPCapabilities(a),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>{var t;return Dn(t=this.preloadSsrcs).call(t,e)}))}preloadRemoteMedia(e){let t=0;const i=[],n=[];for(;e>0;){const r=[xB({ssrcId:GB+t},JN("USE_SUB_RTX")?{rtx:GB+t+1}:{})],o="".concat(GB+t,"_").concat(jB+t),{ssrcs:s,ssrcGroups:a}=cF(r,this.cname,JN("SYNC_GROUP")?o:void 0),c=this.preCreateOrRecycleSendMedia("video",s,a,void 0),d=[{ssrcId:jB+t}],l="".concat(GB+t,"_").concat(jB+t),{ssrcs:u,ssrcGroups:h}=cF(d,this.cname,JN("SYNC_GROUP")?l:void 0),p=this.preCreateOrRecycleSendMedia("audio",u,h,void 0);e--,t+=2,i.push(c,p),n.push(s[0].ssrcId,u[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=n,{mids:i,preSSRCs:n,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,n){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;ND.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===YV.VIDEO?o.videoCodecs:o.audioCodecs,a=e===YV.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:BB,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:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,n),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return cD(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=cF(t,this.cname,JN("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(_w()&&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&&(hw()||function(){const e=sw();return!(e.name!==iw.CHROME||!e.osVersion)&&Number(e.version)<=90}()||mw(143)||gw(143)||JN("RESERVE_MID_1_MLINE")||JN("ENABLE_ENCODED_TRANSFORM")&&uw())||0===t&&!function(e){const t=sw();return!(t.name!==iw.FIREFOX||!t.osVersion)&&Number(t.version)===e}(138)&&JN("USE_SUB_RTX")||Aw()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=kO(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),_w()&&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||_w()||Aw()?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||aD((i=this._isUseExtmapAllowMixed,this._isUseDataChannel?FB(i):"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".concat(i?"\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")));var i;this._rtpCapabilities=e;let n=!1;const r=this.rtpCapabilities.send,o=this.localCapabilities.send,s=this.localCapabilities.recv,a=s.videoCodecs,c=s.audioCodecs,d=s.videoExtensions,l=s.audioExtensions;for(const e of t.mediaDescriptions){var u;if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!Dn(u=this.useLocalCodecsMids).call(u,e.attributes.mid)){if(n=!0,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(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var h;e.media.fmts=a.map((e=>e.payloadType.toString(10))),e.attributes.payloads=a,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||Dn(h=this.useLocalCodecsMids).call(h,t)||this.useLocalCodecsMids.push(t)}else if(0===r.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"vp8")}));0===t.length&&t.push(o.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.videoCodecs,e.attributes.extmaps=r.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var p;e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||Dn(p=this.useLocalCodecsMids).call(p,t)||this.useLocalCodecsMids.push(t)}else if(0===r.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.audioCodecs,e.attributes.extmaps=r.audioExtensions,TF(e)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,n]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(xB(xB({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case zV.TCP_RELAY:this._candidates=i;break;case zV.UDP_TCP_RELAY:case zV.RELAY:this._candidates=[...t,...i];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=kO(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<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((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(_w()){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:BB,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=RF(s,a,this.localCapabilities.send,s===YV.VIDEO?n:r),d=s===YV.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:BB,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}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),i=new Set(e.map((e=>e.fingerprint)));let n=!1;t.size!==i.size&&(n=!0);for(const e of t)i.has(e)||(n=!0);return n}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(eD)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return ND.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 ND.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(ND.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&&"video"===t.media.mediaType&&Dn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return ND.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(JN("USE_PUB_RTX")||JN("USE_SUB_RTX")){const e=CF(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=RF(YV.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));ND.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),ND.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===YV.VIDEO?s.videoCodecs:s.audioCodecs,c=e===YV.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:BB,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:this.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:"".concat(d)}};l=this.mungSendMediaDesc(l,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}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=kO(e);return lF(n),dF(n,t),uF(n,t),hF(n),pF(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=kO(e);return i.attributes&&i.attributes.payloads&&Array.isArray(i.attributes.payloads)&&i.attributes.payloads.length>0&&i.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&JN("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),pF(i,t,this.localCapabilities.recv),TF(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=>_w()?"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}getPtFromCodec(e){const t=this._rtpCapabilities.recv.audioCodecs.find((t=>{var i;if((null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)===e)return!0}));return null==t?void 0:t.payloadType}};function HB(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 KB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?HB(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):HB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var YB=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(YB||{});const zB=new Map;function qB(e,t,i,n){let{scale:r}=e;if(0===r&&n===YB.UP||r>=t.length-1&&n===YB.DOWN)return e;let o=KB(KB({},e),{},{scale:n===YB.DOWN?++r:--r});switch(i){case"maintain-framerate":o=KB(KB({},o),t[r].motion);break;case"maintain-resolution":o=KB(KB({},o),t[r].detail);break;case"balanced":o=KB(KB({},o),t[r].balanced)}return o}function XB(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:JB(t)};zB.set(e,i)}else zB.delete(e)}function JB(e){const t=KB({},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:m,BALANCE_RESOLUTION_FACTOR:f,MOTION_RESOLUTION_FACTOR:S,MOTION_BITRATE_FACTOR:g,DETAIL_FRAMERATE_FACTOR:T,DETAIL_BITRATE_FACTOR:R}=KN,C=Math.min(t.frameRate,a),v=[{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(f,e),frameRate:Math.max(Math.round(Math.pow(m,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(S,e),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(g,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(g,e)*o),d)},y={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(T,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)};v.push({scale:e,threshold:t,balanced:a,motion:c,detail:y})}return v}function QB(e,t,i,n,r,o){const s=zB.get(e)||{overUse:0,underUse:0,adaptationList:JB(r)},{adaptationList:a}=s;zB.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=KN,{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 JN("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[0].threshold.fps_down),e<r}(t,l,a,o)&&(s.overUse++,h=ON.CPU,s.overUse>c)||"number"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;const{threshold:{bwe_down:n}}=i[t];return e<n}(i,l,a)&&(s.overUse++,h=ON.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=qB(n,a,o,YB.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 JN("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=qB(n,a,o,YB.UP),0===u.scale&&(h=ON.NONE))),[u,h])}function ZB(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 $B(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ZB(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ZB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function ej(e){var t;return!!JN("ENABLE_AG_ADAPTATION")&&(!!(e instanceof lM||Dn(t=e._hints).call(t,hP.CUSTOM_TRACK))&&(!!JN("FORCE_SUPPORT_AG_ADAPTATION")||!!(Cw(14,0,!1)&&vw(17,4,!0)||Rw(14)&&yw(17,4,!0))))}const tj=new Map;function ij(e,t,i,n,r,o){if(nj(e,i),r(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;XB(e,t);const a=window.setInterval((()=>{const a=tj.get(e);if(!JN("ENABLE_AG_ADAPTATION")||!a)return nj(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]=QB(e,o,d,a.adaptationConfig,t,n);u&&(i.qualityLimitationReason=u),l&&a.adaptationConfig.scale!==l.scale&&(ND.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=$B($B({},a.adaptationConfig),l),r(l))}}),JN("CHECK_LOCAL_STATS_INTERVAL")),c=$B({},t);tj.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),ND.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}function nj(e,t){const i=tj.get(e);if(i){const{timer:t}=i;window.clearTimeout(t),tj.delete(e)}t.qualityLimitationReason=ON.NONE,XB(e)}function rj(e,t){var i;let n;switch(t){case JV.LocalAudioTrack:n=kV.Audio;break;case JV.LocalVideoTrack:n=Dn(i=e._hints).call(i,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:n=kV.Low}return n}function oj(e){const t=jD();if(e.some((e=>e._bypassWebAudio)))throw new jw(Bw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new jw(Bw.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function sj(e,t){oj(e);const i=t||new Sk;return e.forEach((e=>i.addAudioTrack(e))),i}const aj=!jD().supportUnifiedPlan||JN("CHROME_FORCE_PLAN_B")&&kw();function cj(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return i={spec:t,store:e},kF("DataChannelConnection").create(i);var i;const n=aj?function(e){return kF("PlanBConnection").create(e)}({spec:t,store:e}):new _j(t,e);return n}function dj(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function lj(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(hO(e.turnServer.servers))return!1;if(JN("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var uj;function hj(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 pj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hj(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let _j=(uj=class e extends KV{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(eD)).call(t,e)})))]}constructor(t,i){super(t,i),bI(this,"id",YO(5,"connection-")),bI(this,"store",void 0),bI(this,"peerConnection",void 0),bI(this,"forceTurn",!1),bI(this,"remoteSDP",void 0),bI(this,"initialOffer",void 0),bI(this,"transportEventReceiver",void 0),bI(this,"statsFilter",void 0),bI(this,"extension",{useXR:JN("USE_XR")}),bI(this,"localCapabilities",void 0),bI(this,"remoteCodecs",void 0),bI(this,"localCandidateCount",0),bI(this,"allCandidatesReceived",!1),bI(this,"isPreallocation",!1),bI(this,"isPreRender",!1),bI(this,"preMediaMap",new Map),bI(this,"dataStreamChannelMap",new Map),bI(this,"establishPromise",void 0),bI(this,"recoveredDataChannelIds",[]),bI(this,"currentDataChannelId",1),bI(this,"supportAV1RtpSpec",!1),bI(this,"mutex",void 0),bI(this,"qualityLimitationReason",ON.NONE),bI(this,"isFirstConnected",!1),this.store=i,this.forceTurn=lj(t),this.mutex=new sN("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=VN(this.peerConnection,JN("STATS_UPDATE_INTERVAL"),void 0,_w()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void ND.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 ND.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const i=rF(t.sdp),n=await mF({filterRTX:!JN("USE_PUB_RTX")&&!JN("USE_SUB_RTX"),filterVideoFec:JN("FILTER_VIDEO_FEC"),filterAudioFec:JN("FILTER_AUDIO_FEC"),filterVideoCodec:JN("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:JN("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:JN("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=gF(n),this.initialOffer=t,JN("ENABLE_SVC")&&"av1"==this.store.codec){const t=await EF();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=n.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&bF(t.sdp)&&(r=kO(n),Xx(r)),pj(pj({},i),{},{rtpCapabilities:r||n,offerSDP:t.sdp})}catch(e){throw new jw(Bw.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.initialOffer.sdp&&bF(this.initialOffer.sdp)&&Jx(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new WB(pj(pj({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!JN("ENABLE_PRE_SUB_WITH_PRE_PC")||!JN("PRE_USE_LOCAL_CODECS"))&&KD(this.store)),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=yF(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),KD(this.store))if(e.preallocation&&JN("ENABLE_PRE_SUB_WITH_PRE_PC")){const e=JN("PRE_SUB_NUM"),{mids:t,preSSRCs:i}=this.remoteSDP.preloadRemoteMedia(e);await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(i)),this.presetMedia(t,i)}else{const{preSSRCs:t=[]}=e,i=t.map((e=>e.ssrcMsg[0].ssrcId));if(0===t.length)return;const{mids:n}=this.remoteSDP.batchSend(t.map((e=>Object.assign({},e))));await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(n,i)}}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,i)=>{this.peerConnection.getTransceivers().forEach((n=>{if(null!=n.mid&&e===n.mid&&n.receiver.track){const r=n.receiver.track;let o;"video"===r.kind&&JN("ENABLE_PRE_RENDER")&&(o=new yk({trackId:"track-".concat(r.kind,"-unknown-").concat(this.store.clientId,"_").concat(YO(5,""))},!0),o.updateVideoTrack(r),o.onFirstVideoFrameRender=()=>{var e;const n=this.preMediaMap.get(t[i]);n&&(n.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[i])},o.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[i])},o.play(this.store.sessionId||void 0),this.isPreRender=!0),this.preMediaMap.set(t[i],{mid:e,track:r,player:o,transceiver:n})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1;const{rtpCapabilities:i}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const{preSSRCs:n=[]}=e,r=n.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(r)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((i=>{let[n,{mid:r,player:o,track:s}]=i;return e.push(r),t.push(n),this.preMediaMap.delete(n),o&&o.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await vF(this.peerConnection,this.remoteSDP,this.extension),ND.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),xD.reportApiInvoke(this.store.sessionId,{name:aO.PRELOAD_MEDIA_FAILED,options:[n,t],tag:cO.TRACER}).onSuccess()),n.length>0){const{mids:e}=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e))));await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(r)),this.presetMedia(e,r)}}t?(await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):ND.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return ub((function*(){const r=yield hb(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=zx();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,pj({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),_w()&&!0===JN("SIMULCAST")&&(yield hb(n.applySimulcastForFirefox(o,e)));const a=yield hb(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(a.sdp,e,c),l=aD(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return oF(t,JN("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield hb(n.stopSending(c,!0)),r}n.remoteSDP.receive(e,t,i,h);const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(n.applySimulcastEncodings(o,e)),yield hb(n.applySendEncodings(o,e)),null==_||_(p),yield hb(n.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=c[t];return{localSSRC:u[t],id:i,transceiver:e}}))}catch(e){throw e instanceof jw?e:new jw(Bw.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)ND.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:JN("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),ND.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else ND.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}
6catch(e){throw e instanceof jw?e:new jw(Bw.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 jw?e:new jw(Bw.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;nj(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 jw(Bw.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 vF(this.peerConnection,this.remoteSDP,this.extension),ND.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.");let a;return"audio"==e&&(a=this.remoteSDP.getPtFromCodec(this.store.audioCodec)),{track:s.receiver.track,id:r,pt:a,transceiver:s}}catch(e){throw new jw(Bw.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 vF(this.peerConnection,this.remoteSDP,this.extension),ND.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 jw(Bw.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.preMediaMap.entries()).some((t=>{let[i,{mid:n,player:r}]=t;if(n===e)return this.preMediaMap.delete(i),r&&r.destroy(),!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 jw(Bw.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 jw(Bw.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 jw(Bw.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=>
vendor: 6,189 bytes, line 6
6t.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 jw(Bw.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),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return ub((function*(){const i=yield hb(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=jD().supportPCSetConfiguration,r=JN("FORCE_TURN_TCP")||t.forceTurn;if(e===zV.RELAY&&!n)return;if(n&&!r){const i=e===zV.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(ND.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const o=yield hb(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=rF(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield hb(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield hb(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){ND.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(zV.TCP_RELAY),await vF(this.peerConnection,this.remoteSDP,this.extension)}catch(e){ND.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{nj(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let{player:t}=e;t&&t.destroy()})),this.preMediaMap.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 pj(pj({},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 jw(Bw.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)?_w()||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:pj(pj({},RN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:pj(pj({},RN),{},{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;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",r=Kx(e.url||"");ND.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(r||"",", host_c
6andidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),JN("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:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(hO(t.turnServer.servers)?i.iceServers=t.turnServer.servers:JN("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(JN("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),JN("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),JN("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),JN("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),JN("ENABLE_ENCODED_TRANSFORM")&&jD().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(Mx(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!JN("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}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=JN("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Mx(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Mx(e.turnServerURL),":443?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}
6=i.getSelectedCandidatePair()||{};if(e&&t){const i=e.address+":"+e.port,n=t.address+":"+t.port;ND.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Kx(i)),", remote ").concat(JSON.stringify(Kx(n))))}}}))}}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 ND.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return ND.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!jD().supportSetRtpSenderParameters)return ND.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=Yx(this.peerConnection,e._mediaStreamTrack),a=IL(e);if(ej(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,hP.CUSTOM_TRACK)?JN("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");ij(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,hP.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=xx(i)),n&&n>=1&&(o.scaleResolutionDownBy=n))}const{maxFramerate:l}=JN("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),JN("DSCP_TYPE")&&kw()){var u;const e=JN("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];_w()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),ND.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await AF(this.store.codec,t,JN("SVC_MODE"))}async updateAdaptation(e,t){var i,n;if(!e)return ND.debug("[updateAdaptation] no rtpSender found");if(!jD().supportSetRtpSenderParameters)return ND.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=xx(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),ND.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?ND.debug("[updateAdaptation] peerConnection not connected}"):ND.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):ND.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!jD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof dM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){ND.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){if(JN("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=aD(e);return t.forEach(((e,t)=>{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(dF(o,e),_F(o,e,this.store.codec))})),cD(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;a<e.length;a++){var i,n,r,o,s;const c=e[a],d=t[a];if(d instanceof dM&&!Dn(i=d._hints).call(i,hP.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>
vendor: 41,790 bytes, line 6
6200&&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(!_w()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof dM&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r,o;return!!(e instanceof dM&&JN("SIMULCAST")&&"vp8"===this.store.codec&&!Dn(t=e._hints).call(t,hP.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&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(JN("SDP_LOGGING"))return ND.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(jD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},sV(uj.prototype,"updateRemoteRTPCapabilities",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"updateRemoteRTPCapabilities"),uj.prototype),sV(uj.prototype,"connect",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"connect"),uj.prototype),sV(uj.prototype,"updateRemoteConnect",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"updateRemoteConnect"),uj.prototype),sV(uj.prototype,"createDataChannels",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"createDataChannels"),uj.prototype),sV(uj.prototype,"receive",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"receive"),uj.prototype),sV(uj.prototype,"batchReceive",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"batchReceive"),uj.prototype),sV(uj.prototype,"stopReceiving",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"stopReceiving"),uj.prototype),sV(uj.prototype,"muteRemote",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"muteRemote"),uj.prototype),sV(uj.prototype,"unmuteRemote",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"unmuteRemote"),uj.prototype),sV(uj.prototype,"muteLocal",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"muteLocal"),uj.prototype),sV(uj.prototype,"unmuteLocal",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"unmuteLocal"),uj.prototype),sV(uj.prototype,"close",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"close"),uj.prototype),sV(uj.prototype,"updateEncoderConfig",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"updateEncoderConfig"),uj.prototype),sV(uj.prototype,"updateSendParameters",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"updateSendParameters"),uj.prototype),sV(uj.prototype,"replaceTrack",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"replaceTrack"),uj.prototype),sV(uj.prototype,"updateAdaptation",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"updateAdaptation"),uj.prototype),sV(uj.prototype,"getRemoteSSRC",[Ej],Object.getOwnPropertyDescriptor(uj.prototype,"getRemoteSSRC"),uj.prototype),uj);function Ej(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<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function mj(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=xx(t.width),n.height=xx(t.height);const r=xx(t.framerate||15);document.body.append(i),document.body.append(n);let o=e._mediaStreamTrack;i.srcObject=new MediaStream([o]),i.play().catch(qO);const s=n.getContext("2d");if(!s)throw new FD(Bw.UNEXPECTED_ERROR,"can not get canvas context");const a=jD(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=n),n.startCapture=()=>{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&&(ND.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=zP((()=>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),ND.debug("clean low stream renderer")},c}var fj=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(fj||{}),Sj=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(Sj||{}),gj=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(gj||{}),Tj=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e[e.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",e}(Tj||{}),Rj=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Rj||{}),Cj=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(Cj||{}),vj=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(vj||{});const yj=1e3,Ij=6,Aj=3,bj=Math.max(Ij,Aj,60);function wj(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function Oj(e){const t={[Rj.CONN_TYPE]:0,[Rj.RTT]:e.rtt,[Rj.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[Rj.CONN_TYPE]=1),"tcp"===i&&(t[Rj.CONN_TYPE]=3),"tls"===i&&(t[Rj.CONN_TYPE]=4);break}case"srflx":t[Rj.CONN_TYPE]=2;break;case"unknown":t[Rj.CONN_TYPE]=5;break;default:t[Rj.CONN_TYPE]=0}return t}function Nj(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 Dj extends rO{constructor(e){super(),bI(this,"store",void 0),bI(this,"uploadWRTCStatsTimer",void 0),bI(this,"uploadOutboundDenoiserStatsTimer",void 0),bI(this,"uploadExtStatsTimer",void 0),bI(this,"uploadExtUsageStatsTimer",void 0),bI(this,"uploadInboundExtStatsTimer",void 0),bI(this,"requestStats",void 0),bI(this,"requestTransportStats",void 0),bI(this,"requestLocalMedia",void 0),bI(this,"requestRemoteMedia",void 0),bI(this,"requestAllTracks",void 0),bI(this,"requestVideoIsReady",void 0),bI(this,"requestUploadStats",void 0),bI(this,"requestUpload",void 0),bI(this,"uploadOutboundStarted",!1),bI(this,"uploadInboundStarted",!1),bI(this,"uploadTransportStarted",!1),bI(this,"uploadBaseStatsStarted",!1),bI(this,"uploadExtensionUsageStarted",!1),bI(this,"lastRecvStats",void 0),bI(this,"lastSendStats",void 0),bI(this,"lastRefRecvStats",void 0),bI(this,"lastRefSendStats",void 0),bI(this,"lastNormalRecvStats",void 0),bI(this,"lastNormalSendStats",void 0),bI(this,"lastExtendStats",{}),bI(this,"needUploadStats",{}),bI(this,"needUploadRenderFreezeTime",!0),bI(this,"lastUploadCompensateTime",-1),bI(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%Aj==0,i=e%Ij==0,n=e%60==0;let r,o;if(this.uploadTransportStarted&&(r=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!r&&this.uploadOutboundStarted&&(r=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),r||o){var s;const a={};if(this.uploadTransportStarted&&r){const e=this.getTransportStats(r,t?this.lastRefSendStats:void 0,o,t);e&&(a.misc=[e])}if(this.uploadOutboundStarted&&r){const e=this.getOutboundStats(r,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,n);e&&(a.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const n=this.getInboundStats(o,i?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);n&&(a.inbound=n)}const c=null===(s=this.requestTransportStats)||void 0===s?void 0:s.call(this).connectState;if(c&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Cj.RTC_PEER_CONNECTION_STATE]=DN[c]):a.misc=[{addition:{[Cj.RTC_PEER_CONNECTION_STATE]:DN[c]}}]),OM.needUploadStats.length>0||i){const e=OM.needUploadStats.shift()||("visible"===OM.visibility?1:0);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Cj.PAGE_VISIBILITY]=e):a.misc=[{addition:{[Cj.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[fj.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,i&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,OM.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,i;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(i=this.requestUploadStats)||void 0===i||i.call(this,{misc:[{addition:{[Cj.RTC_PEER_CONNECTION_STATE]:DN[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===bj+1&&(e=1)}),yj)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%Aj==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const n=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*n;const r=this.requestStats(!0);new Array(n).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&r){const t=this.requestRemoteMedia()||[],i=[];t.forEach((e=>{let[t,n]=e;const o={peer:t.uid};if((t._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(t._videoSSRC)||!1)&&n.has(YV.VIDEO)&&t.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const n={};if(i&&i._player){const e=i._player,{renderFreezeAccTime2:t,videoElementStatus:r}=e;if("visible"===OM.visibility&&r===NP.PLAYING&&jD().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),wj(n,Sj.Video_Render_Freeze_Time_Render2,i),JN("USE_NEW_RENDER_FREEZE_TIME")&&wj(n,Sj.Video_Render_Freeze_Time_Render,i)}}return n}(t._videoSSRC,r,t.videoTrack);e&&(o.video=e)}o.video&&i.push(o)})),i.length>0&&(e.inbound=i,this.requestUploadStats(e))}}))}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),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,i,n){if(!this.requestStats)return;if(!n)return null==e.rtt?void 0:{addition:{[Rj.RTT]:e.rtt,[Rj.CONN_TYPE]:void 0,[Rj.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=Oj(e);if(this.store.useP2P){if(i){const e=Oj(i);r[Rj.CONN_TYPE]&&e[Rj.CONN_TYPE]&&(r[Rj.CONN_TYPE]+=e[Rj.CONN_TYPE]<<3)}r[Rj.CONN_TYPE]?r[Rj.CONN_TYPE]+=110:r[Rj.CONN_TYPE]=110}else{r[Rj.CONN_TYPE]?r[Rj.CONN_TYPE]+=100:r[Rj.CONN_TYPE]=100;const i=function(e,t){if(t)return[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))];return[0,0]}(e,t);r[vj.Transport_Send_Bitrate]=i[0],r[vj.Transport_Recv_Bitrate]=i[1]}return{addition:r}}getOutboundStats(e,t,i,n,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||0===o.length)return;let s,a,c;return o.forEach((n=>{let[o,{track:d,ssrcs:l}]=n;switch(o){case JV.LocalVideoLowTrack:case JV.LocalVideoTrack:if(o===JV.LocalVideoTrack){var u;const n=function(e,t,i,n,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},{sentFrame:c,inputFrame:d}=s;if(n&&(wj(a,Sj.Video_Send_Qp_Sum,s.qpSumPerFrame),d&&c)){const e=d.frameRate,t=c.frameRate;a[Sj.Video_Send_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(r){switch(c&&(wj(a,gj.Video_Send_Height,c.height),wj(a,gj.Video_Send_Width,c.width),wj(a,gj.Video_Send_Frame_Rate,c.frameRate)),a[gj.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[gj.Video_Send_Adaptation]=0;break;case"cpu":a[gj.Video_Send_Adaptation]=1;break;case"bandwidth":a[gj.Video_Send_Adaptation]=2;break;case"other":a[gj.Video_Send_Adaptation]=3}let n=0;s.adaptionChangeReason&&(n+=Nj(s.adaptionChangeReason)),t.qualityLimitationReason&&(n+=Nj(t.qualityLimitationReason)<<3),a[gj.Video_Send_Adaptation]=n,a[gj.Video_Send_Player_Status]=PP[i._player?i._player.videoElementStatus:"uninit"],wj(a,gj.Video_Send_Nacks,s.nacksCount),wj(a,gj.Video_Send_Plis,s.plisCount),wj(a,gj.Video_Send_Firs,s.firsCount),wj(a,gj.Video_Send_Avg_Encode,s.avgEncodeMs),wj(a,gj.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),wj(a,gj.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),wj(a,gj.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),wj(a,gj.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const o=r.videoSend.find((t=>t.ssrc===e));if(o){let e=yj*Aj;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.packets&&null!=s.packets&&wj(a,gj.Video_Send_Package_Rate,1e3*(s.packets-o.packets)/e),null!=s.packetsLost&&null!=o.packetsLost&&wj(a,gj.Video_Send_Package_Lost,s.packetsLost-o.packetsLost),null!=o.bytes&&null!=s.bytes&&wj(a,gj.Video_Send_Bitrate,8*(s.bytes-o.bytes)/e)}}return a}(l[0].ssrcId,e,d,t,i),o="CameraVideoTrack"===d.__className__?3:Dn(u=d._hints).call(u,hP.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||r)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o);const s=d&&function(e,t,i,n){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(n){const e=r.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,s=e&&e.frameRate||0;wj(o,gj.Video_Capture_Height,t),wj(o,gj.Video_Capture_Width,n),wj(o,gj.Video_Capture_Frame_Rate,s)}return o}(l[0].ssrcId,e,d,!!i),c=function(e,t){const i={};return t&&(wj(i,gj.Video_Send_Retransmit,e.bitrate.retransmit),wj(i,gj.Video_Send_Target_Encoded,e.bitrate.targetEncoded),wj(i,gj.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),wj(i,gj.Video_Send_Transmit,e.bitrate.transmit),wj(i,gj.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);a=Object.assign({},n,s,c)}else c=function(e,t,i,n,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(n){const t=o.sentFrame;t&&(wj(s,gj.Video_Send_Low_Height,t.height),wj(s,gj.Video_Send_Low_Width,t.width),wj(s,gj.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=yj*Ij;i.timestamp&&o.timestamp&&(e=o.timestamp-i.timestamp),null!=i.packets&&null!=o.packets&&wj(s,gj.Video_Send_Low_Package_Rate,1e3*(o.packets-i.packets)/e),null!=o.packetsLost&&null!=i.packetsLost&&wj(s,gj.Video_Send_Low_Package_Lost,o.packetsLost-i.packetsLost),null!=i.bytes&&null!=o.bytes&&wj(s,gj.Video_Send_Low_Bitrate,8*(o.bytes-i.bytes)/e)}}return s}(l[0].ssrcId,e,0,i);break;case JV.LocalAudioTrack:s=d&&function(e,t,i,n,r,o){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(r){a[gj.Audio_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0;const t=100*i._source.getAccurateVolumeLevel(),n=s.inputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));wj(a,gj.Audio_Send_Level,e)}wj(a,gj.Audio_Capture_PCM_Level,t),wj(a,gj.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),wj(a,gj.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),wj(a,gj.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),wj(a,gj.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),a[gj.Audio_Send_Freeze]=0;const o=r.audioSend.find((t=>t.ssrc===e));if(o){let e=yj*Ij;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.bytes&&null!=s.bytes&&wj(a,gj.Audio_Send_Bitrate,8*(s.bytes-o.bytes)/e),null!=o.packets&&null!=s.packets&&wj(a,gj.Audio_Send_Package_Rate,1e3*(s.packets-o.packets)/e)}}return a}(l[0].ssrcId,e,d,0,i)}})),{high:a,low:c,audio:s}}getInboundStats(e,t,i,n){if(!this.requestRemoteMedia)return;const r=this.requestRemoteMedia()||[],o=[];return r.forEach((r=>{let[s,a]=r;const c={peer:s.uid};let d;if(a.has(YV.VIDEO)&&s.videoTrack){const r=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,o=s.videoTrack?function(e,t,i,n,r,o,s,a){const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},{receivedFrame:l,outputFrame:u,decodeFrameRate:h}=c;wj(d,Tj.Video_Render_Frame_Rate_Decode,h),c.framesRateFirefox&&wj(d,Tj.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&wj(d,Tj.Video_Recv_Frame_Rate,l.frameRate),wj(d,Tj.Video_Recv_Frame_Dropped,c.framesDroppedCount),wj(d,Tj.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),wj(d,Tj.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),wj(d,Tj.Video_Recv_Packages_Discarded,c.packetsDiscarded),wj(d,Tj.Video_Recv_Avg_Decode,c.avgDecodeMs),wj(d,Tj.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),wj(d,Tj.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),wj(d,Tj.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),wj(d,Tj.Video_Recv_Key_Frames_Decoded,c.keyFramesDecoded);const p=a&&a.videoRecv.find((t=>t.ssrc===e));if(p){const e=t.timestamp-a.timestamp||yj;null!=c.packetsLost&&null!=p.packetsLost&&wj(d,Tj.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&wj(d,Tj.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&wj(d,Tj.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}const _=o&&o.videoRecv.find((t=>t.ssrc===e));if(_&&(wj(d,Sj.Video_Recv_Qp_Sum,c.qpSumPerFrame),d[Sj.Video_Recv_Freeze]=n&&LB.isRemoteVideoFreeze(i,c,_)?1:0),s){var E;const t=s.videoRecv.find((t=>t.ssrc===e));l?(wj(d,gj.Video_Recv_Height,l.height),wj(d,gj.Video_Recv_Width,l.width)):i&&(wj(d,gj.Video_Recv_Height,i._videoHeight||0),wj(d,gj.Video_Recv_Width,i._videoWidth||0)),u&&wj(d,gj.Video_Recv_Frame_Rate_Output,u.frameRate);const n=null===(E=i._player)||void 0===E?void 0:E.rendFrameRate.toFixed(0);if(n&&wj(d,gj.Video_Render_Frame_Rate_Render,+n),wj(d,gj.Video_Recv_Jitter_Buffer,c.jitterBufferMs),wj(d,gj.Video_Recv_Current_Delay,c.currentDelayMs),wj(d,gj.Video_Recv_Firs,c.firsCount),wj(d,gj.Video_Recv_Nacks,c.nacksCount),wj(d,gj.Video_Recv_Plis,c.plisCount),i){d[gj.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const{freezeTimeCounterList:i,renderFreezeAccTime:n,renderFreezeAccTime2:o,videoElementStatus:s}=e;if(i&&i.length>0&&wj(d,Sj.Video_Render_Freeze_Time,i.splice(0,1)[0]),r&&"visible"===OM.visibility&&s===NP.PLAYING&&jD().supportRequestVideoFrameCallback){const t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),wj(d,Sj.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,n);e.renderFreezeAccTime=Math.max(0,n-i),wj(d,Sj.Video_Render_Freeze_Time_Render,JN("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof c.totalFreezesDuration){const e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;wj(d,gj.Video_Render_Freeze_Duration,1e3*e)}}}if(d[gj.Video_Recv_Player_Status]=PP[i._player?i._player.videoElementStatus:"uninit"],t&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-t.totalInterFrameDelay,i=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=c.framesDecodeCount-t.framesDecodeCount,r=e/n*1e3,o=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(o)&&r+o>Math.max(3*r,r+150)&&(d[gj.Video_Recv_I_Frame_Delay]=o)}}return d}(s._videoSSRC,e,s.videoTrack,!0===r,this.needUploadRenderFreezeTime,t,i,n):void 0;if(o&&(c.video=o),s.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===s._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(d=t.estimatedPlayoutTimestamp)}}if(a.has(YV.AUDIO)&&s.audioTrack){const r=s.audioTrack?function(e,t,i,n,r,o){const s=t.audioRecv.find((t=>t.ssrc===e));if(!s)return;const a={};wj(a,Tj.Audio_Recv_Jitter,s.jitterMs),wj(a,Tj.Audio_Recv_Bytes_Retransmit,s.retransmittedBytesReceived),wj(a,Tj.Audio_Recv_Packages_Retransmit,s.retransmittedPacketsReceived),wj(a,Tj.Audio_Recv_Packages_Discarded,s.packetsDiscarded),wj(a,Tj.Audio_Recv_Avg_Processing_Delay,s.avgProcessingDelayMs);const c=o&&o.audioRecv.find((t=>t.ssrc===e));if(c){const e=yj;null!=s.packets&&null!=c.packets&&wj(a,Tj.Audio_Recv_Package_Rate,1e3*(s.packets-c.packets)/e),null!=s.packetsLost&&null!=c.packetsLost&&wj(a,Tj.Audio_Recv_Package_Lost,s.packetsLost-c.packetsLost)}if(n){const{receivedFrames:e,droppedFrames:t}=s;null!=e&&null!=t&&(a[Sj.Audio_Recv_Freeze]=0===(d=e)||100*t/d>20?1:0)}var d;if(r){const t=100*i._source.getAccurateVolumeLevel(),n=s.outputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));wj(a,gj.Audio_Render_Level,e)}wj(a,gj.Audio_Recv_PCM_Level,t),i&&(a[gj.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),wj(a,gj.Audio_Recv_Jitter_Buffer,s.jitterBufferMs),wj(a,gj.Audio_Recv_Current_Delay,s.jitterBufferMs),a[gj.Audio_Recv_Player_Status]=PP[pL.getPlayerState(i.getTrackId())];const o=r.audioRecv.find((t=>t.ssrc===e));if(o){null!=o.bytes&&null!=s.bytes&&wj(a,gj.Audio_Recv_Bitrate,8*(s.bytes-o.bytes)/(yj*Aj));const e=s.concealedSamples-o.concealedSamples;e>0&&wj(a,gj.Audio_Recv_Concealed_Samples,e);const t=s.totalSamplesReceived-o.totalSamplesReceived;t>0&&wj(a,gj.Audio_Recv_Total_Samples_Received,t);const i=s.freezeSamples80-o.freezeSamples80;i>0&&wj(a,gj.Audio_Render_Freeze_Samples_80ms,i);const n=s.freezeSamples200-o.freezeSamples200;n>0&&wj(a,gj.Audio_Render_Freeze_Samples_200ms,n);const r=s.freezeMs80-o.freezeMs80;wj(a,gj.Audio_Render_Freeze_Time_80ms,r<0?0:r);const c=s.freezeMs200-o.freezeMs200;wj(a,gj.Audio_Render_Freeze_Time_200ms,c<0?0:c)}}return a}(s._audioSSRC,e,s.audioTrack,t,i,n):void 0;if(r&&(c.audio=r),s.audioTrack&&d){const t=e.audioRecv.find((e=>e.ssrc===s._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-d;c.audio?c.audio[Tj.Audio_Recv_AV_Sync_TIME]=e:c.audio={[Tj.Audio_Recv_AV_Sync_TIME]:e}}}}(c.video||c.audio)&&o.push(c)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,o}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 mk));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(EV.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.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=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(YV.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(YV.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),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=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:JN("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(YV.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(YV.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+JN("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(EV.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a})}),JN("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,OM.stopCollectStats()}}const Pj=JN("ICE_RESTART_INTERVAL");let Lj=new Map,kj=new Map,Mj=[zV.UDP_TCP_RELAY,zV.TCP_RELAY,zV.RELAY],Uj=JN("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&jD().supportPCSetConfiguration;function Vj(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=Lj.get(e.id);i&&(window.clearTimeout(i),Lj.delete(e.id));const n=kj.get(e.id);t&&n&&n.index===Mj.length-1&&(ND.debug("[".concat(e.id,"] reset ICE restart policy")),kj.delete(e.id))}function xj(e,t,i){if(0===Lj.size&&0===kj.size&&(Array.isArray(JN("RESTART_SEQUENCE"))&&JN("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){const n=e[i];if(e.filter((e=>e===n)).length!==t.filter((e=>e===n)).length)return!1}return!0}(Mj,JN("RESTART_SEQUENCE"))&&(Mj=JN("RESTART_SEQUENCE").filter((e=>{var t;if(Dn(t=Object.values(zV)).call(t,e))return!0})),ND.debug("use reconnection policy from config distribution, queues: ".concat(Mj.join(" => ")))),Uj=JN("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&jD().supportPCSetConfiguration),0===Mj.length)return void i();let n,{index:r=0,type:o}=kj.get(e.id)||{};if(Uj&&o===zV.RELAY)return void i();let s=o&&r>=Mj.length-1;if(Uj)o=zV.RELAY;else{if(s)return void i();o?(r++,o=Mj[r]):(o=Mj[0],r=0)}ND.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(o,", index: ").concat(r)),t(o),kj.set(e.id,{index:r,type:o}),n=window.setTimeout((()=>xj(e,t,i)),Pj),Lj.set(e.id,n)}var Fj;function Bj(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 jj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Bj(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Bj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Gj(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=_b,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new Wj(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Wj(e){function t(e){if(Object(e)!==e)return Wh.reject(new TypeError(e+" is not an object."));var t=e.done;return Wh.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Wj=function(e){this.s=e,this.n=e.next},Wj.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Wh.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Wh.reject(e):t(i.apply(this.s,arguments))}},new Wj(e)}let Hj=(Fj=class extends rO{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(ZV.StateChange,t,this._state)}constructor(e,t){super(),bI(this,"isPlanB",void 0),bI(this,"store",void 0),bI(this,"statsUploader",void 0),bI(this,"connection",void 0),bI(this,"localTrackMap",new Map),bI(this,"remoteUserMap",new Map),bI(this,"localDataChannels",[]),bI(this,"remoteDataChannelMap",new Map),bI(this,"pendingLocalTracks",[]),bI(this,"pendingRemoteTracks",[]),bI(this,"pendingLocalDataChannels",[]),bI(this,"pendingRemoteDataChannels",[]),bI(this,"statsCollector",void 0),bI(this,"shouldForwardP2PCreation",void 0),bI(this,"iceFailedCount",0),bI(this,"dtlsFailedCount",0),bI(this,"mutex",void 0),bI(this,"_state",QV.Disconnected),bI(this,"_pcStatsUploadType",JN("NEW_ICE_RESTART")?qV.FIRST_CONNECTION:qV.OLD_FIRST_CONNECTION),bI(this,"_isStartRestartIce",!1),bI(this,"_restartTimer",void 0),bI(this,"_isTryConnecting",!1),bI(this,"_iceError",null),bI(this,"_forceTurn",!1),bI(this,"_isWaitPcToRePub",!1),bI(this,"handleMuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==QV.Connected)return void i(new jw(Bw.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){const e=o[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,ND.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?ND.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(r);await CO(this,ZV.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==QV.Connected)return void i(new jw(Bw.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(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,ND.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=mj(e,yO(this,ZV.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}this.store.enableInstantMuteRestore?ND.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender be
6cause enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r);await CO(this,ZV.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleUpdateVideoEncoder",(async(e,t,i,n)=>{let r;n||(r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(JV.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==QV.Connected)return void t();const{id:n,track:s}=i;await this.connection.updateSendParameters(n,s),await this.connection.updateEncoderConfig(n,s),this.emit(ZV.UpdateVideoEncoder,s),t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),bI(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(JV.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==QV.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleReplaceMixingTrack",(async(e,t,i,n)=>{if(!this.connection||this.state!==QV.Connected)return void t();const r=sj([e]);let o;ND.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()}})),bI(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;ND.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!==QV.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]===JV.LocalVideoTrack&&!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding){const t=this.localTrackMap.get(JV.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),bI(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),bI(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),bI(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),bI(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),bI(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Dj(this.store),this.bindStatsUploaderEvents(),this.mutex=new sN("P2PChannel-mutex",this.store.clientId),this.isPlanB=!jD().supportUnifiedPlan||JN("CHROME_FORCE_PLAN_B")&&kw(),this.shouldForwardP2PCreation=JN("FORWARD_P2P_CREATION")&&jD().supportPCSetConfiguration&&Lw(),this.shouldForwardP2PCreation&&(this.connection=cj(this.store),this.emit(ZV.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){var i;this.state=QV.New,this._forceTurn=lj(e),ND.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if((!this.shouldForwardP2PCreation||n||t)&&((n||t)&&this.connection&&(ND.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=cj(this.store,e),this.emit
6(ZV.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new jw(Bw.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=JN("NEW_ICE_RESTART")?qV.FIRST_CONNECTION:qV.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e){if(!this.connection)throw new jw(Bw.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==QV.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=QV.Connected,t}if(this.connection instanceof _j){if(this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints)){ND.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, try next."));return xD.reportApiInvoke(this.store.sessionId,{name:aO.MISMATCH_DTLS_PARAMETERS,options:[e.dtlsParameters.fingerprints],tag:cO.TRACER}).onSuccess(),void setTimeout((()=>{this.emit(ZV.RequestReconnect)}))}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[i]=e;return Dn(t=[JV.LocalVideoLowTrack,JV.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 _j||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(xD.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,ND.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default co
6dec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof _j&&"closed"!==this.connection.peerConnectionState&&Dn(e=[QV.New,QV.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==QV.Connected){if(this.state===QV.Disconnected)throw new jw(Bw.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 ub((function*(){const r=yield hb(n.mutex.lock("From P2PChannel.publish"));try{var o;const s=n.connection&&Dn(o=["disconnected","failed"]).call(o,n.connection.peerConnectionState);if(!n.connection||n.state!==QV.Connected||s){if(n.state===QV.Disconnected)throw new jw(Bw.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return n.pendingLocalTracks=n.pendingLocalTracks.concat(t),void(s&&(n._isWaitPcToRePub=!0))}n.store.pubId=n.store.pubId+1,NB.markPublishStart(n.store.clientId,n.store.pubId);const a=n.filterTobePublishedTracks(e,t,i);if(0===a.length)return void(yield hb(n.tryToUnmuteAudio(e)));yield*pb(Gj(n.doPublish(n.connection,a)))}finally{r()}}))()}doPublish(e,t){var i=this;return ub((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===JV.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),r=yield hb(e.send(n,i.store.codec,i.store.audioCodec)),o=(yield hb(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)===Bw.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,n),d=(yield hb(r.next(c))).value;if(i.state===QV.Disconnected)throw new jw(Bw.UNEXPECTED_ERROR,"PeerConnection already disconnected.");JN("ENABLE_VIDEO_SEI");const l=JN("ENABLE_ENCODED_TRANSFORM"),u=JN("ENABLE_AUDIO_METADATA"),h=JN("ENABLE_AUDIO_PTS");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const{interceptLocalVideoFrame:i,interceptLocalAudioFrame:n}=UF();e.trackMediaType===YV.VIDEO?await i(t.sender,e):e.trackMediaType===YV.AUDIO&&await n(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0,pts:h?()=>e.pts.shift():void 0})})),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===JV.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i||!this.connection)return;if(!(i.track instanceof dM))return ND.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=Wx(e,t)),i.maxFramerate=e.framerate?xx(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==JV.LocalVideoLowTrack||!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return ND.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=xx(t.width)),t.height&&(i.height=xx(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=zP((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),xx(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}),ND.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return ub((function*(){if(!t.connection||t.state!==QV.Connected)return;const i=yield hb(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(JV.LocalVideoTrack);if(!r)throw new jw(Bw.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(JV.LocalVideoLowTrack))throw new jw(Bw.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:JV.LocalVideoLowTrack}];if(yield*pb(Gj(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(JV.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield hb(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(ND.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await RO(this,ZV.RequestRePublish,this.pendingLocalTracks),this.emit
6(ZV.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(ND.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await RO(this,ZV.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==YV.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==YV.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await RO(this,ZV.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===YV.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(ZV.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==QV.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!==QV.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.stopD
6ataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==QV.Connected)return;const e=this.localTrackMap.get(JV.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[JV.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!==QV.Connected)throw new jw(Bw.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.forEac
6h((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!==QV.Connected)throw new jw(Bw.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,d,l;const u=this.connection.getPreMedia(i);if(u)ND.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=u.transceiver,s=u.track,a=u.mid,l=u.player,u.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:u.firstVideoRender});else if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new jw(Bw.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,"."));
vendor: 8,148 bytes, line 6
6const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);(this.connection instanceof _j||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(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 _j||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),s=r.track,a=r.id,d=r.pt}if(t===YV.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new wM(s,e.uid,e._uintid,this.store),ND.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 bM(s,e.uid,e._uintid,this.store,l),ND.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(SP.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(SP.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),l?e._videoTrack.once(SP.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(SP.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&JN("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:i,interceptRemoteAudioFrame:n}=UF();t==YV.VIDEO?await i(c.receiver,{onSei:JN("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)}),onFirstFrame:e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==YV.AUDIO&&await n(c.receiver,{enableTopn:!!JN("ENABLE_AUDIO_TOPN"),enableMetadata:!!JN("ENABLE_AUDIO_METADATA"),enablePts:!!JN("ENABLE_AUDIO_PTS"),pt:d,onMetadata:e=>{this.safeEmit(ZV.AudioMetadata,e)},onPts:e=>{this.safeEmit(ZV.AudioPts,e)}})}const h=this.remoteUserMap.get(e);h?h.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const p=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==p&&(this.pendingRemoteTracks.splice(p,1),this.emit(ZV.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==QV.Connected)throw new jw(Bw.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);if(n){const{track:t,mid:r,transceiver:o,player:s}=n;i.set(e.ssrcId,{track:t,id:r,transceiver:o,player:s})}else 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])}));for(const{user:t,mediaType:n,ssrcId:r}of e){const e=i.get(r);if(!e)return void ND.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(t.uid," subscribe data,").concat(n,", ").concat(r));const{track:o,id:s,transceiver:a,player:c}=e;if(a&&JN("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=UF();n==YV.VIDEO?await e(a.receiver,{onSei:JN("ENABLE_VIDEO_SEI")&&(e=>{var i;return null===(i=t._videoTrack)||void 0===i?void 0:i._onSei(e)}),onFirstFrame:e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):n==YV.AUDIO&&await i(a.receiver,{enableTopn:!!JN("ENABLE_AUDIO_TOPN"),enableMetadata:!!JN("ENABLE_AUDIO_METADATA"),enablePts:!!JN("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(ZV.AudioMetadata,e)},onPts:e=>{this.safeEmit(ZV.AudioPts,e)}})}if(n===YV.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(o):(t._audioTrack=new wM(o,t.uid,t._uintid,this.store),ND.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),a&&t._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(o):(t._videoTrack=new bM(o,t.uid,t._uintid,this.store,c),ND.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),a&&t._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._videoTrack)),JN("ENABLE_VIDEO_SEI")&&a){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=UF();n==YV.VIDEO?await e(a.receiver,{onSei:e=>{var i;null===(i=t._videoTrack)||void 0===i||i._onSei(e)},onFirstFrame:e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):n==YV.AUDIO&&await i(a.receiver)}const d=this.remoteUserMap.get(t);d?d.set(n,s):this.remoteUserMap.set(t,new Map([[n,s]])),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(ZV.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===QV.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===YV.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===YV.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==QV.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===YV.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===YV.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===YV.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.stopD
6ataChannels(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!==QV.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===YV.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===YV.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=Xn(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===YV.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===YV.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===YV.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!==QV.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 ND.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void ND.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===YV.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 ND.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||ND.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(JV.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}addAudioPts(e){const t=this.localTrackMap.get(JV.LocalAudioTrack),i=t&&t.track;i&&i.pts.push(e)}getAllTracks(e){const t=this.localTrackMap.get(JV.LocalAudioTrack);if((null==t?void 0:t.track)instanceof Sk){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==JV.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===JV.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===JV.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(JV.LocalAudioTrack),o=n?this.localTrackMap.get(JV.LocalVideoLowTrack):this.localTrackMap.get(JV.LocalVideoTrack);xD.publish(this.store.sessionId,{eventElapse:NB.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(hP.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 Ek)),a=n?null===(o=this.localTrackMap.get(JV.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof dM));xD.publish(this.store.sessionId,{eventElapse:NB.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(hP.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===YV.VIDEO?i._videoSSRC:i._audioSSRC;r&&xD.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===YV.VIDEO,audio:n===YV.AUDIO,peerid:i.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:NB.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){ND.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new sN("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=cj(this.store),this.emit
vendor: 64,485 bytes, line 6
6(ZV.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(JV.LocalAudioTrack);if((null==e?void 0:e.track)instanceof Sk){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=QV.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(JV.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(JV.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 dM||t&&t.track instanceof Ek?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(fD(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(JV.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=qp(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(ND.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=QV.Reconnecting,JN("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.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=cj(this.store),this.emit(ZV.PeerConnectionStateChange,this.connection.peerConnectionState),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 JV.LocalVideoTrack:Dn(t=n._hints).call(t,hP.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case JV.LocalAudioTrack:n instanceof Sk?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case JV.LocalVideoLowTrack:}})),this.emit(ZV.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(fD(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(ZV.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(fD(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),ND.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 UB?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 UB?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 ub((function*(){if(!t.connection||t.state!==QV.Connected)return;const i=yield hb(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield hb(t.connection.restartICE(e));const r=yield hb(n.next());if(r.done)return;const o=r.value,s=yield o;switch(dj(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case zV.UDP_TCP_RELAY:t._pcStatsUploadType=qV.UDP_TCP_RESTART;break;case zV.TCP_RELAY:t._pcStatsUploadType=qV.TCP_RESTART;break;case zV.RELAY:t._pcStatsUploadType=qV.RELAY_RESTART;break;default:t._pcStatsUploadType=qV.OLD_RESTART}t._isTryConnecting=!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(JV.LocalVideoTrack),i=this.localTrackMap.get(JV.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=vO(this,ZV.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(hP.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return gU[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=vO(this,ZV.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 Wh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(ND.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==QV.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===JV.LocalVideoTrack&&!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding){const t=this.localTrackMap.get(JV.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=PO(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(JV.LocalAudioTrack);for(const r of e){if(r instanceof dM&&(this.localTrackMap.has(JV.LocalVideoTrack)||s?new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:JV.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:JV.LocalVideoLowTrack})}if(r instanceof Ek)if(a){const e=a.track;if(e instanceof Sk)oj([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=sj([e,r]);ND.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 Sk)oj([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&jD().webAudioMediaStreamDest&&!r._bypassWebAudio){o=sj(o?[r,o]:[r])}else o=r}return o&&(ND.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),n.push({track:o,type:JV.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=PO(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof Ek){const e=this.localTrackMap.get(JV.LocalAudioTrack);if(!e)continue;e.track instanceof Sk?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([JV.LocalAudioTrack,e]),e.track.close())):t.push([JV.LocalAudioTrack,e])}if(i instanceof dM){const e=this.localTrackMap.get(JV.LocalVideoTrack);if(!e)continue;t.push([JV.LocalVideoTrack,e]);const i=this.localTrackMap.get(JV.LocalVideoLowTrack);i&&t.push([JV.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=PO(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=PO(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 JV.LocalVideoTrack:t.addListener(uP.GET_STATS,this.handleGetLocalVideoStats),t.addListener(uP.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(uP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(uP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case JV.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case JV.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof Sk?e.trackList.forEach((e=>{e.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(uP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(uP.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 JV.LocalVideoTrack:t.off(uP.GET_STATS,this.handleGetLocalVideoStats),t.off(uP.GET_RTC_STATS,this.handleGetRTCStats),t.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(uP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(uP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case JV.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case JV.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof Sk?e.trackList.forEach((e=>{e.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uP.GET_STATS,this.handleGetLocalAudioStats),e.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(uP.GET_STATS,this.handleGetLocalAudioStats),e.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(uP.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof bM&&t.addListener(uP.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof wM&&t.addListener(uP.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(uP.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(YV.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(YV.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 JV.LocalAudioTrack:r=kV.Audio,o={dtx:s instanceof mk&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case JV.LocalVideoTrack:r=Dn(n=s._hints).call(n,hP.SCREEN_TRACK)?kV.Screen:kV.High,o=jj(jj({},Fx(s)),{},{codec:this.store.codec,svc_mode:zx()});break;case JV.LocalVideoLowTrack:r=kV.Low,o=jj(jj({},Fx(s)),{},{codec:this.store.codec,svc_mode:zx()})}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 JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoLowTrack:i=kV.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(ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(ZV.PeerConnectionStateChange,t),"connecting"===t&&e instanceof _j&&!_w()&&JN("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),JN("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t){this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof _j&&Vj(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=qV.DISCONNECTED_OR_FAILED;if("CONNECTED"===vO(this,ZV.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));xD.reportApiInvoke(this.store.sessionId,{name:aO.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:cO.TRACER}).onSuccess(),this.republish()}}if(JN("NEW_ICE_RESTART")&&e instanceof _j&&!_w()&&!this._forceTurn&&!this.store.useDcSignal){if(Dn(XV).call(XV,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(dj(e)){ND.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===vO(this,ZV.QueryClientConnectionState)&&this.emit(ZV.RequestRestartICE,t)}},i=()=>{dj(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),ND.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(ZV.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{xj(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&JN("ICE_RESTART")){"CONNECTED"===vO(this,ZV.QueryClientConnectionState)&&this.emit(ZV.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(ND.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout((()=>this.emit(ZV.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(ND.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout((()=>this.emit(ZV.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),xD.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:cO.TRACER}).onSuccess(),this.emit(ZV.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(fD(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(SP.FIRST_FRAME_DECODED),xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_AUDIO_DECODE,MD.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:NB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_AUDIO_RECEIVED,MD.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:NB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{var n;const r=Array.from(fD(n=this.remoteUserMap).call(n)).find((t=>t._videoSSRC===e));r&&this.store.firstVideoFrameDecoded(r.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoRender=e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&(this.store.firstVideoFrameDecoded(i.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(i),this.emit(ZV.FirstVideoPreRender,i.uid,e))},e.onFirstVideoReceived=e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&(this.store.firstVideoFrameDecoded(i.uid,{firstReceived:Date.now()}),xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_VIDEO_RECEIVED,MD.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:NB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&this.emit(ZV.FirstVideoBufferReady,i.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(ZV.ConnectionTypeChange,i),ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Hx(t))," -> ").concat(JSON.stringify(Hx(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Hx(t))," -> ").concat(JSON.stringify(Hx(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return jj(jj({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){ND.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===QV.Connected?(ND.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&(this.connection=cj(this.store),this.emit(ZV.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)))}resetConnection(e){e instanceof _j&&function(e){kj.delete(e.id),Vj(e)}(e),e.close(),this.emit(ZV.PeerConnectionStateChange,"closed"),function(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}(e),this._isWaitPcToRePub=!1}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(JV.LocalAudioTrack);if(e instanceof Ek&&(null==i?void 0:i.track)instanceof Sk)return i.track.isActive||t.push([JV.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]===JV.LocalVideoTrack)){const e=this.localTrackMap.get(JV.LocalVideoLowTrack);e&&t.push([JV.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(JV.LocalAudioTrack);if(e instanceof Ek&&(null==i?void 0:i.track)instanceof Sk)return i.track.isActive&&t.push([JV.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===JV.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(JV.LocalVideoLowTrack);e&&t.push([JV.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 JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:i=kV.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 JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:i=kV.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 YV.VIDEO:return void(i._videoSSRC&&t.push({stream_type:YV.VIDEO,ssrcId:i._videoSSRC}));case YV.AUDIO:return void(i._audioSSRC&&t.push({stream_type:YV.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===YV.VIDEO?e|=VV.Video:e|=VV.Audio,t.set(i,e)}else n===YV.VIDEO?t.set(i,VV.Video):t.set(i,VV.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(JV.LocalVideoTrack),i=this.localTrackMap.get(JV.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof _j&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof _j)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof _j&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var r;let{stream_type:o}=e;const s=null===(r=t.find((e=>{let{stream_type:t}=e;return o===t})))||void 0===r?void 0:r.attributes;if(s&&JN("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(Dn(e).call(e,hP.SCREEN_TRACK)||Dn(e).call(e,hP.SCREEN_LOW_TRACK))&&(s.remb=!1,ND.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof Ek){var t;const n=this.filterTobeUnmutedTracks(e[i]);if(0===n.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(n.map((e=>{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await CO(this,ZV.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(ZV.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(ZV.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null===(e=this.connection)||void 0===e?void 0:e.peerConnectionState)||"closed"}}}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 KO(dN(this.dtlsFailedCount,cN)),this.emit(ZV.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await RO(this,ZV.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(ZV.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(JV.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof dM))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof dM)).length>1)throw new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof Ek)).length>1&&(e.some((e=>e instanceof Ek&&e._bypassWebAudio))||!jD().webAudioMediaStreamDest))throw new jw(Bw.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 dM&&this.pendingLocalTracks.some((e=>e instanceof dM)))throw new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof Ek&&this.pendingLocalTracks.some((e=>e instanceof Ek))&&(!jD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof Ek&&e._bypassWebAudio))))throw new jw(Bw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var i;const n=!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding,r=jj(jj({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=n?e._mediaStreamTrack.clone():mj(e,r);const s=YO(8,"track-low-"),a=new dM(o,jj(jj({},n&&{scaleResolutionDownBy:Wx(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(mP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,pP.LOW_STREAM)})),a._hints.push(hP.LOW_STREAM),Dn(i=e._hints).call(i,hP.SCREEN_TRACK)&&a._hints.push(hP.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(uP.NEED_CLOSE,(()=>{a.close()})),a}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 _j){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();xD.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:this._iceError||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}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,i=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!i)return;const{isInternalUpload:n,isExternalUpload:r}=i;if(n&&r)return;const{subscribeEnd:o,firstPreRender:s,peerPublishDuration:a,peerPubStatusMs:c}=i;let{firstRender:d=0}=i;if(o&&(d||s)&&a&&c){i.isInternalUpload=!0;const{playEnd:n}=i;n&&(i.isExternalUpload=!0);const{firstPreRender:r=0}=i;d=r||d;const s=e.videoTrack,l={peer:e._uintid,width:(null==s?void 0:s._videoWidth)||0,height:(null==s?void 0:s._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:a,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:i.userJoinNotify||0,videoAddNotify:i.videoAddNotify||0,subscribeStart:i.subscribeStart||0,subscribeEnd:i.subscribeEnd||0,firstReceived:i.firstReceived||0,firstDecoded:i.firstDecoded||0,firstPreRender:r||0,firstRender:n?Math.max(d,n):Math.max(d,o),playStart:i.playStart||0,playEnd:i.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:YD(this.store),firstReceivedEncodedFrame:i.firstReceivedEncodedFrame||0,frameType:i.frameType||"",rtpTimestamp:i.rtpTimestamp||0,framePayloadType:i.framePayloadType||0,frameDataLength:i.frameDataLength||0,mimeType:i.mimeType||""};xD.firstXLAPeerFirstVideoFrame(this.store.sessionId,l)}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(fD(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));xD.firstRemoteVideoDecode(this.store.sessionId,kD.FIRST_VIDEO_DECODE,MD.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:NB.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===JV.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,pP.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},sV(Fj.prototype,"startP2PConnection",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"startP2PConnection"),Fj.prototype),sV(Fj.prototype,"connect",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"connect"),Fj.prototype),sV(Fj.prototype,"updateRemoteRTPCapabilities",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"updateRemoteRTPCapabilities"),Fj.prototype),sV(Fj.prototype,"publishDataChannel",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"publishDataChannel"),Fj.prototype),sV(Fj.prototype,"unpublish",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unpublish"),Fj.prototype),sV(Fj.prototype,"unpublishDataChannel",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unpublishDataChannel"),Fj.prototype),sV(Fj.prototype,"unpublishLowStream",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unpublishLowStream"),Fj.prototype),sV(Fj.prototype,"subscribeDataChannel",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"subscribeDataChannel"),Fj.prototype),sV(Fj.prototype,"subscribe",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"subscribe"),Fj.prototype),sV(Fj.prototype,"massSubscribe",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"massSubscribe"),Fj.prototype),sV(Fj.prototype,"unsubscribe",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unsubscribe"),Fj.prototype),sV(Fj.prototype,"unsubscribeDataChannel",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unsubscribeDataChannel"),Fj.prototype),sV(Fj.prototype,"massUnsubscribe",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"massUnsubscribe"),Fj.prototype),sV(Fj.prototype,"muteRemote",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"muteRemote"),Fj.prototype),sV(Fj.prototype,"unmuteRemote",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"unmuteRemote"),Fj.prototype),sV(Fj.prototype,"hasRemoteMediaWithLock",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"hasRemoteMediaWithLock"),Fj.prototype),sV(Fj.prototype,"disconnectForReconnect",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"disconnectForReconnect"),Fj.prototype),sV(Fj.prototype,"updateBitrateLimit",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"updateBitrateLimit"),Fj.prototype),sV(Fj.prototype,"remoteMediaSsrcChanged",[Kj],Object.getOwnPropertyDescriptor(Fj.prototype,"remoteMediaSsrcChanged"),Fj.prototype),Fj);function Kj(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;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function Yj(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 zj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Yj(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Yj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const qj=Date.now(),Xj=20,Jj=new Map,Qj=new Map;async function Zj(e){const t=Jj.get(e),i=Array.isArray(t)&&t[t.length-1],n=Qj.get(e);if(!i)return void(n.isSyncing=!1);const r={uid:i.uid,payload:i.payload};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const o=i.sendTs-n.firstSendTs,s=o-(Date.now()-n.firstRecvTs);s>0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(t.pop(),$j(i.context,r),a=0):a=Math.min(a,Xj),setTimeout((()=>t.length&&Zj(e)),a)}function $j(e,t){e.safeEmit(mO.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function eG(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 $j(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=Jj.get(n)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=zj(zj({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),Jj.set(n,r);let a=!1;var c;Qj.has(n)?a=!(null===(c=Qj.get(n))||void 0===c||!c.isSyncing):Qj.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||Zj(n)}const tG=sw().name;function iG(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 nG(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?iG(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):iG(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const rG="websdk_ng_cache_parameter",oG=JN("MAX_PRELOAD_ASYNC_LENGTH"),sG=1e4,aG=new Map,cG=[];let dG=null,lG=0,uG=0;const hG=new Map,pG=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),_G=function(e,t){const i=[];let n=0;const r=async()=>{const e=i.shift();e&&await e(),i.length>0&&n<t?r():n--};return async function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return new Wh((async(o,a)=>{i.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),n<t&&(n++,r())}))}}(fG,oG),EG=Xb.CancelToken.source();class mG{constructor(){bI(this,"_audioContext",null)}createMuteAudioTrack(){this._audioContext=new AudioContext;const e=this._audioContext.sampleRate,t=10*e,i=this._audioContext.createBuffer(2,t,e),n=this._audioContext.createBufferSource();n.buffer=i;const r=this._audioContext.createMediaStreamDestination();n.connect(r),n.start();return r.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function fG(e,t,i,n,r,o,s){try{if(!JN("ENABLE_PRELOAD"))return;if(!jD().supportWebCrypto)return void VO((()=>{ND.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 jw(Bw.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Yw(i,"token",1,2047),Yw(e,"appid",1,2047),gV(t),n&&TV(n);const a=zO();ND.debug("preload channel ".concat(t,", uid is ").concat(n));const c={appId:e,cname:t,token:i||e,uid:"string"!=typeof n?n:null,sid:a,proxyServer:r,role:s};let d,l;"string"==typeof n?(c.stringUid=n,[l,d]=await Wh.all([gB(n,{sid:a,appId:e},EG.token),RB(nG(nG({},c),{},{token:i||e,uid:0}),EG.token)]),c.uid=l.uid,d.gatewayInfo.uid=c.uid,d.gatewayInfo.res.uid=c.uid):(o&&(c.stringUid=o),d=await RB(c,EG.token));const u={sid:a,appId:e,cname:t,token:i||e,uid:c.stringUid||n,intUid:c.uid||d.gatewayInfo.uid,stringUid:c.stringUid,ts:Date.now(),sua:l,ap:d};await TG(u),lG++}catch(e){throw uG++,function(e){dG||(dG=window.setTimeout((()=>{let t="";hG.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),xD.reportApiInvoke(null,{name:aO.PRELOAD,options:{success:lG,failed:uG,err:t}}).onError(e),lG=0,uG=0,hG.clear(),dG=null}),sG));const t=hG.get(e.code)||0;hG.set(e.code,t+1)}(e),e}}async function SG(e){try{if(JN("AP_REQUEST_DETAIL")||JN("ENABLE_ROLE_SELECT_EDGE"))return;const t=gG(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",BO(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:pG},i,xO(e));return JSON.parse(window.atob(FO(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<JN("AP_CACHE_LIFETIME"))return i}catch(e){ND.warn("Error get preloadInfo",e.message)}}function gG(e){let t;try{if(t=yG(rG),!t)return;const i=JSON.parse(t),n=AG(e),r=function(e,t){for(let i=e.length-1;i>=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 IG(rG,JSON.stringify(i)),o[n]}catch(e){ND.warn("Error delete preload info: ".concat(t),e.message),IG(rG,"")}}async function TG(e){let t;try{e.uid&&gG({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=AG(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",BO(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:pG},i,xO(window.btoa(JSON.stringify(e))));return FO(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=yG(rG);const r=t?JSON.parse(t):[];r.push({[i]:n}),r.length>JN("AP_CACHE_NUM")&&r.shift(),IG(rG,JSON.stringify(r))}catch(e){ND.warn("Error caching server parameters:",e.message),IG(rG,"")}}function RG(e){if(e){let t=aG.get(e);t&&(window.clearTimeout(t),t=null,aG.delete(e)),Dn(cG).call(cG,e)||"disabled"!==e.cloudProxyServer||cG.push(e)}if(aG.size<JN("AP_CACHE_NUM")&&cG.length>0){const e=cG.shift();aG.set(e,window.setTimeout((async()=>{const{appId:t,cname:i,token:n,stringUid:r,uid:o,proxyServer:s,role:a}=e;try{await _G(t,i,n,o,s,r,a),aG.has(e)&&RG(e)}catch(t){ND.warn("update preload failed",t.message),CG(e)}}),JN("AP_UPDATE_INTERVAL")))}}function CG(e){const t=cG.indexOf(e);-1!==t&&cG.splice(t,1);let i=aG.get(e);i&&(window.clearTimeout(i),i=null,aG.delete(e),RG())}function vG(e,t){const i=e.sua,n=e.ap;t&&i&&xD.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),xD.reportResourceTiming(e.ap.url,e.sid),xD.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:[Dx.CHOOSE_SERVER,Dx.CLOUD_PROXY_FALLBACK].toString()}),xD.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:[Dx.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function yG(e){return window.atob(window.localStorage.getItem(e)||"")}function IG(e,t){window.localStorage.setItem(e,window.btoa(t))}function AG(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)),nN(t)}function bG(e){let t=function(){const e=DG.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&&(GG(t,10),xG(t,i));let n=e.cid;void 0!==n&&(GG(t,16),GG(t,n));let r=e.cname;void 0!==r&&(GG(t,26),xG(t,r));let o=e.deviceId;void 0!==o&&(GG(t,34),xG(t,o));let s=e.elapse;void 0!==s&&(GG(t,40),HG(t,s));let a=e.fileSize;void 0!==a&&(GG(t,48),HG(t,NG(a)));let c=e.height;void 0!==c&&(GG(t,56),HG(t,NG(c)));let d=e.jpg;void 0!==d&&(GG(t,66),GG(t,d.length),UG(t,d));let l=e.networkType;void 0!==l&&(GG(t,72),HG(t,NG(l)));let u=e.osType;void 0!==u&&(GG(t,80),HG(t,NG(u)));let h=e.requestId;void 0!==h&&(GG(t,90),xG(t,h));let p=e.sdkVersion;void 0!==p&&(GG(t,98),xG(t,p));let _=e.sequence;void 0!==_&&(GG(t,104),HG(t,NG(_)));let E=e.sid;void 0!==E&&(GG(t,114),xG(t,E));let m=e.timestamp;void 0!==m&&(GG(t,120),HG(t,m));let f=e.uid;void 0!==f&&(GG(t,128),GG(t,f));let S=e.vid;void 0!==S&&(GG(t,136),GG(t,S));let g=e.width;void 0!==g&&(GG(t,144),HG(t,NG(g)));let T=e.service;void 0!==T&&(GG(t,152),GG(t,T));let R=e.callbackData;void 0!==R&&(GG(t,162),GG(t,R.length),UG(t,R));let C=e.ticket;void 0!==C&&(GG(t,170),xG(t,C));let v=e.vendorConfigs;void 0!==v&&(GG(t,178),xG(t,v))}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function wG(e){return function(e){let t={};e:for(;!LG(e);){let i=jG(e);switch(i>>>3){case 0:break e;case 1:t.code=jG(e);break;case 2:t.msg=VG(e,jG(e));break;case 3:t.requestId=VG(e,jG(e));break;case 4:t.timestamp=WG(e,!1);break;default:OG(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function OG(e,t){switch(t){case 0:for(;128&FG(e););break;case 2:PG(e,jG(e));break;case 5:PG(e,4);break;case 1:PG(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function NG(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let DG=[];function PG(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function LG(e){return e.offset>=e.limit}function kG(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 MG(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function UG(e,t){let i=kG(e,t.length);e.bytes.set(t,i)}function VG(e,t){let i=MG(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+i];0==(128&u)?s+=n(u):192==(224&u)?e+1>=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 xG(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4}GG(e,n);let r=kG(e,n),o=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?o[r++]=n:(n<2048?o[r++]=n>>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 FG(e){return e.bytes[MG(e,1)]}function BG(e,t){let i=kG(e,1);e.bytes[i]=t}function jG(e){let t,i=0,n=0;do{t=FG(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function GG(e,t){for(t>>>=0;t>=128;)BG(e,127&t|128),t>>>=7;BG(e,t)}function WG(e,t){let i,n=0,r=0,o=0;return i=FG(e),n=127&i,128&i&&(i=FG(e),n|=(127&i)<<7,128&i&&(i=FG(e),n|=(127&i)<<14,128&i&&(i=FG(e),n|=(127&i)<<21,128&i&&(i=FG(e),r=127&i,128&i&&(i=FG(e),r|=(127&i)<<7,128&i&&(i=FG(e),r|=(127&i)<<14,128&i&&(i=FG(e),r|=(127&i)<<21,128&i&&(i=FG(e),o=127&i,128&i&&(i=FG(e),o|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|o<<24,unsigned:t}}function HG(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=kG(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 KG={},YG={},zG=4294967296,qG=zG*zG,XG=qG/2,JG=tW(0,!0),QG=tW(0),ZG=iW(0,-2147483648,!1),$G=iW(-1,2147483647,!1),eW=iW(-1,-1,!0);function tW(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=YG[e],n)?n:(i=iW(e,0,!0),r&&(YG[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=KG[e],n)?n:(i=iW(e,e<0?-1:0,!1),r&&(KG[e]=i),i)}function iW(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function nW(e,t){if(isNaN(e))return t?JG:QG;if(t){if(e<0)return JG;if(e>=qG)return eW}else{if(e<=-XG)return ZG;if(e+1>=XG)return $G}return e<0?t?JG:QG:iW(e%zG|0,e/zG|0,t)}function rW(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 oW extends rO{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(sx.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(),bI(this,"name","AgoraRTCImageModeration"),bI(this,"_connectionState",ox.CONNECTING),bI(this,"_sequence",0),bI(this,"_moderationStartTime",void 0),bI(this,"_workerConnection",void 0),bI(this,"_workerMessageLengthLimit",void 0),bI(this,"_qualityRatio",void 0),bI(this,"_connectInfo",void 0),bI(this,"_cancelTokenSource",Xb.CancelToken.source()),bI(this,"_retryConfig",void 0),bI(this,"_moderationInterval",void 0),bI(this,"_moderationTimer",null),bI(this,"_moderationMode",1),bI(this,"_quality",1),bI(this,"_qualityTimer",null),bI(this,"_ticket",void 0),bI(this,"_moderationIntervalMinimum",void 0),bI(this,"_uploadFailedNum",0),bI(this,"_uploadNum",0),bI(this,"_uploadTimer",null),bI(this,"_extraInfo",void 0),bI(this,"_vendor",""),bI(this,"_encoder",new TextEncoder),bI(this,"_moderationId",void 0),bI(this,"inspectImage",(()=>{if(this.connectionState!==ox.CONNECTED)throw new FD(Bw.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===ox.CONNECTED?this.requestToInspectImage():ND.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()})),this._moderationId=YO(5,"image-moderation-"),this._workerMessageLengthLimit=JN("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=JN("IMAGE_MODERATION_INTERVAL_MINIMUM"),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),this._qualityRatio=JN("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new wx("worker-"+this._moderationId,cN),this.on(sx.STATE_CHANGE,((e,t)=>{ND.debug("[".concat(this._moderationId,"] Moderation operation :").concat(ax[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(sx.STATE_CHANGE,ax.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((n,r)=>{this.on(sx.CONNECTION_STATE_CHANGE,((e,t)=>{e===ox.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),ND.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===ox.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=JN("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;uB++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:uB,seq:uB,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return lN((async()=>{h=Date.now();const e=await WF(_,{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 FD(Bw.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw ND.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new FD(Bw.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw ND.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new FD(Bw.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw ND.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new FD(Bw.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw ND.error(e.toString()),e}const n=JN("IMAGE_MODERATION_WORKER_WSS");if(n)return{addressList:[n],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=JN("IMAGE_MODERATION_WORKER_HOST"),o=t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(i,"/moderation")})).filter((e=>!!e));return{addressList:o,workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(xD.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)=>(xD.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Bw.OPERATION_ABORTED&&t.code!==Bw.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(sx.STATE_CHANGE,ax.AP_CONNECTED);const{addressList:o,ticket:s}=r;return this._ticket=s,o}async connectWorker(e){this.emit(sx.STATE_CHANGE,ax.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(SV.CONNECTED,(async()=>{this.emit(sx.STATE_CHANGE,ax.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=ox.CONNECTED})),this._workerConnection.on(SV.CLOSED,(()=>{this.connectionState=ox.CLOSED})),this._workerConnection.on(SV.FAILED,(()=>{this.connectionState=ox.CLOSED})),this._workerConnection.on(SV.RECONNECTING,(()=>{this.connectionState=this.connectionState===ox.CONNECTED?ox.RECONNECTING:ox.CONNECTING})),this._workerConnection.on(SV.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=wG(new Uint8Array(e.data));JN("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&ND.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++,ND.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{xD.reportApiInvoke(this._connectInfo.sid||null,{name:aO.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:cO.TRACER}).onError(new FD(Bw.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),JN("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else ND.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(SV.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this._workerConnection.on(SV.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=vO(this,sx.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(JN("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&ND.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 JN("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&ND.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 AL(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+YO(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:oW.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.24.2-200",sequence:this._sequence,sid:s,timestamp:nW(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=bG(h);if(p.byteLength<this._workerMessageLengthLimit){if(JN("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?rW(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):rW(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},h);delete e.jpg,ND.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return p}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=Xb.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=ox.CLOSED,this.emit(sx.STATE_CHANGE,ax.CLOSED)}}function sW(e){if(Hw(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new FD(Bw.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new FD(Bw.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const aW={name:"ImageModeration",create:function(e){let{config:t}=e;return sW(t),new oW(t)}};var cW,dW,lW,uW,hW,pW,_W,EW,mW,fW,SW,gW,TW,RW,CW,vW,yW,IW,AW,bW,wW,OW,NW,DW,PW,LW,kW,MW,UW,VW,xW,FW,BW,jW,GW,WW,HW,KW,YW,zW,qW,XW,JW;function QW(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 ZW(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?QW(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):QW(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}sN.setLogger(ND);let $W=(cW=VD(),dW=VD({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof FP))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),lW=VD({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==gP.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),uW=VD({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),hW=VD({argsMap:(e,t,i)=>[t,i]}),pW=VD({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),_W=VD({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),EW=VD({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),mW=VD(),fW=VD(),SW=VD(),gW=VD(),TW=VD(),RW=VD(),CW=VD(),vW=VD(),yW=VD(),IW=VD(),AW=VD(),bW=VD(),wW=VD(),OW=VD(),NW=VD(),DW=VD(),PW=VD({argsMap:(e,t)=>[t]}),LW=VD(),kW=VD(),MW=VD(),UW=VD(),VW=VD(),xW=VD(),FW=VD(),BW=VD(),jW=VD({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),GW=VD(),WW=VD(),HW=VD(),KW=VD(),YW=VD(),zW=VD(),qW=VD({reportResult:!0}),XW=VD(),JW=class extends rO{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,t){let i;if(super(),bI(this,"store",void 0),bI(this,"_uid",void 0),bI(this,"_channelName",void 0),bI(this,"_uintUid",void 0),bI(this,"_users",[]),bI(this,"_config",void 0),bI(this,"_clientId",void 0),bI(this,"_appId",void 0),bI(this,"_sessionId",null),bI(this,"_key",void 0),bI(this,"_rtmConfig",{}),bI(this,"_joinInfo",void 0),bI(this,"_gateway",void 0),bI(this,"_statsCollector",void 0),bI(this,"_configDistribute",void 0),bI(this,"_leaveMutex",void 0),bI(this,"_publishMutex",void 0),bI(this,"_renewTokenMutex",void 0),bI(this,"_subscribeMutex",void 0),bI(this,"_encryptionMode","none"),bI(this,"_encryptionSecret",null),bI(this,"_encryptionSalt",null),bI(this,"_encryptDataStream",!1),bI(this,"_encryptDataStreamKey",null),bI(this,"_encryptDataStreamIv",null),bI(this,"_proxyServer",void 0),bI(this,"_turnServer",{servers:[],mode:"auto"}),bI(this,"_cloudProxyServerMode","disabled"),bI(this,"_isDualStreamEnabled",!1),bI(this,"_defaultStreamFallbackType",void 0),bI(this,"_lowStreamParameter",void 0),bI(this,"_streamFallbackTypeCacheMap",new Map),bI(this,"_remoteStreamTypeCacheMap",new Map),bI(this,"_axiosCancelSource",Xb.CancelToken.source()),bI(this,"_audioVolumeIndicationInterval",void 0),bI(this,"_networkQualityInterval",void 0),bI(this,"_userOfflineTimeout",void 0),bI(this,"_streamRemovedTimeout",void 0),bI(this,"_rteDetailInterval",void 0),bI(this,"_liveTranscodeStreamingClient",void 0),bI(this,"_liveRawStreamingClient",void 0),bI(this,"_channelMediaRelayClient",void 0),bI(this,"_networkQualitySensitivity","normal"),bI(this,"_p2pCh
6annel",void 0),bI(this,"_useLocalAccessPoint",!1),bI(this,"_setLocalAPVersion",void 0),bI(this,"_joinAndNotLeaveYet",!1),bI(this,"_numberOfJoinCount",0),bI(this,"_joinResponse",null),bI(this,"_remoteDefaultVideoStreamType",void 0),bI(this,"_inspect",void 0),bI(this,"_moderation",void 0),bI(this,"_license",void 0),bI(this,"_pendingPublishedUsers",[]),bI(this,"ntpAlignErrorCount",0),bI(this,"remoteInboundOffset",0),bI(this,"_peerConnectionState",void 0),bI(this,"_pendingRtpCapabilityChange",void 0),bI(this,"_fallbackServerInfo",void 0),bI(this,"_dualStreamMode",void 0),bI(this,"_handleLocalTrackEnable",((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),bI(this,"_handleLocalTrackDisable",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),bI(this,"_handleUserOnline",(e=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(e.uid,this.channelName))return void ND.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&ND.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(mO.USER_JOINED,t));else{const t=new UB(e.uid,e.uint_id||e.uid);this._users.push(t),ND.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(mO.USER_JOINED,t)}})),bI(this,"_handleUserOffline",(e=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(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:DO(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),ND.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(mO.USER_LEAVED,t,e.reason))})),bI(this,"_handleAddAudioOrVideoStream",((e,t,i,n,r,o,s,a)=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void ND.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));ND.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=o||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==i&&(c._audioSSRC=i),void 0!==n&&(c._cname=n),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==i&&(c._videoSSRC=i),void 0!==n&&(c._cname=n),void 0!==a&&(c._rtxSsrcId=a),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(ND.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(mO.USER_PUBLISHED,c,e)),"video"===e?xD.onGatewayStream(this._sessionId,kD.ON_ADD_VIDEO_STREAM,MD.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):xD.onGatewayStream(this._sessionId,kD.ON_ADD_AUDIO_STREAM,MD.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,i).then((t=>{if(t&&(ND.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof Hj))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{ND.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(ND.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{ND.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(r);"video"===e&&("unknown"===l?this.safeEmit(mO.AV1_DECODABLE_RESULT,!1):hw()||Ew()||(null==l?void 0:l.toLocaleLowerCase())!==eD.av1||EB().then((e=>{JN("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(mO.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))}
vendor: 27,823 bytes, line 6
6)),bI(this,"_handleRemoveStream",(e=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void ND.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));ND.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{ND.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mO.USER_UNPUBLISHED,t,"audio"),ND.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mO.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{ND.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mO.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{ND.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mO.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 Hj&&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),xD.onGatewayStream(this._sessionId,kD.ON_REMOVE_STREAM,MD.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()})),bI(this,"_handleSetStreamLocalEnable",((e,t,i)=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void ND.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));ND.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";ND.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mO.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";ND.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mO.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(ND.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(mO.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),ND.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(mO.USER_UNPUBLISHED,n,e)):void 0})),bI(this,"_handleMuteStream",((e,t,i)=>{if(JN("BLOCK_LOCAL_CLIENT")&&CU(e,this.channelName))return;ND.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void ND.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";ND.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mO.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";ND.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mO.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)?(ND.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(mO.USER_PUBLISHED,n,t)):void ND.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),ND.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(mO.USER_UNPUBLISHED,n,t)}})),bI(this,"_handleP2PLost",(async e=>{ND.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():ND.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),bI(this,"_handleTokenWillExpire",(()=>{ND.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(mO.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),bI(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),ND.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),bI(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(mO.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(mO.NETWORK_QUALITY,e)})),bI(this,"_handleP2PAddAudioOrVideoStream",((e,t,i,n)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void ND.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));ND.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&&(ND.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(mO.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(ND.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{ND.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||YO(5,"client-"),this.store=new class{constructor(e,t,i,n,r){Fw(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:GN.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!r}}dispatch(e){this.state=function(e,t){switch(t.type){case $N.SET_SESSION_ID:return xw(xw({},e),{},{sessionId:t.sessionId});case $N.SET_P2P_ID:return xw(xw({},e),{},{p2pId:t.p2pId});case $N.SET_UID:return xw(xw({},e),{},{uid:t.uid});case $N.SET_INT_UID:return xw(xw({},e),{},{intUid:t.intUid});case $N.SET_PUB_ID:return xw(xw({},e),{},{pubId:t.pubId});case $N.KEY_METRIC_CLIENT_CREATED:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{clientCreated:t.metric})});case $N.KEY_METRIC_JOIN_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinStart:t.metric})});case $N.KEY_METRIC_PRELOAD_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{preloadStart:t.metric})});case $N.KEY_METRIC_PRELOAD_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{preloadEnd:t.metric})});case $N.KEY_METRIC_JOIN_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinEnd:t.metric})});case $N.KEY_METRIC_REQUEST_AP_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{requestAPStart:t.metric})});case $N.KEY_METRIC_REQUEST_AP_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{requestAPEnd:t.metric})});case $N.KEY_METRIC_REQUEST_SUA_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case $N.KEY_METRIC_BEFORE_CONNECT:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{beforeConnect:t.metric})});case $N.KEY_METRIC_PEER_RECEIVER:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{peerReceiver:t.metric})});case $N.KEY_METRIC_SIGNAL_CONNECTED:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{signalConnected:t.metric})});case $N.KEY_METRIC_JOIN_REQ:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinReq:t.metric})});case $N.KEY_METRIC_JOIN_REP:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinRep:t.metric})});case $N.KEY_METRIC_JOIN_GATEWAY_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case $N.KEY_METRIC_JOIN_GATEWAY_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case $N.KEY_METRIC_PEER_CONNECTION_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case $N.KEY_METRIC_PEER_CONNECTION_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case $N.KEY_METRIC_DESCRIPTION_START:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{descriptionStart:t.metric})});case $N.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case $N.KEY_METRIC_ICE_CONNECTION_END:return xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case $N.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=xw(xw({},i[n]),t.metric),xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{publish:[...i]})})):xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case $N.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]=xw(xw({},i[n]),t.metric),xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{subscribe:[...i]})})):xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case $N.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const i=e.keyMetrics.firstVideoFrameDecoded,n=i.findIndex((e=>e.userId===t.metric.userId));return-1!==n?(i[n]=xw(xw({},i[n]),t.metric),xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{firstVideoFrameDecoded:[...i]})})):xw(xw({},e),{},{keyMetrics:xw(xw({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case $N.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case $N.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case $N.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=xw(xw({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case $N.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case $N.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case $N.SET_USE_P2P:return xw(xw({},e),{},{useP2P:t.val});case $N.SET_TRANSPORT_TYPE:return xw(xw({},e),{},{p2pTransport:t.val});case $N.SET_RTE_URL:return xw(xw({},e),{},{rteUrl:t.rteUrl});case $N.SET_RTE_SID:return xw(xw({},e),{},{rteSid:t.rteSid});default:return e}}(this.state,e)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(e){this.state.useDcSignal=e}set autoSubscribe(e){this.state.autoSubscribe=e}get autoSubscribe(){return this.state.autoSubscribe}set enableInstantMuteRestore(e){this.state.enableInstantMuteRestore=e}get enableInstantMuteRestore(){return this.state.enableInstantMuteRestore}set networkQualityProbe(e){this.state.networkQualityProbe=e}get networkQualityProbe(){return this.state.networkQualityProbe}set sessionId(e){this.dispatch({type:$N.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:$N.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:$N.SET_RTE_SID,rteSid:e})}get rteSid(){return this.state.rteSid}set cid(e){this.state.cid=e}get cid(){return this.state.cid}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:$N.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:$N.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:$N.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:$N.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:$N.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:$N.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:$N.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:$N.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(e){this.state.hasStartJoinChannel=e}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:$N.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:$N.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:$N.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:$N.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:$N.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:$N.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:$N.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:$N.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:$N.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:$N.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:$N.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:$N.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:$N.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:$N.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:$N.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:$N.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:$N.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:$N.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:xw({userId:e},t)})}descriptionStart(){this.dispatch({type:$N.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:$N.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:$N.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:$N.KEY_METRIC_PUBLISH,metric:xw(xw({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:$N.KEY_METRIC_SUBSCRIBE,metric:xw(xw(xw(xw(xw({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:$N.KEY_METRIC_SUBSCRIBE,metric:xw(xw(xw({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:$N.RECORD_JOIN_CHANNEL_SERVICE,record:xw(xw({},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:$N.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:$N.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:$N.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:$N.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===JN("SIGNAL_CHANNEL")),this._leaveMutex=new sN("client-leave",this._clientId),this._publishMutex=new sN("client-publish",this._clientId),this._renewTokenMutex=new sN("client-renewtoken",this._clientId),this._subscribeMutex=new sN("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),ND.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(BN," build: ").concat(YN,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{EO(e.clientRoleOptions),i=Object.assign({},e.clientRoleOptions)}catch(e){ND.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var n;this._statsCollector=new LB(this.store),this._statsCollector.onStatsException=(e,t,i)=>{ND.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),e===OB.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof lM&&JN("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(mO.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));if(r){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(r.uid,{peerPublishDuration:i,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(r)),xD.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(JN("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof dM));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?JN("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new BF(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||cN,httpRetryConfig:e.httpRetryConfig||cN,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:i}),this._configDistribute=new bB(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(n={store:this.store,statsCollector:this._statsCollector},kF("P2PChannel").create(n)),this._handleP2PEvents()):this._p2pChannel=new Hj(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];XN("JOIN_GATEWAY_USE_443PORT_ONLY",o),XN("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof bx&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,i){Zb.get(e)||Zb.set(e,[]),$b.get(e)||$b.set(e,t),ew.get(e)||ew.set(e,0);const n=Zb.get(e),r=$b.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(ew.get(e)===r){const e=Qb();n.push(e),await e.promise}ew.set(e,ew.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a<o;a++)s[a-3]=arguments[a];const c=await i(...s);return ew.set(e,ew.get(e)-1),ew.get(e)===r-1&&n.length>0&&(n[0].resolve(),n.shift()),0===ew.get(e)&&(Zb.set(e,[]),$b.set(e,0),ew.set(e,0)),c}("client.join",JN("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"===(uN||uN||(uN=(window.location.protocol.split(":")[0]||"").toUpperCase(),uN)),a=fN()?window.isSecureContext:"Browser Not Support";if(!fN()&&!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";ND.warning(e)}let c;xD.setAppId(e);try{if(!i&&null!==i)throw new FD(Bw.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));if(i&&Yw(i,"token",1,2047),Yw(e,"appid",1,2047),gV(t),n&&TV(n),r)if("string"==typeof r)Yw(r,"optionalInfo",1,256),c=r;else{if("object"!=typeof r)throw new FD(Bw.INVALID_PARAMS,"Invalid options: options is not a string or object");{const{autoSubscribe:e,enableInstantMuteRestore:t,networkQualityProbe:i}=r;e&&(Gw(e,"autoSubscribe"),ND.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),t&&(Gw(t,"enableInstantMuteRestore"),ND.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),i&&(Gw(i,"networkQualityProbe"),ND.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(i)),this.store.networkQualityProbe=i)}}}catch(r){throw xD.reportApiInvoke(zO(),{name:aO.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:cO.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){ND.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),ND.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw xD.reportApiInvoke(zO(),{name:aO.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:cO.TRACER}).onError(r),r}this._gateway.state="CONNECTING",this.store.preloadStart();const d=await SG({appId:e,cname:t,uid:n,stringUid:"string"==typeof n?n:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const l=(null==d?void 0:d.sid)||zO();ND.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=l,this.store.sessionId=this._sessionId);const u=xD.reportApiInvoke(this._sessionId,{id:this._clientId,name:aO.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:cO.TRACER}),h=ZW(ZW(ZW({},this._rtmConfig),{},{role:this.role,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:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!d},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:JN("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(h.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(h.stringUid=n,this._uintUid?(h.uid=this._uintUid,this._uintUid=void 0):h.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(h.aesmode=this._encryptionMode,h.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<t.length;e+=1)i[e]=t.charCodeAt(e);return i}(),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=tO(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return function(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(h.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=JN("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(h.appId+this._encryptionSecret+this._encryptionSecret):e.encode(h.appId+h.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,o=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:nD,hash:"SHA-256",salt:i},n,r+iD);return new Uint8Array(o).subarray(r/8)}(this._encryptionMode,t,xO(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:nD,hash:"SHA-256",salt:i},n,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"])}(this._encryptionMode,t,xO(this._encryptionSalt))}else a?ND.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):ND.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,ND.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:h.stringUid});const p=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&p===this._sessionId&&xD.joinChannelTimeout(this._sessionId,5)}),5e3);try{var _;let n;const r=h.cloudProxyServer;if(Dn(_=["proxy3","proxy4","proxy5"]).call(_,r)){const e=JN("PROXY_SERVER_TYPE3");Array.isArray(e)?h.proxyServer=e[0]:h.proxyServer=e}if(xD.setProxyServer(h.proxyServer),ND.setProxyServer(h.proxyServer),this.store.requestAPStart(),d){if(ND.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(h.stringUid?", ".concat(h.stringUid," => ").concat(d.intUid):""," ")),h.stringUid&&!h.uid&&(h.uid=d.intUid),n={gatewayInfo:d.ap.gatewayInfo},JN("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===h.turnServer.mode)if(0===d.ap.proxyInfo.addresses.length)ND.warning("no edge services in a
6p response of proxy fallback, will not set proxy in iceServers");else{const e=(await Gx(d.ap.proxyInfo,d.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||WN.tcpport,udpport:e.udpport||WN.udpport,username:e.username||WN.username,password:e.password||WN.password,forceturn:!1,security:!0})));h.turnServer={mode:"manual",servers:e}}vG(d,h.stringUid)}else{if(h.stringUid&&!h.uid){let e;[e,n]=await Wh.all([SB(h.stringUid,h,this._axiosCancelSource.token,this._config.httpRetryConfig||cN,this.store).finally((()=>{this.store.requestSUAEnd()})),fB(h,this._axiosCancelSource.token,this._config.httpRetryConfig||cN,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),ND.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(h.stringUid," => ").concat(e)),h.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await fB(h,this._axiosCancelSource.token,this._config.httpRetryConfig||cN,!0,this.store);if(!this._joinAndNotLeaveYet)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(h,this._axiosCancelSource.token),this._configDistribute.on(GV.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(GV.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(GV.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{var t;Dn(t=[0,1,4,5,6,7,8,9]).call(t,e)&&(this.remoteUsers.forEach((t=>{this._remoteStreamTypeCacheMap.get(t.uid)!==e&&this.setRemoteVideoStreamType(t.uid,e)})),this.setRemoteDefaultVideoStreamType(e))})),this._configDistribute.on(GV.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(mO.FALLBACK_TO_HLS,fO.CONFIG)})),this._configDistribute.on(GV.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{ND.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=i||e;const o=n.gatewayInfo,s=h.uid?h.uid:o.uid;this._joinInfo=ZW(ZW({},h),{},{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,this.store.cid=o.cid;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));u.onSuccess(a),this._appId=e,this._channelName=h.cname,this._uid=a,this.store.uid=a,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!hw()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(hw()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const c=h.stringUid?"string uid: ".concat(h.stringUid,",uid: ").concat(h.uid):"uid: ".concat(this._uid);return ND.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout((()=>{ND.startUpload()}),5e3),this.store.joinEnd(),E=this,Dn(TU).call(TU,E)||TU.push(E),"disabled"===this._cloudProxyServerMode&&jD().supportWebCrypto&&JN("ENABLE_PRELOAD")&&RG(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&xD.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&xD.reportRteDetail(this._sessionId)}),JN("RTE_DETAIL_REPORT_INTERVAL")||6e4),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Bw.OPERATION_ABORTED?ND.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):ND.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==Bw.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),u.onError(t),t}var E}async _joinGateway(){if(!this._joinInfo||!this._key)throw new FD(Bw.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!JN("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===Bw.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,uO.FALLBACK),ND.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new FD(Bw.INVALID_OPERATION);return xD.reportApiInvoke(this._sessionId,{name:aO.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:cO.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){ND.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!hw()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(hw()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=TU.indexOf(e);-1!==t&&TU.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return ND.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();await this._gateway.leave("CONNECTED"!==this.connectionState,uO.LEAVE),ND.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof FP))return this._publishDataChannel
vendor: 48,610 bytes, line 6
6(e);e=[e]}if(0===e.length)throw new FD(Bw.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new FD(Bw.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof FP))throw new FD(Bw.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new FD(Bw.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}ND.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 dM&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),ND.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw ND.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{n()}}async _publishDataChannel(e){if(null==e)throw new FD(Bw.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));Hw(e.id,"id",0,65535,!0),Gw(e.ordered,"ordered"),Yw(e.metadata,"metadata",0,512),ND.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 FD(Bw.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 FD(Bw.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&JN("FORCE_TURN")&&!JN("TURN_ENABLE_TCP")&&!JN("TURN_ENABLE_UDP"))throw new FD(Bw.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return MF(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw ND.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new FD(Bw.CREATE_DATACHANNEL_ERROR);try{await Wh.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==Bw.DISCONNECT_P2P)throw e}}return ND.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw ND.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new FD(Bw.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof FP))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);ND.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(cx.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),ND.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw ND.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()),ND.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),ND.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw ND.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof UB)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new FD(Bw.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(Ww(t,"mediaType",["audio","video"]),this.store.useP2P)throw new FD(Bw.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===YV.AUDIO,n=t===YV.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 FD(Bw.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new UB(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)),ND.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 FD(Bw.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 ND.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var i;if(Hw(t,"channelId",0,65535,!0),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n)throw ND.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw ND.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new FD(Bw.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 ND.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new FD(Bw.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();ND.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 ND.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new FD(Bw.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)!==Bw.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return ND.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,i){if(Ww(t,"mediaType",["audio","video"]),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");throw ND.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 FD(Bw.INVALID_REMOTE_USER,"user is not published");throw ND.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 FD(Bw.REMOTE_USER_IS_NOT_PUBLISHED);throw ND.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();ND.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.store.useP2P&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}ND.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{ND.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new FD(Bw.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw ND.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(Ww(t,"mediaType",["audio","video"]),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");throw ND.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 FD(Bw.INVALID_REMOTE_USER,"user is not published");throw ND.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 FD(Bw.REMOTE_USER_IS_NOT_PUBLISHED);throw ND.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?YV.AUDIO:YV.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const c=await this._subscribeMutex.lock();ND.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?YV.AUDIO:YV.VIDEO,ssrcId:r}),NB.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)!==Bw.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}ND.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{ND.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new FD(Bw.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),i}catch(t){throw ND.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(zw(e,"subscribeList"),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();ND.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(Ww(s,"mediaType",["audio","video"]),!o){const e=new FD(Bw.INVALID_PARAMS,"user property does not exist in subscribeList item");throw ND.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 FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");ND.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 FD(Bw.REMOTE_USER_IS_NOT_PUBLISHED);ND.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=VV.Video|VV.LwoVideo,d=i.get(o);if(d){if("video"===s?d&c:d&VV.Audio){e.splice(t,1),ND.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,d|("video"===s?c:VV.Audio))}else i.set(o,"video"===s?c:VV.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:o}=n,s=VV.Video|VV.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^VV.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=Xn(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&VV.Audio&&(r.audio_ssrc=i._audioSSRC),n&VV.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===YV.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===YV.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=YV.VIDEO:n.audio_error_code&&(t=YV.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=Ex(i);ND.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new FD(Bw.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;xD.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===YV.VIDEO,audio:e.mediaType===YV.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===YV.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)})),ND.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 UB)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new FD(Bw.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&&Ww(t,"mediaType",["audio","video"]),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");throw ND.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}ND.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const r=await this._subscribeMutex.lock();try{if(this.store.useP2P)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&&DO(this._users,e),ND.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===Bw.DISCONNECT_P2P)return void ND.warning("disconnecting p2p, abort unsubscribe request.");throw ND.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&Hw(t,"id",0,65535,!0),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new FD(Bw.INVALID_REMOTE_USER,"user is not in the channel");throw ND.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 FD(Bw.REMOTE_USER_IS_NOT_PUBLISHED);throw ND.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}ND.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),ND.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===Bw.DISCONNECT_P2P)return void ND.warning("disconnecting p2p, abort unsubscribe request.");throw ND.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(zw(e,"unsubscribeList"),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");ND.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 FD(Bw.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw ND.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Ww(r,"mediaType",["video","audio",void 0]);const o=this._users.find((e=>e===n));if(!o){ND.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const s=VV.Video|VV.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&VV.Audio;break;default:a=o&(VV.Audio|s)}if(a){ND.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|VV.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|VV.Audio|s)}else r?"audio"===r?t.set(n,VV.Audio):"video"===r&&t.set(n,s):t.set(n,VV.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),ND.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===Bw.DISCONNECT_P2P)return void ND.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw ND.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new jw(Bw.INVALID_PARAMS);qw(e.width)||Kw(e.width,"streamParameter.width"),qw(e.height)||Kw(e.height,"streamParameter.height"),qw(e.framerate)||Kw(e.framerate,"streamParameter.framerate"),qw(e.bitrate)||Hw(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&ND.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),ND.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,JV.LocalVideoLowTrack)}async setDualStreamMode(e,t){Ww(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{ND.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):ND.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case _O.AUTO_SIMULCAST_STREAM:ND.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case _O.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case _O.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw ND.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!jD().supportDualStream)throw xD.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new FD(Bw.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new FD(Bw.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw xD.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=_O.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{ND.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),xD.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),ND.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void ND.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(JV.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw xD.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=_O.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{ND.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),xD.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),ND.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){Ww(e,"role",["audience","host"])}(e),t&&EO(t),"rtc"===this.mode||"p2p"===this.mode)throw ND.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new FD(Bw.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new FD(Bw.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new FD(Bw.INVALID_OPERATION,"can not set client role to audience when publishing stream");const i=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==i&&JN("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",SO.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),ND.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===i&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof Hj){const{video_codec:e}=this._pendingRtpCapabilityChange;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>{var t;return Dn(t=Object.keys(eD)).call(t,e)})))}}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode)return;if("audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&EO(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{ND.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+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(Yw(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new FD(Bw.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,xD.setProxyServer(this._proxyServer),ND.setProxyServer(this._proxyServer),ND.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 FD(Bw.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new FD(Bw.INVALID_OPERATION,"You have already set the proxy")}if(hO(e))return this._turnServer={servers:e,mode:"original-manual"},void ND.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>pO(e))),this._turnServer={servers:e,mode:"manual"},ND.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new FD(Bw.INVALID_OPERATION,"you should set license before join channel")}if(Yw(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new FD(Bw.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,ND.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new FD(Bw.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 FD(Bw.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 FD(Bw.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,ND.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"Stop proxy server after leave channel");xD.setProxyServer(),ND.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",ND.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 FD(Bw.INVALID_PARAMS,"accessPoints is required.");zw(e.accessPoints.serverList,"accessPoints.serverList"),Yw(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{Hw(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 FD(Bw.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");JN("CLOSE_AFB_FOR_LOCAL_AP")&&(XN("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),XN("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,XN("WEBCS_DOMAIN",s),XN("WEBCS_DOMAIN_BACKUP_LIST",s),XN("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(zw(e.report.hostname,"report.hostname"),XN("EVENT_REPORT_DOMAIN",e.report.hostname[0]),XN("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(XN("EVENT_REPORT_DOMAIN",o[0]),XN("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),XN("STATS_COLLECTOR_PORT",a),e.report?XN("ENABLE_EVENT_REPORT",!0):XN("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(zw(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),XN("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(zw(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),XN("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?XN("ENABLE_CONFIG_DISTRIBUTE",!0):XN("ENABLE_CONFIG_DISTRIBUTE",!1),ND.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(zw(e,"serverList"),Yw(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new FD(Bw.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,XN("WEBCS_DOMAIN",e),XN("WEBCS_DOMAIN_BACKUP_LIST",e),XN("GATEWAY_DOMAINS",[t]),XN("EVENT_REPORT_DOMAIN",e[0]),XN("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),XN("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),ND.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Ww(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw ND.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else ND.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Ww(t,"streamType",[0,1,4,5,6,7,8,9]);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 ND.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}ND.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Ww(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw ND.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}ND.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){Ww(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),Yw(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 FD(Bw.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new FD(Bw.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Gw(n,"encryptDataStream"),!Dn(r).call(r,e))throw new FD(Bw.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||ND.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=FO(i))}async renewToken(e){if(Yw(e,"token",1,2047),!this._key||!this._joinInfo)throw new FD(Bw.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(JN("USE_NEW_TOKEN")){ND.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await yB(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||cN);ND.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else ND.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});ND.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,ND.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?ND.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(mO.VOLUME_INDICATOR,e)}),JN("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 FD(Bw.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new FD(Bw.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 FD(Bw.LIVE_STREAMING_TASK_CONFLICT);const i=t?RV.TRANSCODE:RV.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(RV.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new FD(Bw.INVALID_PARAMS,"can not find live streaming url to stop");await Wh.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){MB(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){MB(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)}sendAudioMetadata(e){this._p2pChannel instanceof Hj&&this._p2pChannel.addAudioMetadata(e)}sendAudioPts(e){this._p2pChannel instanceof Hj&&this._p2pChannel.addAudioPts(e)}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new FD(Bw.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=Xn(n=Array.from(i)).call(n,((e,t)=>e+t),0),o={serverTs:0,seq:oD++,length:i.length,checkSum:r},s=new Uint8Array($O(r,2)),a=new ArrayBuffer(rD),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=jO(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:tD,additionalData:s},t,i);return jO(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new FD(Bw.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(_V.DATA_STREAM,{payload:FO(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-qj},!i)}sendMetadata(e){if(!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new FD(Bw.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(_V.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:FO(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(PD),!this._joinInfo)throw new FD(Bw.INVALID_OPERATION,"can not send custom report, not joined");await xD.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(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(JN("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((i=>{Dn(t).call(t,i)||delete e[i]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){Ww(t.spatialLayer,"spatialLayer",[0,1,2,3]),Ww(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw ND.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(Gw(t,"apRTM"),Hw(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,ND.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(ND.debug("[".concat(this._clientId,"] reset client")),function(e){const t=RU.indexOf(e);-1!==t&&RU.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this._pendingRtpCapabilityChange=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=Xb.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&CG(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&xD.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&xD.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),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 sN("client-publish",this._clientId),this._subscribeMutex=new sN("client-subscribe",this._clientId),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||zO();e?ND.debug("[".concat(this._clientId,"] new Session ").concat(n)):ND.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,xD.addSid(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,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};xD.sessionInit(this._sessionId,ZW({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 FD(Bw.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&JN("FORCE_TURN")&&!JN("TURN_ENABLE_TCP")&&!JN("TURN_ENABLE_UDP"))throw new FD(Bw.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");ND.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(cx.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!==Bw.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 dM&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{ND.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))})),!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)===Bw.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new FD(Bw.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));ND.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<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==Bw.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===Bw.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new FD(Bw.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},kF("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>
6{xD.reportApiInvoke(this._sessionId,{name:aO.ON_LIVE_STREAM_ERROR,options:[e,t],tag:cO.TRACER}).onSuccess(),this.safeEmit(mO.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{xD.reportApiInvoke(this._sessionId,{name:aO.ON_LIVE_STREAM_WARNING,options:[e,t],tag:cO.TRACER}).onSuccess(),this.safeEmit(mO.LIVE_STREAMING_WARNING,e,t)},e.on(bV.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new FD(Bw.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const r=JN("UAP_AP").slice(0,JN("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 iB(r,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,cN).then(t).catch(i)})),e};return e===RV.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new FD(Bw.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}},kF("ChannelMediaRelay").create(e));n.on("state",(e=>{e===PV.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(mO.CHANNEL_MEDIA_RELAY_STATE,e)})),n.on("event",(e=>{this.safeEmit(mO.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 ND.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));ND.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 MF(e,!0)}(e);c._dataChannels.push(i),ND.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(mO.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(ND.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{ND.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})),t&&(this.safeEmit(mO.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 ND.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&&(ND.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)})),ND.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(mO.USER_UNPUBLISHED,n,"datachannel",r._
vendor: 7,049 bytes, line 6
6config))}))}_getEncodingName(e){var t,i;if(!this._joinResponse)return;const n=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!n)return;for(const t of n){var r;if(t.payloadType===e)return null==t||null===(r=t.rtpMap)||void 0===r?void 0:r.encodingName}const o=null===(i=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===i?void 0:i.videoCodecs;if(o)for(const t of o){var s;if(t.payloadType===e)return null==t||null===(s=t.rtpMap)||void 0===s?void 0:s.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){ND.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{ND.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(mO.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 ND.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(MV.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void ND.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach((e=>{const{value:n,type:r,expires:o}=t[e];o&&o<=i||r||vU()||!Object.prototype.hasOwnProperty.call(HN,e)||(ZN[e]=n,qN[e]=n,ND.debug("Update gateway parameters from config distribute",e,n))}))}catch(e){ND.error("Error update config from local cache",e.message)}}()})),this._gateway.on(MV.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(MV.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===uO.FALLBACK)return;const r=()=>{this.safeEmit(mO.CONNECTION_STATE_CHANGE,e,t,i)};if(xD.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:aO.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:cO.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),ND.info("[".concat(this._clientId,"] signal 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=>{ND.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{ND.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),JN("VOS_CONFIGURE")&&Array.isArray(JN("VOS_CONFIGURE"))&&JN("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(JN("VOS_CONFIGURE")).catch((e=>{ND.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),ND.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{ND.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{ND.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{ND.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),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=>{ND.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_||(ND.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,YV.AUDIO,!1)),e._trust_video_mute_state_||(ND.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,YV.VIDEO,!1)),e._trust_audio_enabled_state_||(ND.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(ND.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(ND.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(ND.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(ND.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(MV.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new FD(Bw.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;if(this._fallbackServerInfo)t=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,xD.reportApiInvoke(this._sessionId,{name:aO.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:cO.TRACER}).onSuccess(),ND.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await SG(ZW(ZW({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,vG(e),this._joinInfo.preload=!0):(t=await mB(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||cN,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 i=[];
6t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[n,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r})})),e(i)}catch(e){t(e)}})),this._gateway.on(MV.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(mO.NETWORK_QUALITY,e)})),this._gateway.on(MV.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(mO.STREAM_TYPE_CHANGED,e,t);xD.reportApiInvoke(this._sessionId,{name:aO.STREAM_TYPE_CHANGE,options:[e,t],tag:cO.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(MV.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(MV.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(MV.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let i;this._joinResponse=e,e.attributes?i=e.attributes.userAttributes.preSubSsrcs:ND.debug("no attributes in joinResponse");const n=sF(e.ortc,t,i);this._p2pChannel.connect(n)})),this._gateway.on(MV.PRE_CONNECT_PC,(async(e,t,i)=>{const{candidates:n,fingerprint:r,turnServer:o}=e;if(this._joinInfo&&n.length>0&&!this._p2pChannel.isPlanB){const{cert:e,cid:a}=this._joinInfo.apResponse,c="".concat(a,"_").concat(e);if(c.length<4||c.length>256)return void ND.debug("[".concat(this._clientId,"] ufrag length is not valid, length: ").concat(c.length));await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});try{var s;t(await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(a,"_").concat(e),icePwd:"".concat(a,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(s=JN("FINGERPRINT"))&&void 0!==s?s:r}]},candidates:n,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0}))}catch(e){e.code&&e.code===Bw.EXCHANGE_SDP_FAILED&&await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0),i(e)}}})),this._gateway.on(MV.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(mO.FALLBACK_TO_HLS,fO.VOSERROR)})),this._gateway.on(MV.RESET_SIGNAL,(()=>{this._p2pChannel instanceof Hj&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(MV.DATACHANNEL_FAILBACK,(()=>{xD.reportApiInvoke(this._sessionId,{name:aO.DATACHANNEL_FAILBACK,options:{},tag:cO.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(mV.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(mV.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(mV.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc))),this._gateway.signal.on(mV.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(mV.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(mV.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)})),this._gateway.signal.on(mV.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(mV.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(mV.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,YV.AUDIO,!0))),this._gateway.signal.on(mV.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,YV.AUDIO,!1))),this._gateway.signal.on(mV.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,YV.VIDEO,!0))),this._gateway.signal.on(mV.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,YV.VIDEO,!1))),this._gateway.signal.on(mV.RECEIVE_METADATA,(e=>{const t=xO(e.metadata);this.safeEmit(mO.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(mV.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let i=xO(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.length<rD)throw new FD(Bw.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(rD));const t=await async function(e,t,i){const n=i.subarray(0,rD),r=n.slice(8,rD),o=(r[0]<<8)+r[1],s=(n[6]<<8)+n[7],a=await window.crypto.subtle.decrypt({
vendor: 30,961 bytes, line 6
6name:"AES-GCM",iv:e,tagLength:tD,additionalData:new Uint8Array($O(o,2))},t,i.subarray(rD));return new Uint8Array(a).subarray(0,s)}(this._encryptDataStreamIv,this._encryptDataStreamKey,i);i=t}let n=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),i=this.remoteUsers.find((t=>t.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||Number.isNaN(n))&&(n=0),eG(ZW(ZW({},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(mV.ON_CRYPT_ERROR,(()=>{VO((()=>{ND.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(mO.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(mV.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(mV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{ND.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,uO.TOKEN_EXPIRE),this.safeEmit(mO.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(mV.ON_STREAM_FALLBACK_UPDATE,(e=>{ND.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(mO.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(mV.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===_O.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{ND.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(mV.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),ND.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(mV.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(mV.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(pV.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case _V.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===kV.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t!==kV.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===kV.Screen||t===kV.ScreenLow}));"offer"===t.state&&xD.publish(this._joinInfo.sid,{eventElapse:NB.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Bw.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===kV.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!==kV.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case _V.SUBSCRIBE:t&&xD.subscribe(this._joinInfo.sid,{succ:!1,ec:Bw.TIMEOUT,audio:t.stream_type===YV.AUDIO,video:t.stream_type===YV.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:NB.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(mV.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(mV.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;JN("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!CU(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 UB(n.string_id||n.stream_id,n.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}),0===this.getListeners(mO.PUBLISHED_USER_LIST).length&&(ND.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(mO.USER_JOINED,e)));const r=VV.Audio&n.stream_type,o=(VV.Video|VV.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(mO.PUBLISHED_USER_LIST).length&&(ND.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(mO.USER_PUBLISHED,e,"audio")),o&&!c&&0===this.getListeners(mO.PUBLISHED_USER_LIST).length&&(ND.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(mO.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&&(ND.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=>{ND.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(mO.PUBLISHED_USER_LIST).length>0?JN("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(ND.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(mO.PUBLISHED_USER_LIST,t)):ND.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(mV.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;if(this._p2pChannel instanceof Hj){if("audience"===this.role&&JN("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void ND.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return Dn(t=Object.keys(eD)).call(t,e)})))}})),this._gateway.signal.on(pV.VOS_FALLBACK_PROMISE,(async(e,t,i)=>{if("FALLBACKCN"===e&&JN("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return i(new FD(Bw.UNEXPECTED_ERROR,"can not recover, no join info"));ND.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const n=await mB(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||cN,this.store);if(JN("QUALITY_FALLBACK_REHEARSAL"))return xD.reportApiInvoke(this._sessionId,{name:aO.VOS_FALLBACK_CN,options:{cur:n.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:cO.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void i();this._fallbackServerInfo=n,t()}catch(e){var n;const t=null==e||null===(n=e.data)||void 0===n?void 0:n.desc;JN("QUALITY_FALLBACK_REHEARSAL")?(xD.reportApiInvoke(this._sessionId,{name:aO.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:cO.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(t)&&Dn(t).call(t,"request downgrade fallback")&&this.safeEmit(mO.FALLBACK_TO_HLS,fO.AP_ERROR),i(e)}}else i()}))}_handleP2PEvents(){this._gateway.signal.on(mV.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(cx.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.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,r,!!a)}))})),this._gateway.signal.on(cx.CALL,(async(e,t,i)=>{if(this.store.useP2P)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(pV.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(cx.UNPUBLISH,(async(e,t,i)=>{if(this.store.useP2P){const{unpubMsg:n,uid:r}=e,o=this._users.find((e=>e.uid===r));if(!o)return ND.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===kV.Audio?YV.AUDIO:YV.VIDEO;await this._p2pChannel.unsubscribe(o,i),this._handleMuteStream(r,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(cx.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case lx.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,YV.VIDEO,!0);break;case lx.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,YV.AUDIO,!0);break;case lx.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,YV.VIDEO,!1);break;case lx.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,YV.AUDIO,!1)}})),this._gateway.signal.on(cx.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const{direction:i,iceParameter:n}=e;if(i!==fV.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(cx.CANDIDATE,(e=>{if(this.store.useP2P){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(ZV.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(cx.RESTART_ICE,e,i===fV.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(ZV.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(cx.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(ZV.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(cx.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(ZV.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===Bw.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(ZV.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===Bw.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(ZV.StateChange,((e,t)=>{t===QV.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(ZV.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(mO.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(ZV.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===Bw.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(ZV.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===Bw.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(ZV.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(ZV.RequestRePublishDataChannel,((e,t,i)=>{Wh.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!==Bw.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(ZV.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===YV.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(ZV.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(ZV.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(ZV.MediaReconnectStart,(e=>{this.safeEmit(mO.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(ZV.MediaReconnectEnd,(e=>{this.safeEmit(mO.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(ZV.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(ZV.RequestRestartICE,(async e=>{if(this.store.useP2P)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(ZV.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(ZV.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=sF(r,o);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(ZV.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(ZV.P2PLost,(()=>{this.safeEmit(mO.P2P_LOST,this.store.uid)})),this._p2pChannel.on(ZV.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(ZV.ConnectionTypeChange,(e=>{this.safeEmit(mO.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(ZV.FirstVideoBufferReady,((e,t)=>{this.safeEmit(mO.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(ZV.FirstVideoPreRender,((e,t)=>{this.safeEmit(mO.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(ZV.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(ZV.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(ZV.AudioMetadata,(e=>{this.safeEmit(mO.AUDIO_METADATA,e)})),this._p2pChannel.on(ZV.AudioPts,(e=>{this.safeEmit(mO.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new FD(Bw.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},kF("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},cN)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(tx.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(mO.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===$V.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(mO.CONTENT_INSPECT_ERROR,new FD(Bw.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(tx.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===Bw.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return ND.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(mO.CONTENT_INSPECT_RESULT,e,t)})),e.on(tx.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new FD(Bw.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(Gw(e,"enabled"),e){if(!t)throw new FD(Bw.INVALID_PARAMS,"config is required");if(sW(t),!this._joinInfo)throw new FD(Bw.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},kF("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},cN)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new FD(Bw.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(sx.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(mO.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===ox.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new FD(Bw.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(sx.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){Ww(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new FD(Bw.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,ND.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return ND.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Gw(e,"enabled"),XN("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_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}}},sV(JW.prototype,"leave",[cW],Object.getOwnPropertyDescriptor(JW.prototype,"leave"),JW.prototype),sV(JW.prototype,"publish",[dW],Object.getOwnPropertyDescriptor(JW.prototype,"publish"),JW.prototype),sV(JW.prototype,"unpublish",[lW],Object.getOwnPropertyDescriptor(JW.prototype,"unpublish"),JW.prototype),sV(JW.prototype,"subscribe",[uW],Object.getOwnPropertyDescriptor(JW.prototype,"subscribe"),JW.prototype),sV(JW.prototype,"presubscribe",[hW],Object.getOwnPropertyDescriptor(JW.prototype,"presubscribe"),JW.prototype),sV(JW.prototype,"massSubscribe",[pW],Object.getOwnPropertyDescriptor(JW.prototype,"massSubscribe"),JW.prototype),sV(JW.prototype,"unsubscribe",[_W],Object.getOwnPropertyDescriptor(JW.prototype,"unsubscribe"),JW.prototype),sV(JW.prototype,"massUnsubscribe",[EW],Object.getOwnPropertyDescriptor(JW.prototype,"massUnsubscribe"),JW.prototype),sV(JW.prototype,"setLowStreamParameter",[mW],Object.getOwnPropertyDescriptor(JW.prototype,"setLowStreamParameter"),JW.prototype),sV(JW.prototype,"setDualStreamMode",[fW],Object.getOwnPropertyDescriptor(JW.prototype,"setDualStreamMode"),JW.prototype),sV(JW.prototype,"enableDualStream",[SW],Object.getOwnPropertyDescriptor(JW.prototype,"enableDualStream"),JW.prototype),sV(JW.prototype,"disableDualStream",[gW],Object.getOwnPropertyDescriptor(JW.prototype,"disableDualStream"),JW.prototype),sV(JW.prototype,"setClientRole",[TW],Object.getOwnPropertyDescriptor(JW.prototype,"setClientRole"),JW.prototype),sV(JW.prototype,"_setClientRoleOptions",[RW],Object.getOwnPropertyDescriptor(JW.prototype,"_setClientRoleOptions"),JW.prototype),sV(JW.prototype,"setProxyServer",[CW],Object.getOwnPropertyDescriptor(JW.prototype,"setProxyServer"),JW.prototype),sV(JW.prototype,"setTurnServer",[vW],Object.getOwnPropertyDescriptor(JW.prototype,"setTurnServer"),JW.prototype),sV(JW.prototype,"setLicense",[yW],Object.getOwnPropertyDescriptor(JW.prototype,"setLicense"),JW.prototype),sV(JW.prototype,"startProxyServer",[IW],Object.getOwnPropertyDescriptor(JW.prototype,"startProxyServer"),JW.prototype),sV(JW.prototype,"stopProxyServer",[AW],Object.getOwnPropertyDescriptor(JW.prototype,"stopProxyServer"),JW.prototype),sV(JW.prototype,"setLocalAccessPointsV2",[bW],Object.getOwnPropertyDescriptor(JW.prototype,"setLocalAccessPointsV2"),JW.prototype),sV(JW.prototype,"setLocalAccessPoints",[wW],Object.getOwnPropertyDescriptor(JW.prototype,"setLocalAccessPoints"),JW.prototype),sV(JW.prototype,"setRemoteDefaultVideoStreamType",[OW],Object.getOwnPropertyDescriptor(JW.prototype,"setRemoteDefaultVideoStreamType"),JW.prototype),sV(JW.prototype,"setRemoteVideoStreamType",[NW],Object.getOwnPropertyDescriptor(JW.prototype,"setRemoteVideoStreamType"),JW.prototype),sV(JW.prototype,"setStreamFallbackOption",[DW],Object.getOwnPropertyDescriptor(JW.prototype,"setStreamFallbackOption"),JW.prototype),sV(JW.prototype,"setEncryptionConfig",[PW],Object.getOwnPropertyDescriptor(JW.prototype,"setEncryptionConfig"),JW.prototype),sV(JW.prototype,"renewToken",[LW],Object.getOwnPropertyDescriptor(JW.prototype,"renewToken"),JW.prototype),sV(JW.prototype,"enableAudioVolumeIndicator",[kW],Object.getOwnPropertyDescriptor(JW.prototype,"enableAudioVolumeIndicator"),JW.prototype),sV(JW.prototype,"startLiveStreaming",[MW],Object.getOwnPropertyDescriptor(JW.prototype,"startLiveStreaming"),JW.prototype),sV(JW.prototype,"setLiveTranscoding",[UW],Object.getOwnPropertyDescriptor(JW.prototype,"setLiveTranscoding"),JW.prototype),sV(JW.prototype,"stopLiveStreaming",[VW],Object.getOwnPropertyDescriptor(JW.prototype,"stopLiveStreaming"),JW.prototype),sV(JW.prototype,"startChannelMediaRelay",[xW],Object.getOwnPropertyDescriptor(JW.prototype,"startChannelMediaRelay"),JW.prototype),sV(JW.prototype,"updateChannelMediaRelay",[FW],Object.getOwnPropertyDescriptor(JW.prototype,"updateChannelMediaRelay"),JW.prototype),sV(JW.prototype,"stopChannelMediaRelay",[BW],Object.getOwnPropertyDescriptor(JW.prototype,"stopChannelMediaRelay"),JW.prototype),sV(JW.prototype,"sendCustomReportMessage",[jW],Object.getOwnPropertyDescriptor(JW.prototype,"sendCustomReportMessage"),JW.prototype),sV(JW.prototype,"pickSVCLayer",[GW],Object.getOwnPropertyDescriptor(JW.prototype,"pickSVCLayer"),JW.prototype),sV(JW.prototype,"setRTMConfig",[WW],Object.getOwnPropertyDescriptor(JW.prototype,"setRTMConfig"),JW.prototype),sV(JW.prototype,"enableContentInspect",[HW],Object.getOwnPropertyDescriptor(JW.prototype,"enableContentInspect"),JW.prototype),sV(JW.prototype,"disableContentInspect",[KW],Object.getOwnPropertyDescriptor(JW.prototype,"disableContentInspect"),JW.prototype),sV(JW.prototype,"setImageModeration",[YW],Object.getOwnPropertyDescriptor(JW.prototype,"setImageModeration"),JW.prototype),sV(JW.prototype,"setP2PTransport",[zW],Object.getOwnPropertyDescriptor(JW.prototype,"setP2PTransport"),JW.prototype),sV(JW.prototype,"getJoinChannelServiceRecords",[qW],Object.getOwnPropertyDescriptor(JW.prototype,"getJoinChannelServiceRecords"),JW.prototype),sV(JW.prototype,"setPublishAudioFilterEnabled",[XW],Object.getOwnPropertyDescriptor(JW.prototype,"setPublishAudioFilterEnabled"),JW.prototype),JW);function eH(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=YO(5,"client-"),n=xD.reportApiInvoke(null,{id:i,name:aO.CREATE_CLIENT,options:[t],tag:cO.TRACER});try{!function(e){Ww(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),Ww(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&Ww(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Yw(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&pO(e.turnServer),void 0!==e.httpRetryConfig&&dO(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&dO(e.websocketRetryConfig)}(t)}catch(e){throw n.onError(e),e}return(vw(16,0,!0)||yw(16,0,!0))&&("vp9"===t.codec&&(t.codec="vp8",ND.debug("browser not support vp9, force use vp8")),XN("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),n.onSuccess(),new $W(ZW(ZW({forceWaitGatewayResponse:!0},t),{},{role:Dn(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}),i)}function tH(){let e=!1;const t=sw();return(t.name===iw.CHROME&&Number(t.version)>=58&&("WebKit"!==rw.engine.name||function(){const e=sw();if(lw()){if(e.os===tw.MAC_OS)return!0;if(e.os===tw.IOS){const e=rw.os.version&&rw.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}())||t.name===iw.FIREFOX&&Number(t.version)>=56||t.name===iw.OPERA&&Number(t.version)>=45||t.name===iw.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(Ew()||Nw())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||Dw()||sw().name===iw.QQ)&&(e=!0),e}class iH{constructor(e,t){bI(this,"id",0),bI(this,"element",void 0),bI(this,"peerPair",void 0),bI(this,"context",void 0),bI(this,"audioPlayerElement",void 0),bI(this,"audioTrack",void 0),iH.count+=1,this.id=iH.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 Wh((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 FD(Bw.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 FD(Bw.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new FD(Bw.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(){ND.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 nH,rH;bI(iH,"count",0);const oH=window.AudioContext||window.webkitAudioContext;const sH=new(nH=VD({report:xD}),sV((rH=class{constructor(){bI(this,"units",[]),bI(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return ND.debug("the system does not need to process local aec"),-1;this.context||(this.context=new oH);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new iH(e,this.context),this.units.push(t)),t.startEchoCancellation(),ND.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return sw().name!==iw.SAFARI}}).prototype,"processExternalMediaAEC",[nH],Object.getOwnPropertyDescriptor(rH.prototype,"processExternalMediaAEC"),rH.prototype),rH);function aH(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 cH(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aH(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aH(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const dH=window||document;function lH(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!dH)return;const i=JX._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(JX.onSecurityPolicyViolation||JX.getListeners(rx.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;JN("CSP_DETECTED_HOSTNAME_LIST").some((e=>Dn(t).call(t,e)))&&(JX.onSecurityPolicyViolation&&"function"==typeof JX.onSecurityPolicyViolation&&JX.onSecurityPolicyViolation(e),JX.getListeners(rx.SECURITY_POLICY_VIOLATION).length>0&&JX.safeEmit(rx.SECURITY_POLICY_VIOLATION,e))};i&&dH.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||JX.getListeners(rx.SECURITY_POLICY_VIOLATION).length>0)&&dH.addEventListener("securitypolicyviolation",n),JX._cspEventHandlerPointer=n}var uH=l,hH=Og,pH=RegExp.prototype,_H=function(e){return e===pH||uH(pH,e)?hH(e):e.flags},EH=i(_H);function mH(e){let t=e.length;for(;--t>=0;)e[t]=0}const fH=256,SH=286,gH=30,TH=15,RH=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]),CH=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]),vH=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),yH=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),IH=new Array(576);mH(IH);const AH=new Array(60);mH(AH);const bH=new Array(512);mH(bH);const wH=new Array(256);mH(wH);const OH=new Array(29);mH(OH);const NH=new Array(gH);function DH(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 PH,LH,kH;function MH(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}mH(NH);const UH=e=>e<256?bH[e]:bH[256+(e>>>7)],VH=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},xH=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,VH(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},FH=(e,t,i)=>{xH(e,i[2*t],i[2*t+1])},BH=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},jH=(e,t,i)=>{const n=new Array(16);let r,o,s=0;for(r=1;r<=TH;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]=BH(n[t]++,t))}},GH=e=>{let t;for(t=0;t<SH;t++)e.dyn_ltree[2*t]=0;for(t=0;t<gH;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},WH=e=>{e.bi_valid>8?VH(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},HH=(e,t,i,n)=>{const r=2*t,o=2*i;return e[r]<e[o]||e[r]===e[o]&&n[t]<=n[i]},KH=(e,t,i)=>{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r<e.heap_len&&HH(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!HH(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n},YH=(e,t,i)=>{let n,r,o,s,a=0;
vendor: 4,225 bytes, line 6
6if(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?FH(e,r,t):(o=wH[r],FH(e,o+fH+1,t),s=RH[o],0!==s&&(r-=OH[o],xH(e,r,s)),n--,o=UH(n),FH(e,o,i),s=CH[o],0!==s&&(n-=NH[o],xH(e,n,s)))}while(a<e.sym_next);FH(e,256,t)},zH=(e,t)=>{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<o;s++)0!==i[2*s]?(e.heap[++e.heap_len]=d=s,e.depth[s]=0):i[2*s+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,i[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[2*c+1]);for(t.max_code=d,s=e.heap_len>>1;s>=1;s--)KH(e,i,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],KH(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++,KH(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<=TH;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),jH(i,d,e.bl_count)},qH=(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<c&&r===s||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4))},XH=(e,t,i)=>{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<c&&r===s)){if(a<d)do{FH(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==o&&(FH(e,r,e.bl_tree),a--),FH(e,16,e.bl_tree),xH(e,a-3,2)):a<=10?(FH(e,17,e.bl_tree),xH(e,a-3,3)):(FH(e,18,e.bl_tree),xH(e,a-11,7));a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4)}};let JH=!1;const QH=(e,t,i,n)=>{xH(e,0+(n?1:0),3),WH(e),VH(e,i),VH(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var ZH=e=>{JH||((()=>{let e,t,i,n,r;const o=new Array(16);for(i=0,n=0;n<28;n++)for(OH[n]=i,e=0;e<1<<RH[n];e++)wH[i++]=n;for(wH[i-1]=n,r=0,n=0;n<16;n++)for(NH[n]=r,e=0;e<1<<CH[n];e++)bH[r++]=n;for(r>>=7;n<gH;n++)for(NH[n]=r<<7,e=0;e<1<<CH[n]-7;e++)bH[256+r++]=n;for(t=0;t<=TH;t++)o[t]=0;for(e=0;e<=143;)IH[2*e+1]=8,e++,o[8]++;for(;e<=255;)IH[2*e+1]=9,e++,o[9]++;for(;e<=279;)IH[2*e+1]=7,e++,o[7]++;for(;e<=287;)IH[2*e+1]=8,e++,o[8]++;for(jH(IH,287,o),e=0;e<gH;e++)AH[2*e+1]=5,AH[2*e]=BH(e,5);PH=new DH(IH,RH,257,SH,TH),LH=new DH(AH,CH,0,gH,TH),kH=new DH(new Array(0),vH,0,19,7)})(),JH=!0),e.l_desc=new MH(e.dyn_ltree,PH),e.d_desc=new MH(e.dyn_dtree,LH),e.bl_desc=new MH(e.bl_tree,kH),e.bi_buf=0,e.bi_valid=0,GH(e)},$H=(e,t,i,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<fH;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),zH(e,e.l_desc),zH(e,e.d_desc),s=(e=>{let t;for(qH(e,e.dyn_ltree,e.l_desc.max_code),qH(e,e.dyn_dtree,e.d_desc.max_code),zH(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*yH[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?QH(e,t,i,n):4===e.strategy||o===r?(xH(e,2+(n?1:0),3),YH(e,IH,AH)):(xH(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(xH(e,t-257,5),xH(e,i-1,5),xH(e,n-4,4),r=0;r<n;r++)xH(e,e.bl_tree[2*yH[r]+1],3);XH(e,e.dyn_ltree,t-1),XH(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),YH(e,e.dyn_ltree,e.dyn_dtree)),GH(e),n&&WH(e)},eK=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>
vendor: 4,208 bytes, line 6
68,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(wH[i]+fH+1)]++,e.dyn_dtree[2*UH(t)]++),e.sym_next===e.sym_end),tK=e=>{xH(e,2,3),FH(e,256,IH),(e=>{16===e.bi_valid?(VH(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)},iK={_tr_init:ZH,_tr_stored_block:QH,_tr_flush_block:$H,_tr_tally:eK,_tr_align:tK};var nK=(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 rK=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 oK=(e,t,i,n)=>{const r=rK,o=n+i;e^=-1;for(let i=n;i<o;i++)e=e>>>8^r[255&(e^t[i])];return-1^e},sK={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"},aK={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:cK,_tr_stored_block:dK,_tr_flush_block:lK,_tr_tally:uK,_tr_align:hK}=iK,{Z_NO_FLUSH:pK,Z_PARTIAL_FLUSH:_K,Z_FULL_FLUSH:EK,Z_FINISH:mK,Z_BLOCK:fK,Z_OK:SK,Z_STREAM_END:gK,Z_STREAM_ERROR:TK,Z_DATA_ERROR:RK,Z_BUF_ERROR:CK,Z_DEFAULT_COMPRESSION:vK,Z_FILTERED:yK,Z_HUFFMAN_ONLY:IK,Z_RLE:AK,Z_FIXED:bK,Z_DEFAULT_STRATEGY:wK,Z_UNKNOWN:OK,Z_DEFLATED:NK}=aK,DK=286,PK=30,LK=19,kK=2*DK+1,MK=15,UK=258,VK=262,xK=42,FK=113,BK=666,jK=(e,t)=>(e.msg=sK[t],t),GK=e=>2*e-(e>4?9:0),WK=e=>{let t=e.length;for(;--t>=0;)e[t]=0},HK=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 KK=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const YK=e=>{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))},zK=(e,t)=>{lK(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,YK(e.strm)},qK=(e,t)=>{e.pending_buf[e.pending++]=t},XK=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},JK=(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=nK(e.adler,t,r,i):2===e.state.wrap&&(e.adler=oK(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},QK=(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-VK?e.strstart-(e.w_size-VK):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+UK;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]&&o<h);if(n=UK-(h-o),o=h-UK,n>s){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},ZK=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-VK)&&(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),HK(e),n+=t),0===e.strm.avail_in)break;if(i=JK(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=KK(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=KK(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<VK&&0!==e.strm.avail_in)},$K=(e,t)=>{let i,n,r,o=e.pending_buf_size-5>
vendor: 3,202 bytes, line 6
6e.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_out<r)break;if(r=e.strm.avail_out-r,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i<o&&(0===i&&t!==mK||t===pK||i!==n+e.strm.avail_in))break;s=t===mK&&i===n+e.strm.avail_in?1:0,dK(e,0,0,s),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,YK(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&&(JK(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_water<e.strstart&&(e.high_water=e.strstart),s?4:t!==pK&&t!==mK&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&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&&(JK(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<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>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===mK)&&t!==pK&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,s=t===mK&&0===e.strm.avail_in&&i===n?1:0,dK(e,e.block_start,i,s),e.block_start+=i,YK(e.strm)),s?3:1)},eY=(e,t)=>{let i,n;for(;;){if(e.lookahead<VK){if(ZK(e),e.lookahead<VK&&t===pK)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=KK(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-VK&&(e.match_length=QK(e,i)),e.match_length>=3)if(n=uK(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=KK(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=KK(e,e.ins_h,e.window[e.strstart+1]);else n=uK(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(zK(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===mK?(zK(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(zK(e,!1),0===e.strm.avail_out)?1:2},tY=(e,t)=>
vendor: 5,648 bytes, line 6
6{let i,n,r;for(;;){if(e.lookahead<VK){if(ZK(e),e.lookahead<VK&&t===pK)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=KK(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_length<e.max_lazy_match&&e.strstart-i<=e.w_size-VK&&(e.match_length=QK(e,i),e.match_length<=5&&(e.strategy===yK||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=uK(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=KK(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&&(zK(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=uK(e,0,e.window[e.strstart-1]),n&&zK(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=uK(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===mK?(zK(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(zK(e,!1),0===e.strm.avail_out)?1:2};function iY(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 nY=[new iY(0,0,0,0,$K),new iY(4,4,8,4,eY),new iY(4,5,16,8,eY),new iY(4,6,32,32,eY),new iY(4,4,16,16,tY),new iY(8,16,32,32,tY),new iY(8,16,128,128,tY),new iY(8,32,128,256,tY),new iY(32,128,258,1024,tY),new iY(32,258,258,4096,tY)];function rY(){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=NK,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*kK),this.dyn_dtree=new Uint16Array(2*(2*PK+1)),this.bl_tree=new Uint16Array(2*(2*LK+1)),WK(this.dyn_ltree),WK(this.dyn_dtree),WK(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MK+1),this.heap=new Uint16Array(2*DK+1),WK(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*DK+1),WK(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 oY=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==xK&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==FK&&t.status!==BK?1:0},sY=e=>{if(oY(e))return jK(e,TK);e.total_in=e.total_out=0,e.data_type=OK;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?xK:FK,e.adler=2===t.wrap?0:1,t.last_flush=-2,cK(t),SK},aY=e=>{const t=sY(e);return t===SK&&(e=>{e.window_size=2*e.w_size,WK(e.head),e.max_lazy_match=nY[e.level].max_lazy,e.good_match=nY[e.level].good_length,e.nice_match=nY[e.level].nice_length,e.max_chain_length=nY[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},cY=(e,t,i,n,r,o)=>{if(!e)return TK;let s=1;if(t===vK&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||i!==NK||n<8||n>15||t<0||t>9||o<0||o>bK||8===n&&1!==s)return jK(e,TK);8===n&&(n=9);const a=new rY;return e.state=a,a.strm=e,a.status=xK,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=o,a.method=i,aY(e)};var dY=(e,t)=>{if(oY(e)||t>fK||t<0)return e?jK(e,TK):TK;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===BK&&t!==mK)return jK(e,0===e.avail_out?CK:TK);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(YK(e),0===e.avail_out)return i.last_flush=-1,SK}else if(0===e.avail_in&&GK(t)<=GK(n)&&t!==mK)return jK(e,CK);if(i.status===BK&&0!==e.avail_in)return jK(e,CK);if(i.status===xK&&0===i.wrap&&(i.status=FK),i.status===xK){let t=NK+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=IK||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,XK(i,t),0!==i.strstart&&(XK(i,e.adler>>>16),XK(i,65535&e.adler)),e.adler=1,i.status=FK,YK(e),0!==i.pending)return i.last_flush=-1,SK}if(57===i.status)if(e.adler=0,qK(i,31),qK(i,139),qK(i,8),i.gzhead)qK(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)),qK(i,255&i.gzhead.time),qK(i,i.gzhead.time>>8&255),qK(i,i.gzhead.time>>16&255),qK(i,i.gzhead.time>>24&255),qK(i,9===i.level?2:i.strategy>=IK||i.level<2?4:0),qK(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(qK(i,255&i.gzhead.extra.length),qK(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=oK(e.adler,i.pending_buf,i.pending,0)),i.gz
vendor: 9,720 bytes, line 6
6index=0,i.status=69;else if(qK(i,0),qK(i,0),qK(i,0),qK(i,0),qK(i,0),qK(i,9===i.level?2:i.strategy>=IK||i.level<2?4:0),qK(i,3),i.status=FK,YK(e),0!==i.pending)return i.last_flush=-1,SK;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=oK(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,YK(e),0!==i.pending)return i.last_flush=-1,SK;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=oK(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=oK(e.adler,i.pending_buf,i.pending-n,n)),YK(e),0!==i.pending)return i.last_flush=-1,SK;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,qK(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=oK(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=oK(e.adler,i.pending_buf,i.pending-n,n)),YK(e),0!==i.pending)return i.last_flush=-1,SK;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,qK(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=oK(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&&(YK(e),0!==i.pending))return i.last_flush=-1,SK;qK(i,255&e.adler),qK(i,e.adler>>8&255),e.adler=0}if(i.status=FK,YK(e),0!==i.pending)return i.last_flush=-1,SK}if(0!==e.avail_in||0!==i.lookahead||t!==pK&&i.status!==BK){let n=0===i.level?$K(i,t):i.strategy===IK?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(ZK(e),0===e.lookahead)){if(t===pK)return 1;break}if(e.match_length=0,i=uK(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(zK(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===mK?(zK(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(zK(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===AK?((e,t)=>{let i,n,r,o;const s=e.window;for(;;){if(e.lookahead<=UK){if(ZK(e),e.lookahead<=UK&&t===pK)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+UK;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]&&r<o);e.match_length=UK-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=uK(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=uK(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(zK(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===mK?(zK(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(zK(e,!1),0===e.strm.avail_out)?1:2})(i,t):nY[i.level].func(i,t);if(3!==n&&4!==n||(i.status=BK),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),SK;if(2===n&&(t===_K?hK(i):t!==fK&&(dK(i,0,0,!1),t===EK&&(WK(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),YK(e),0===e.avail_out))return i.last_flush=-1,SK}return t!==mK?SK:i.wrap<=0?gK:(2===i.wrap?(qK(i,255&e.adler),qK(i,e.adler>>8&255),qK(i,e.adler>>16&255),qK(i,e.adler>>24&255),qK(i,255&e.total_in),qK(i,e.total_in>>8&255),qK(i,e.total_in>>16&255),qK(i,e.total_in>>24&255)):(XK(i,e.adler>>>16),XK(i,65535&e.adler)),YK(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?SK:gK)},lY=(e,t)=>{let i=t.length;if(oY(e))return TK;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==xK||n.lookahead)return TK;if(1===r&&(e.adler=nK(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(WK(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,ZK(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=KK(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,ZK(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,SK},uY={deflateInit:(e,t)=>cY(e,t,NK,15,8,wK),deflateInit2:cY,deflateReset:aY,deflateResetKeep:sY,deflateSetHeader:(e,t)=>oY(e)||2!==e.state.wrap?TK:(e.state.gzhead=t,SK),deflate:dY,deflateEnd:e=>{if(oY(e))return TK;const t=e.state.status;return e.state=null,t===FK?jK(e,RK):SK},deflateSetDictionary:lY,deflateInfo:"pako deflate (from Nodeca project)"};const hY=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var pY={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)hY(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,r=e.length;t<r;t++){let r=e[t];i.set(r,n),n+=r.length}return i}};let _Y=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){_Y=!1}const EY=new Uint8Array(256);for(let e=0;e<256;e++)EY[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;EY[254]=EY[254]=1;var mY={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<s;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<s&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(a),o=0,r=0;o<a;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<s&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[o++]=i:i<2048?(t[o++]=192|i>>>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;n<i;){let t=e[n++];if(t<128){o[r++]=t;continue}let s=EY[t];if(s>4)o[r++]=65533,n+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&n<i;)t=t<<6|63&e[n++],s--;s>1?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&&_Y)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i})(o,r)},utf8border:(e,t)=>{(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+EY[e[i]]>t?i:t}};var fY=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 SY=Object.prototype.toString,{Z_NO_FLUSH:gY,Z_SYNC_FLUSH:TY,Z_FULL_FLUSH:RY,Z_FINISH:CY,Z_OK:vY,Z_STREAM_END:yY,Z_DEFAULT_COMPRESSION:IY,Z_DEFAULT_STRATEGY:AY,Z_DEFLATED:bY}=aK;function wY(e){this.options=pY.assign({level:IY,method:bY,chunkSize:16384,windowBits:15,memLevel:8,strategy:AY},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 fY,this.strm.avail_out=0;let i=uY.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==vY)throw new Error(sK[i]);if(t.header&&uY.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?mY.string2buf(t.dictionary):"[object ArrayBuffer]"===SY.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=uY.deflateSetDictionary(this.strm,e),i!==vY)throw new Error(sK[i]);this._dict_set=!0}}function OY(e,t){const i=new wY(t);if(i.push(e,!0),i.err)throw i.msg||sK[i.err];return i.result}wY.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?CY:gY,"string"==typeof e?i.input=mY.string2buf(e):"[object ArrayBuffer]"===SY.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===TY||o===RY)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=uY.deflate(i,o),r===yY)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=uY.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===vY;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},wY.prototype.onData=function(e){this.chunks.push(e)},wY.prototype.onEnd=function(e){e===vY&&(this.result=pY.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var NY={Deflate:wY,deflate:OY,deflateRaw:function(e,t){return(t=t||{}).raw=!0,OY(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,OY(e,t)},constants:aK};const DY=16209;var PY=function(e,t){let i,n,r,o,s,a,c,d,l,u,h,p,_,E,m,f,S,g,T,R,C,v,y,I;const A=e.state;i=e.next_in,y=e.input,n=i+(e.avail_in-5),r=e.next_out,I=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,m=(1<<A.lenbits)-1,f=(1<<A.distbits)-1;
vendor: 5,067 bytes, line 6
6e:do{p<15&&(h+=y[i++]<<p,p+=8,h+=y[i++]<<p,p+=8),S=_[h&m];t:for(;;){if(g=S>>>24,h>>>=g,p-=g,g=S>>>16&255,0===g)I[r++]=65535&S;else{if(!(16&g)){if(0==(64&g)){S=_[(65535&S)+(h&(1<<g)-1)];continue t}if(32&g){A.mode=16191;break e}e.msg="invalid literal/length code",A.mode=DY;break e}T=65535&S,g&=15,g&&(p<g&&(h+=y[i++]<<p,p+=8),T+=h&(1<<g)-1,h>>>=g,p-=g),p<15&&(h+=y[i++]<<p,p+=8,h+=y[i++]<<p,p+=8),S=E[h&f];i:for(;;){if(g=S>>>24,h>>>=g,p-=g,g=S>>>16&255,!(16&g)){if(0==(64&g)){S=E[(65535&S)+(h&(1<<g)-1)];continue i}e.msg="invalid distance code",A.mode=DY;break e}if(R=65535&S,g&=15,p<g&&(h+=y[i++]<<p,p+=8,p<g&&(h+=y[i++]<<p,p+=8)),R+=h&(1<<g)-1,R>a){e.msg="invalid distance too far back",A.mode=DY;break e}if(h>>>=g,p-=g,g=r-o,R>g){if(g=R-g,g>d&&A.sane){e.msg="invalid distance too far back",A.mode=DY;break e}if(C=0,v=u,0===l){if(C+=c-g,g<T){T-=g;do{I[r++]=u[C++]}while(--g);C=r-R,v=I}}else if(l<g){if(C+=c+l-g,g-=l,g<T){T-=g;do{I[r++]=u[C++]}while(--g);if(C=0,l<T){g=l,T-=g;do{I[r++]=u[C++]}while(--g);C=r-R,v=I}}}else if(C+=l-g,g<T){T-=g;do{I[r++]=u[C++]}while(--g);C=r-R,v=I}for(;T>2;)I[r++]=v[C++],I[r++]=v[C++],I[r++]=v[C++],T-=3;T&&(I[r++]=v[C++],T>1&&(I[r++]=v[C++]))}else{C=r-R;do{I[r++]=I[C++],I[r++]=I[C++],I[r++]=I[C++],T-=3}while(T>2);T&&(I[r++]=I[C++],T>1&&(I[r++]=I[C++]))}break}}break}}while(i<n&&r<s);T=p>>3,i-=T,p-=T<<3,h&=(1<<p)-1,e.next_in=i,e.next_out=r,e.avail_in=i<n?n-i+5:5-(i-n),e.avail_out=r<s?s-r+257:257-(r-s),A.hold=h,A.bits=p};const LY=15,kY=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),MY=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),UY=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),VY=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var xY=(e,t,i,n,r,o,s,a)=>{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,S=0,g=0,T=0,R=0,C=0,v=0,y=0,I=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=LY;E++)A[E]=0;for(m=0;m<n;m++)A[t[i+m]]++;for(g=c,S=LY;S>=1&&0===A[S];S--);if(g>S&&(g=S),0===S)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f<S&&0===A[f];f++);for(g<f&&(g=f),C=1,E=1;E<=LY;E++)if(C<<=1,C-=A[E],C<0)return-1;if(C>0&&(0===e||1!==S))return-1;for(b[1]=0,E=1;E<LY;E++)b[E+1]=b[E]+A[E];for(m=0;m<n;m++)0!==t[i+m]&&(s[b[t[i+m]]++]=m);if(0===e?(I=D=s,_=20):1===e?(I=kY,D=MY,_=257):(I=UY,D=VY,_=0),y=0,m=0,E=f,p=o,T=g,R=0,u=-1,v=1<<g,h=v-1,1===e&&v>852||2===e&&v>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=I[s[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(y>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;y&d;)d>>=1;if(0!==d?(y&=d-1,y+=d):y=0,m++,0==--A[E]){if(E===S)break;E=t[i+s[m]]}if(E>g&&(y&h)!==u){for(0===R&&(R=g),p+=f,T=E-R,C=1<<T;T+R<S&&(C-=A[T+R],!(C<=0));)T++,C<<=1;if(v+=1<<T,1===e&&v>852||2===e&&v>592)return 1;u=y&h,r[u]=g<<24|T<<16|p-o|0}}return 0!==y&&(r[p+y]=E-R<<24|64<<16|0),a.bits=g,0};const{Z_FINISH:FY,Z_BLOCK:BY,Z_TREES:jY,Z_OK:GY,Z_STREAM_END:WY,Z_NEED_DICT:HY,Z_STREAM_ERROR:KY,Z_DATA_ERROR:YY,Z_MEM_ERROR:zY,Z_BUF_ERROR:qY,Z_DEFLATED:XY}=aK,JY=16180,QY=16190,ZY=16191,$Y=16192,ez=16194,tz=16199,iz=16200,nz=16206,rz=16209,oz=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function sz(){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 az=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<JY||t.mode>16211?1:0},cz=e=>{if(az(e))return KY;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=JY,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,GY},dz=e=>{if(az(e))return KY;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,cz(e)},lz=(e,t)=>{let i;if(az(e))return KY;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?KY:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,dz(e))},uz=(e,t)=>{if(!e)return KY;const i=new sz;e.state=i,i.strm=e,i.window=null,i.mode=JY;const n=lz(e,t);return n!==GY&&(e.state=null),n};let hz,pz,_z=!0;const Ez=e=>{if(_z){hz=new Int32Array(512),pz=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(xY(1,e.lens,0,288,hz,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;xY(2,e.lens,0,32,pz,0,e.work,{bits:5}),_z=!1}
vendor: 34,990 bytes, line 6
6e.lencode=hz,e.lenbits=9,e.distcode=pz,e.distbits=5},mz=(e,t,i,n)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),n>=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<o.wsize&&(o.whave+=r))),0};var fz=(e,t)=>{let i,n,r,o,s,a,c,d,l,u,h,p,_,E,m,f,S,g,T,R,C,v,y=0;const I=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(az(e)||!e.output||!e.input&&0!==e.avail_in)return KY;i=e.state,i.mode===ZY&&(i.mode=$Y),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,v=GY;e:for(;;)switch(i.mode){case JY:if(0===i.wrap){i.mode=$Y;break}for(;l<16;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(2&i.wrap&&35615===d){0===i.wbits&&(i.wbits=15),i.check=0,I[0]=255&d,I[1]=d>>>8&255,i.check=oK(i.check,I,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=rz;break}if((15&d)!==XY){e.msg="unknown compression method",i.mode=rz;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=rz;break}i.dmax=1<<i.wbits,i.flags=0,e.adler=i.check=1,i.mode=512&d?16189:ZY,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(i.flags=d,(255&EH(i))!==XY){e.msg="unknown compression method",i.mode=rz;break}if(57344&EH(i)){e.msg="unknown header flags set",i.mode=rz;break}i.head&&(i.head.text=d>>8&1),512&EH(i)&&4&i.wrap&&(I[0]=255&d,I[1]=d>>>8&255,i.check=oK(i.check,I,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.head&&(i.head.time=d),512&EH(i)&&4&i.wrap&&(I[0]=255&d,I[1]=d>>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,i.check=oK(i.check,I,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.head&&(i.head.xflags=255&d,i.head.os=d>>8),512&EH(i)&&4&i.wrap&&(I[0]=255&d,I[1]=d>>>8&255,i.check=oK(i.check,I,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&EH(i)){for(;l<16;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.length=d,i.head&&(i.head.extra_len=d),512&EH(i)&&4&i.wrap&&(I[0]=255&d,I[1]=d>>>8&255,i.check=oK(i.check,I,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&EH(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&EH(i)&&4&i.wrap&&(i.check=oK(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&EH(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<a);if(512&EH(i)&&4&i.wrap&&(i.check=oK(i.check,n,p,o)),a-=p,o+=p,C)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&EH(i)){if(0===a)break e;p=0;do{C=n[o+p++],i.head&&C&&i.length<65536&&(i.head.comment+=String.fromCharCode(C))}while(C&&p<a);if(512&EH(i)&&4&i.wrap&&(i.check=oK(i.check,n,p,o)),a-=p,o+=p,C)break e}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&EH(i)){for(;l<16;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(4&i.wrap&&d!==(65535&i.check)){e.msg="header crc mismatch",i.mode=rz;break}d=0,l=0}i.head&&(i.head.hcrc=EH(i)>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ZY;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}e.adler=i.check=oz(d),d=0,l=0,i.mode=QY;case QY:if(0===i.havedict)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=d,i.bits=l,HY;e.adler=i.check=1,i.mode=ZY;case ZY:if(t===BY||t===jY)break e;case $Y:if(i.last){d>>>=7&l,l-=7&l,i.mode=nz;break}for(;l<3;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}switch(i.last=1&d,d>>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(Ez(i),i.mode=tz,t===jY){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=rz}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++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",i.mode=rz;break}if(i.length=65535&d,d=0,l=0,i.mode=ez,t===jY)break e;case ez: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=ZY;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(i.nlen=257+(31&d),d>>>=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=rz;break}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.lens[w[i.have++]]=7&d,d>>>=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},v=xY(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid code lengths set",i.mode=rz;break}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;y=i.lencode[d&(1<<i.lenbits)-1],m=y>>>24,f=y>>>16&255,S=65535&y,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(S<16)d>>>=m,l-=m,i.lens[i.have++]=S;else{if(16===S){for(b=m+2;l<b;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(d>>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=rz;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===S){for(b=m+3;l<b;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}d>>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l<b;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}d>>>=m,l-=m,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=rz;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===rz)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=rz;break}if(i.lenbits=9,A={bits:i.lenbits},v=xY(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid literal/lengths set",i.mode=rz;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},v=xY(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,v){e.msg="invalid distances set",i.mode=rz;break}if(i.mode=tz,t===jY)break e;case tz:i.mode=iz;case iz: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,PY(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===ZY&&(i.back=-1);break}for(i.back=0;y=i.lencode[d&(1<<i.lenbits)-1],m=y>>>24,f=y>>>16&255,S=65535&y,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(f&&0==(240&f)){for(g=m,T=f,R=S;y=i.lencode[R+((d&(1<<g+T)-1)>>g)],m=y>>>24,f=y>>>16&255,S=65535&y,!(g+m<=l);){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}d>>>=g,l-=g,i.back+=g}if(d>>>=m,l-=m,i.back+=m,i.length=S,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=ZY;break}if(64&f){e.msg="invalid literal/length code",i.mode=rz;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.length+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;y=i.distcode[d&(1<<i.distbits)-1],m=y>>>24,f=y>>>16&255,S=65535&y,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(0==(240&f)){for(g=m,T=f,R=S;y=i.distcode[R+((d&(1<<g+T)-1)>>g)],m=y>>>24,f=y>>>16&255,S=65535&y,!(g+m<=l);){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}d>>>=g,l-=g,i.back+=g}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=rz;break}i.offset=S,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}i.offset+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=rz;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=rz;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=iz);break;case 16205:if(0===c)break e;r[s++]=i.length,c--,i.mode=iz;break;case nz:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[o++]<<l,l+=8}if(h-=c,e.total_out+=h,i.total+=h,4&i.wrap&&h&&(e.adler=i.check=EH(i)?oK(i.check,r,h,s-h):nK(i.check,r,h,s-h)),h=c,4&i.wrap&&(EH(i)?d:oz(d))!==i.check){e.msg="incorrect data check",i.mode=rz;break}d=0,l=0}i.mode=16207;case 16207:if(i.wrap&&EH(i)){for(;l<32;){if(0===a)break e;a--,d+=n[o++]<<l,l+=8}if(4&i.wrap&&d!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=rz;break}d=0,l=0}i.mode=16208;case 16208:v=WY;break e;case rz:v=YY;break e;case 16210:return zY;default:return KY}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=d,i.bits=l,(i.wsize||h!==e.avail_out&&i.mode<rz&&(i.mode<nz||t!==FY))&&mz(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,i.total+=h,4&i.wrap&&h&&(e.adler=i.check=EH(i)?oK(i.check,r,h,e.next_out-h):nK(i.check,r,h,e.next_out-h)),e.data_type=i.bits+(i.last?64:0)+(i.mode===ZY?128:0)+(i.mode===tz||i.mode===ez?256:0),(0===u&&0===h||t===FY)&&v===GY&&(v=qY),v},Sz={inflateReset:dz,inflateReset2:lz,inflateResetKeep:cz,inflateInit:e=>uz(e,15),inflateInit2:uz,inflate:fz,inflateEnd:e=>{if(az(e))return KY;let t=e.state;return t.window&&(t.window=null),e.state=null,GY},inflateGetHeader:(e,t)=>{if(az(e))return KY;const i=e.state;return 0==(2&i.wrap)?KY:(i.head=t,t.done=!1,GY)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,o;return az(e)?KY:(n=e.state,0!==n.wrap&&n.mode!==QY?KY:n.mode===QY&&(r=1,r=nK(r,t,i,0),r!==n.check)?YY:(o=mz(e,t,i,i),o?(n.mode=16210,zY):(n.havedict=1,GY)))},inflateInfo:"pako inflate (from Nodeca project)"};var gz=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 Tz=Object.prototype.toString,{Z_NO_FLUSH:Rz,Z_FINISH:Cz,Z_OK:vz,Z_STREAM_END:yz,Z_NEED_DICT:Iz,Z_STREAM_ERROR:Az,Z_DATA_ERROR:bz,Z_MEM_ERROR:wz}=aK;function Oz(e){this.options=pY.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 fY,this.strm.avail_out=0;let i=Sz.inflateInit2(this.strm,t.windowBits);if(i!==vz)throw new Error(sK[i]);if(this.header=new gz,Sz.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=mY.string2buf(t.dictionary):"[object ArrayBuffer]"===Tz.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Sz.inflateSetDictionary(this.strm,t.dictionary),i!==vz)))throw new Error(sK[i])}function Nz(e,t){const i=new Oz(t);if(i.push(e),i.err)throw i.msg||sK[i.err];return i.result}Oz.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?Cz:Rz,"[object ArrayBuffer]"===Tz.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=Sz.inflate(i,s),o===Iz&&r&&(o=Sz.inflateSetDictionary(i,r),o===vz?o=Sz.inflate(i,s):o===bz&&(o=Iz));i.avail_in>0&&o===yz&&i.state.wrap>0&&0!==e[i.next_in];)Sz.inflateReset(i),o=Sz.inflate(i,s);switch(o){case Az:case bz:case Iz:case wz:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===yz))if("string"===this.options.to){let e=mY.utf8border(i.output,i.next_out),t=i.next_out-e,r=mY.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!==vz||0!==a){if(o===yz)return o=Sz.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Oz.prototype.onData=function(e){this.chunks.push(e)},Oz.prototype.onEnd=function(e){e===vz&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=pY.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Dz={Inflate:Oz,inflate:Nz,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Nz(e,t)},ungzip:Nz,constants:aK};const{Deflate:Pz,deflate:Lz,deflateRaw:kz,gzip:Mz}=NY,{Inflate:Uz,inflate:Vz,inflateRaw:xz,ungzip:Fz}=Dz;var Bz=Lz,jz=kz,Gz=Vz,Wz=xz,Hz=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(Hz||{});class Kz{constructor(){bI(this,"_sequence",0),bI(this,"_startTime",Date.now()),bI(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){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;JN("SHOW_DATASTREAM2_LOG")&&ND.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,JN("SHOW_DATASTREAM2_LOG")&&ND.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===Hz.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,i=new ArrayBuffer(0);o?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(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 Gz(new Uint8Array(e))}compress(e){return Bz(new Uint8Array(e))}}const Yz={name:"DataStream",create:(e,t)=>{const i=t?new DM(e):new PM(e);return i.useDataStream(new Kz),i}};class zz extends rO{constructor(e,t,i){super(),bI(this,"ws",void 0),bI(this,"requestId",1),bI(this,"heartBeatTimer",void 0),bI(this,"joinInfo",void 0),bI(this,"clientId",void 0),bI(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),bI(this,"onClose",(e=>{this.emit("close"),this.dispose()})),bI(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 wx("cross-channel-".concat(this.clientId),i),this.ws.on(SV.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(SV.CONNECTED,this.onOpen),this.ws.on(SV.ON_MESSAGE,this.onMessage),this.ws.on(SV.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 Wh(((t,i)=>{const n=window.setTimeout((()=>{i(new FD(Bw.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new FD(Bw.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(n),i(new FD(Bw.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new FD(Bw.WS_DISCONNECT);const t=()=>new Wh(((e,t)=>{this.ws.once(SV.CLOSED,(()=>t(new FD(Bw.WS_ABORT)))),this.ws.once(SV.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Wh(((e,t)=>{const n=()=>{t(new FD(Bw.WS_ABORT))};this.ws.once(SV.RECONNECTING,n),this.ws.once(SV.CLOSED,n),this.once("req_".concat(i),e),KO(3e3).then((()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(SV.RECONNECTING,n),this.ws.off(SV.CLOSED,n),t(new FD(Bw.TIMEOUT,"cross channel ws request timeout"))}))})),r=await n;if(!r||200!==r.code)throw new FD(Bw.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(SV.REQUEST_NEW_URLS),this.ws.on(SV.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 qz extends rO{set state(e){e!==this._state&&(e!==PV.RELAY_STATE_FAILURE&&(this.errorCode=LV.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),bI(this,"joinInfo",void 0),bI(this,"sid",void 0),bI(this,"clientId",void 0),bI(this,"cancelToken",Xb.CancelToken.source()),bI(this,"workerToken",void 0),bI(this,"requestId",0),bI(this,"signal",void 0),bI(this,"prevChannelMediaConfig",void 0),bI(this,"httpRetryConfig",void 0),bI(this,"_resolution",void 0),bI(this,"_state",PV.RELAY_STATE_IDLE),bI(this,"errorCode",LV.RELAY_OK),bI(this,"onStatus",(e=>{ND.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",DV.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",DV.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=LV.SRC_TOKEN_EXPIRED,this.state=PV.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=LV.DEST_TOKEN_EXPIRED,this.state=PV.RELAY_STATE_FAILURE))})),bI(this,"onReconnect",(async()=>{ND.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",DV.NETWORK_DISCONNECTED),this.state=PV.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==PV.RELAY_STATE_IDLE&&(ND.error("auto restart channel media relay failed",e.toString()),this.errorCode=LV.SERVER_CONNECTION_LOST,this.state=PV.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=zO(),this.signal=new zz(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==PV.RELAY_STATE_IDLE)throw new FD(Bw.INVALID_OPERATION);this.state=PV.RELAY_STATE_CONNECTING,await this.connect(),ND.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 FD(Bw.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new FD(Bw.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new FD(Bw.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==PV.RELAY_STATE_RUNNING)throw new FD(Bw.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==PV.RELAY_STATE_RUNNING)throw new FD(Bw.INVALID_OPERATION);const t=this.genMessage(NV.SetVideoProfile);await this.signal.request(t),ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),ND.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=PV.RELAY_STATE_IDLE,this.dispose()}dispose(){ND.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=Xb.CancelToken.source(),this.state=PV.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await vB(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",DV.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(NV.SetSdkProfile,e);await this.signal.request(t),ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const i=this.genMessage(NV.SetSourceChannel,e);await this.signal.request(i),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",DV.PACKET_JOINED_SRC_CHANNEL),ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const n=this.genMessage(NV.SetSourceUserId,e);await this.signal.request(n),ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const r=this.genMessage(NV.SetDestChannel,e);await this.signal.request(r),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",DV.PACKET_JOINED_DEST_CHANNEL),ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(NV.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",DV.PACKET_SENT_TO_DEST_CHANNEL),this.state=PV.RELAY_STATE_RUNNING,ND.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(NV.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",DV.PACKET_UPDATE_DEST_CHANNEL),ND.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(NV.StopPacketTransfer);await this.signal.request(e),ND.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:BN,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.2-200"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case NV.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case NV.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new FD(Bw.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 NV.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new FD(Bw.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case NV.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new FD(Bw.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 NV.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case NV.Reconnect:return o.clientRequest={command:"Reconnect"},o;case NV.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case NV.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new FD(Bw.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 NV.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const Xz={name:"ChannelMediaRelay",create:function(e){return new qz(e.joinInfo,e.clientId,e.websocketRetryConfig||cN,e.httpRetryConfig||cN,e.resolution)}};function Jz(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 Qz(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Jz(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Jz(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Zz extends rO{constructor(e,t,i,n){super(),bI(this,"spec",void 0),bI(this,"token",void 0),bI(this,"websocket",void 0),bI(this,"pingpongTimer",void 0),bI(this,"reconnectMode","retry"),bI(this,"serviceMode",void 0),bI(this,"reqId",0),bI(this,"commandReqId",0),bI(this,"handleWebSocketOpen",(()=>{this.reconnectMode="retry",this.startPingPong()})),bI(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(xD.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===RV.TRANSCODE?1:2}),this.emit(AV.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new wx("live-streaming",i),this.websocket.on(SV.CONNECTED,this.handleWebSocketOpen),this.websocket.on(SV.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(SV.REQUEST_NEW_URLS,((e,t)=>{RO(this,AV.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(SV.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 FD(Bw.UNEXPECTED_ERROR);const s=Qz({command:e,sdkVersion:"4.24.2-200"===BN?"0.0.1":BN,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 FD(Bw.WS_DISCONNECT);const a=()=>new Wh(((e,t)=>{this.websocket.once(SV.CLOSED,(()=>t(new FD(Bw.WS_ABORT)))),this.websocket.once(SV.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Wh(((e,t)=>{const i=()=>{t(new FD(Bw.WS_ABORT))};this.websocket.once(SV.RECONNECTING,i),this.websocket.once(SV.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&xD.workerEvent(this.spec.sid,Qz(Qz({},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&&xD.workerEvent(this.spec.sid,Qz(Qz({},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.24.2-200"===BN?"0.0.1":BN;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 wV.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void ND.warning("live stream response already exists stream");case wV.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case wV.LIVE_STREAM_RESPONSE_BAD_STREAM:case wV.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new FD(Bw.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case wV.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case wV.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new FD(Bw.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case wV.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new FD(Bw.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(AV.WARNING,t,e.serverResponse.url)}case wV.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new FD(Bw.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(AV.WARNING,t,e.serverResponse.url)}case wV.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case wV.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new FD(Bw.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case wV.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new FD(Bw.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(AV.WARNING,t,e.serverResponse.url)}case wV.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case wV.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case wV.LIVE_STREAM_RESPONSE_WORKER_LOST:case wV.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case wV.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case wV.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new FD(Bw.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(qO)}),6e3)}}function $z(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 eq(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?$z(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):$z(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class tq extends rO{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:cN,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:cN;super(),bI(this,"onLiveStreamWarning",void 0),bI(this,"onLiveStreamError",void 0),bI(this,"spec",void 0),bI(this,"retryTimeout",1e4),bI(this,"connection",void 0),bI(this,"httpRetryConfig",void 0),bI(this,"wsRetryConfig",void 0),bI(this,"streamingTasks",new Map),bI(this,"isStartingStreamingTask",!1),bI(this,"taskMutex",new sN("live-streaming")),bI(this,"cancelToken",Xb.CancelToken.source()),bI(this,"transcodingConfig",void 0),bI(this,"uapResponse",void 0),bI(this,"lastTaskId",1),bI(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=eq(eq({},IV),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(ND.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=>eq(eq(eq({},CV),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){qw(e.width)||Hw(e.width,"config.width",0,1e4),qw(e.height)||Hw(e.height,"config.height",0,1e4),qw(e.videoBitrate)||Hw(e.videoBitrate,"config.videoBitrate",1,1e6),qw(e.videoFrameRate)||Hw(e.videoFrameRate,"config.videoFrameRate"),qw(e.lowLatency)||Gw(e.lowLatency,"config.lowLatency"),qw(e.audioSampleRate)||Ww(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),qw(e.audioBitrate)||Hw(e.audioBitrate,"config.audio
6Bitrate",1,128),qw(e.audioChannels)||Ww(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),qw(e.videoGop)||Hw(e.videoGop,"config.videoGop"),qw(e.videoCodecProfile)||Ww(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),qw(e.userCount)||Hw(e.userCount,"config.userCount",0,17),qw(e.backgroundColor)||Hw(e.backgroundColor,"config.backgroundColor",0,16777215),qw(e.userConfigExtraInfo)||Yw(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!qw(e.transcodingUsers)&&(zw(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{TV(e.uid),qw(e.x)||Hw(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),qw(e.y)||Hw(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),qw(e.width)||Hw(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),qw(e.height)||Hw(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),qw(e.zOrder)||Hw(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),qw(e.alpha)||Hw(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),qw(e.watermark)||yV(e.watermark,"watermark"),qw(e.backgroundImage)||yV(e.backgroundImage,"backgroundImage"),e.images&&!qw(e.images)&&(zw(e.images,"config.images"),e.images.forEach(((e,t)=>{yV(e,"images[".concat(t,"]"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>eq(eq(eq({},vV),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(eq(eq(eq({},vV),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(eq(eq(eq({},vV),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>eq({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Wh.resolve(e.uid):SB(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Wh.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(Zh(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});ND.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=>{ND.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{ND.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{ND.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}
vendor: 29,347 bytes, line 6
6))}}async startLiveStreamingTask(e,t,i){if(!this.transcodingConfig&&t===RV.TRANSCODE)throw new FD(Bw.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};ND.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 FD(Bw.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case RV.TRANSCODE:n.transcodingConfig=eq({},this.transcodingConfig);case RV.RAW:}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new Wh(((t,n)=>{KO(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 Wh.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===RV.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,ND.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 Wh(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new FD(Bw.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{ND.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===RV.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{ND.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(Zh(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=Xb.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new FD(Bw.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await RO(this,bV.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new Zz(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(AV.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(AV.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(AV.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new FD(Bw.UNEXPECTED_ERROR,"can not get new live streaming address list"));RO(this,bV.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 wV.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case wV.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new FD(Bw.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return ND.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case wV.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new FD(Bw.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case wV.LIVE_STREAM_RESPONSE_WORKER_LOST:case wV.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(Zh(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(ND.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new FD(Bw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{ND.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)})).catch((e=>{ND.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const iq={name:"LiveStreaming",create:function(e){return new tq(e.joinInfo,e.websocketRetryConfig||cN,e.httpRetryConfig||cN)}};function nq(e){let t=_q();return function(e,t){let i=e.appId;void 0!==i&&(wq(t,10),Rq(t,i));let n=e.cid;void 0!==n&&(wq(t,16),wq(t,n));let r=e.cname;void 0!==r&&(wq(t,26),Rq(t,r));let o=e.deviceId;void 0!==o&&(wq(t,34),Rq(t,o));let s=e.elapse;void 0!==s&&(wq(t,40),Oq(t,s));let a=e.fileSize;void 0!==a&&(wq(t,48),Oq(t,hq(a)));let c=e.height;void 0!==c&&(wq(t,56),Oq(t,hq(c)));let d=e.jpg;void 0!==d&&(wq(t,66),wq(t,d.length),function(e,t){let i=Sq(e,t.length);e.bytes.set(t,i)}(t,d));let l=e.networkType;void 0!==l&&(wq(t,72),Oq(t,hq(l)));let u=e.osType;void 0!==u&&(wq(t,80),Oq(t,hq(u)));let h=e.requestId;void 0!==h&&(wq(t,90),Rq(t,h));let p=e.sdkVersion;void 0!==p&&(wq(t,98),Rq(t,p));let _=e.sequence;void 0!==_&&(wq(t,104),Oq(t,hq(_)));let E=e.sid;void 0!==E&&(wq(t,114),Rq(t,E));let m=e.timestamp;void 0!==m&&(wq(t,120),Oq(t,m));let f=e.uid;void 0!==f&&(wq(t,128),wq(t,f));let S=e.vid;void 0!==S&&(wq(t,136),wq(t,S));let g=e.width;void 0!==g&&(wq(t,144),Oq(t,hq(g)));let T=e.service;void 0!==T&&(wq(t,152),wq(t,T));let R=e.callbackData;void 0!==R&&(wq(t,162),Rq(t,R));let C=e.jpgEncryption;void 0!==C&&(wq(t,168),wq(t,C));let v=e.requestType;void 0!==v&&(wq(t,176),wq(t,v));let y=e.scorePorn;void 0!==y&&(wq(t,185),Aq(t,y));let I=e.scoreSexy;void 0!==I&&(wq(t,193),Aq(t,I));let A=e.scoreNeutral;void 0!==A&&(wq(t,201),Aq(t,A));let b=e.scene;void 0!==b&&(wq(t,208),wq(t,b));let w=e.ossFilePrefix;void 0!==w&&(wq(t,218),Rq(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){wq(t,226);let i=_q();sq(e,i),wq(t,i.limit),Cq(t,i),Eq(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function rq(e){return function(e){let t={};e:for(;!fq(e);){let i=bq(e);switch(i>>>3){case 0:break e;case 1:t.code=bq(e);break;case 2:t.msg=Tq(e,bq(e));break;case 3:{let i=aq(e);t.data=oq(e),e.limit=i;break}default:cq(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function oq(e){let t={};e:for(;!fq(e);){let i=bq(e);switch(i>>>3){case 0:break e;case 1:t.requestId=Tq(e,bq(e));break;case 2:t.requestType=bq(e)>>>0;break;case 3:t.scorePorn=Iq(e);break;case 4:t.scoreSexy=Iq(e);break;case 5:t.scoreNeutral=Iq(e);break;case 6:t.requestScene=bq(e)>>>0;break;case 7:t.scene=bq(e)>>>0;break;default:cq(e,7&i)}}return t}function sq(e,t){let i=e.service;void 0!==i&&(wq(t,8),wq(t,i));let n=e.vendor;void 0!==n&&(wq(t,16),wq(t,n));let r=e.token;void 0!==r&&(wq(t,26),Rq(t,r));let o=e.callbackUrl;void 0!==o&&(wq(t,34),Rq(t,o))}function aq(e){let t=bq(e),i=e.limit;return e.limit=e.offset+t,i}function cq(e,t){switch(t){case 0:for(;128&vq(e););break;case 2:mq(e,bq(e));break;case 5:mq(e,4);break;case 1:mq(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let dq=new Float32Array(1);new Uint8Array(dq.buffer);let lq=new Float64Array(1),uq=new Uint8Array(lq.buffer);function hq(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let pq=[];function _q(){const e=pq.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function Eq(e){pq.push(e)}function mq(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function fq(e){return e.offset>=e.limit}function Sq(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 gq(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function Tq(e,t){let i=gq(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+i];0==(128&u)?s+=n(u):192==(224&u)?e+1>=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 Rq(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4}wq(e,n);let r=Sq(e,n),o=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?o[r++]=n:(n<2048?o[r++]=n>>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 Cq(e,t){let i=Sq(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e<o;e++)n[e+i]=r[e]}function vq(e){return e.bytes[gq(e,1)]}function yq(e,t){let i=Sq(e,1);e.bytes[i]=t}function Iq(e){let t=gq(e,8),i=e.bytes;return uq[0]=i[t++],uq[1]=i[t++],uq[2]=i[t++],uq[3]=i[t++],uq[4]=i[t++],uq[5]=i[t++],uq[6]=i[t++],uq[7]=i[t++],lq[0]}function Aq(e,t){let i=Sq(e,8),n=e.bytes;lq[0]=t,n[i++]=uq[0],n[i++]=uq[1],n[i++]=uq[2],n[i++]=uq[3],n[i++]=uq[4],n[i++]=uq[5],n[i++]=uq[6],n[i++]=uq[7]}function bq(e){let t,i=0,n=0;do{t=vq(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function wq(e,t){for(t>>>=0;t>=128;)yq(e,127&t|128),t>>>=7;yq(e,t)}function Oq(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=Sq(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 Nq(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 Dq=new Map([["moderation",1],["supervise",2]]);class Pq extends rO{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(tx.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=Xn(t=e.map((e=>Dq.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(),bI(this,"name","AgoraRTCVideoContentInspect"),bI(this,"_connectionState",$V.CONNECTING),bI(this,"_innerConnectionState",void 0),bI(this,"sequence",0),bI(this,"inspectStartTime",void 0),bI(this,"workerManagerConnection",void 0),bI(this,"workerConnection",void 0),bI(this,"workerMessageLengthLimit",void 0),bI(this,"inspectIntervalMinimum",void 0),bI(this,"qualityRatio",void 0),bI(this,"_connectInfo",void 0),bI(this,"_cancelTokenSource",Xb.CancelToken.source()),bI(this,"_retryConfig",void 0),bI(this,"wmSequence",0),bI(this,"inspectInterval",void 0),bI(this,"inspectTimer",null),bI(this,"ossFilePrefix",void 0),bI(this,"extraInfo",void 0),bI(this,"_inspectType",void 0),bI(this,"_inspectMode",void 0),bI(this,"_quality",1),bI(this,"qualityTimer",null),bI(this,"_inspectId",void 0),bI(this,"_needWorkUrlOnly",!1),bI(this,"inspectImage",(()=>{if(this.connectionState!==$V.CONNECTED)throw new FD(Bw.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===$V.CONNECTED?this.requestToInspectImage():ND.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()})),this._inspectId=YO(5,"inspect-"),this.workerMessageLengthLimit=JN("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=JN("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=JN("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new wx("worker-manager-"+this._inspectId,cN),this.on(tx.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,ND.debug("[".concat(this._inspectId,"] Inspect operation :").concat(ex[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new wx("worker-"+this._inspectId,cN),this.handleWorkerEvents()}async init(e,t){this.emit(tx.STATE_CHANGE,ex.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((n,r)=>{this.on(tx.CONNECTION_STATE_CHANGE,((e,t)=>{t===$V.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=JN("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;uB++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:uB,seq:uB,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return lN((async()=>{h=Date.now();const e=await WF(_,{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 FD(Bw.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw ND.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new FD(Bw.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw ND.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new FD(Bw.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw ND.error(e.toString()),e}const n=JN("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(n)return{addressList:[n],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=JN("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=JN("VIDEO_INSPECT_WORKER_MANAGER_PORT"),s=t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(o||i)})).filter((e=>!!e));return{addressList:s,workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(xD.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)=>(xD.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Bw.OPERATION_ABORTED&&t.code!==Bw.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(tx.STATE_CHANGE,ex.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(tx.STATE_CHANGE,ex.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(SV.CONNECTED,(async()=>{this.emit(tx.STATE_CHANGE,ex.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.2-200",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(SV.CLOSED,(()=>{this._innerConnectionState<ex.GET_WORKER_MANAGER_RESPONSE&&ND.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(SV.FAILED,(()=>{this._innerConnectionState<ex.GET_WORKER_MANAGER_RESPONSE&&ND.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(SV.RECONNECTING,(()=>{this._innerConnectionState<ex.GET_WORKER_MANAGER_RESPONSE&&ND.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(SV.ON_MESSAGE,(async e=>{this.emit(tx.STATE_CHANGE,ex.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw ND.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new FD(Bw.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw ND.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new FD(Bw.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=JN("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(tx.STATE_CHANGE,ex.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(tx.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(SV.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(SV.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(SV.CONNECTED,(async()=>{this.emit(tx.STATE_CHANGE,ex.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=$V.CONNECTED})),this.workerConnection.on(SV.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=rq(new Uint8Array(e.data));if(JN("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&ND.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(tx.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=Xn(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(tx.INSPECT_RESULT,r)}else this.emit(tx.INSPECT_RESULT,void 0,new FD(Bw.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(tx.INSPECT_RESULT,void 0,new FD(Bw.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else ND.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(tx.INSPECT_RESULT,void 0,new FD(Bw.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(SV.CLOSED,(()=>{this.connectionState=$V.CLOSED})),this.workerConnection.on(SV.FAILED,(()=>{this.connectionState=$V.CLOSED})),this.workerConnection.on(SV.RECONNECTING,(()=>{this.connectionState=this.connectionState===$V.CONNECTED?$V.RECONNECTING:$V.CONNECTING})),this.workerConnection.on(SV.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this.workerConnection.on(SV.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(tx.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=vO(this,tx.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(tx.INSPECT_RESULT,void 0,new FD(Bw.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(tx.INSPECT_RESULT,void 0,new FD(Bw.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 AL(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+YO(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:(p=Number(c-this.inspectStartTime),{low:p|=0,high:p>>31,unsigned:p>=0}),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.2-200",sequence:this.sequence,sid:s,timestamp:nW(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var p;void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const _=nq(h);if(_.byteLength<this.workerMessageLengthLimit){if(JN("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Nq(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Nq(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},h);delete e.jpg,ND.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return _}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=Xb.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=$V.CLOSED,this.emit(tx.STATE_CHANGE,ex.CLOSED)}}const Lq={name:"ContentInspect",create:function(e){let{config:t}=e;return function(e){if(!e)throw new FD(Bw.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new FD(Bw.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!Dn(t=["supervise","moderation"]).call(t,e))throw new FD(Bw.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new FD(Bw.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new Pq(t)}};var kq=i(ie.Object.getOwnPropertySymbols),Mq=wi,Uq=zi.indexOf,Vq=Bn,xq=y([].indexOf),Fq=!!xq&&1/xq([1],1,-0)<0;Mq({target:"Array",proto:!0,forced:Fq||!Vq("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return Fq?xq(this,e,t)||0:Uq(this,e,t)}});var Bq=Ji("Array").indexOf,jq=l,Gq=Bq,Wq=Array.prototype,Hq=function(e){var t=e.indexOf;return e===Wq||jq(Wq,e)&&t===Wq.indexOf?Gq:t},Kq=i(Hq);function Yq(e,t){if(null==e)return{};var i,n,r=function(e,t){if(null==e)return{};var i,n,r={},o=VU(e);for(n=0;n<o.length;n++)i=o[n],Kq(t).call(t,i)>=0||(r[i]=e[i]);return r}(e,t);if(kq){var o=kq(e);for(n=0;n<o.length;n++)i=o[n],Kq(t).call(t,i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}let zq=class{get localCapabilities(){return kO(this._localCapabilities)}get rtpCapabilities(){return kO(this._rtpCapabilities)}get candidates(){return kO(this._candidates)}get iceParameters(){return kO(this._iceParameters)}get dtlsParameters(){return kO(this._dtlsParameters)}constructor(e){bI(this,"sessionDesc",void 0),bI(this,"_localCapabilities",void 0),bI(this,"_rtpCapabilities",void 0),bI(this,"_candidates",void 0),bI(this,"_iceParameters",void 0),bI(this,"_dtlsParameters",void 0),bI(this,"setup",void 0),bI(this,"currentMidIndex",void 0),bI(this,"cname","o/i14u9pJrxRKAsu"),bI(this,"firefoxSsrcMidMap",new Map),e=kO(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===fV.RECEIVE_ONLY?aD("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"):aD("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===fV.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=s===fV.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===fV.RECEIVE_ONLY?r.send.videoCodecs:RF(YV.VIDEO,u,h,c),_=s===fV.RECEIVE_ONLY?r.send.audioCodecs:RF(YV.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,TF(e));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return cD(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}=cF(t,this.cname,JN("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(_w()&&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=kO(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),_w()&&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=kO(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
6when 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=RF(o,s,this.localCapabilities.send,o===YV.AUDIO?r:n),c=o===YV.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(_w()){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<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}restartICE(e){e=kO(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,r,o){const s=this.rtpCapabilities.send,a=e===YV.VIDEO?s.videoCodecs:s.audioCodecs,c=e===YV.VIDEO?s.videoExtensions:s.audioExtensions;_w()&&(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=kO(e);return lF(n),dF(n,t),uF(n,t),hF(n),pF(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=kO(e);return pF(i,t,this.localCapabilities.recv),TF(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=>_w()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const qq=["sdp"];var Xq;function Jq(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 Qq(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
vendor: 33,835 bytes, line 6
6t%2?Jq(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Jq(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let Zq=(Xq=class e extends HV{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}constructor(t,i,n){super(t,i),bI(this,"direction",void 0),bI(this,"name",void 0),bI(this,"store",void 0),bI(this,"spec",void 0),bI(this,"peerConnection",void 0),bI(this,"initialOffer",void 0),bI(this,"transport",void 0),bI(this,"statsFilter",void 0),bI(this,"localCandidateCount",0),bI(this,"_isInRestartIce",!1),bI(this,"mutex",void 0),bI(this,"onLocalCandidate",void 0),bI(this,"remoteSDP",void 0),bI(this,"pendingCandidates",[]),bI(this,"localCapabilities",void 0),bI(this,"isReady",!1),bI(this,"restartCnt",0),bI(this,"curTurnServerIndex",0),this.store=i,this.spec=t,this.mutex=new sN("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,i.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=n?n:fV.SEND_ONLY,this.name=this.direction===fV.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=VN(this.peerConnection,JN("STATS_UPDATE_INTERVAL"),void 0,_w()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{const t=await mF();if(this.localCapabilities=gF(t),e){const{sdp:t}=e,i=Yq(e,qq),n=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=nF(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]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(SF(t,e,"videoExtensions",i,n,r),SF(t,e,"videoCodecs",i,n,r),SF(t,e,"audioExtensions",i,n,r),SF(t,e,"audioCodecs",i,n,r),JN("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){ND.debug("raising H264 baseline profile priority");const i=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,i)}-1!==t&&JN("FILTER_SEND_H264_BASELINE")&&(i.videoCodecs=i.videoCodecs.filter((e=>!(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 zq({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=rF(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await fF({},{},r.sdp);this.localCapabilities=gF(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Qq(Qq({},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=rF(e.sdp);return this.initialOffer=e,Qq(Qq({},t),{},{sdp:e.sdp})}}catch(e){throw new jw(Bw.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 fF({},{},t);this.remoteSDP=new zq({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 jw(Bw.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 jw(Bw.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return ub((function*(){const r=yield hb(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)}})),_w()&&!0===JN("SIMULCAST")&&(yield hb(n.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield hb(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=aD(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 oF(t,JN("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}));yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=n.remoteSDP.toString();throw yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield hb(n.stopSending(a,!0)),e}yield hb(n.applySimulcastEncodings(o,e)),yield hb(n.applySendEncodings(o,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield hb(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 jw?e:new jw(Bw.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 jw(Bw.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}),ND.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else ND.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 jw(Bw.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}),ND.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else ND.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new jw(Bw.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 jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===GN.Auto&&(this.store.p2pTransport=GN.SdRtn,jD().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,jD().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}=rF(e.sdp);return this.store.descriptionStart(),this.direction===fV.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===fV.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}=rF(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 jw(Bw.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 jw(Bw.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)?_w()||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:Qq(Qq({},RN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Qq(Qq({},RN),{},{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 ND.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&&(hO(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),JN("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),Dn(o=[GN.Relay,GN.SdRtn]).call(o,i)&&(r.iceTransportPolicy="relay"),JN("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return JN("ENABLE_ENCODED_TRANSFORM")&&jD().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),ND.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));ND.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const o=r.length>i?r[i]:r[0];switch(t){case GN.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(Mx(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(Mx(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case GN.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(Mx(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(Mx(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()||{};if(e&&i){const t=e.address+":"+e.port,n=i.address+":"+i.port;ND.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Kx(t)),", remote ").concat(JSON.stringify(Kx(n))))}}}))}}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 ND.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return ND.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!jD().supportSetRtpSenderParameters)return ND.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,hP.LOW_STREAM)&&(i&&(r.maxFramerate=xx(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(JN("DSCP_TYPE")&&kw()){var s;const e=JN("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];_w()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),ND.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!jD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof dM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){ND.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=aD(e);return t.forEach(((e,t)=>{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(dF(o,e),_F(o,e,this.store.codec))})),cD(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;a<e.length;a++){var i,n,r,o,s;const c=e[a],d=t[a];if(d instanceof dM&&!Dn(i=d._hints).call(i,hP.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&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(!_w()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof dM&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r,o;return!!(e instanceof dM&&JN("SIMULCAST")&&"vp8"===this.store.codec&&!Dn(t=e._hints).call(t,hP.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&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(JN("SDP_LOGGING"))return ND.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 jw(Bw.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 jw(Bw.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=aD(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=aD(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===YV.AUDIO&&"audio"===r.media.mediaType&&TF(r),cD(n)}},sV(Xq.prototype,"establish",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"establish"),Xq.prototype),sV(Xq.prototype,"connect",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"connect"),Xq.prototype),sV(Xq.prototype,"receive",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"receive"),Xq.prototype),sV(Xq.prototype,"mockReceive",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"mockReceive"),Xq.prototype),sV(Xq.prototype,"stopReceiving",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"stopReceiving"),Xq.prototype),sV(Xq.prototype,"restartICE",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"restartICE"),Xq.prototype),sV(Xq.prototype,"close",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"close"),Xq.prototype),sV(Xq.prototype,"updateEncoderConfig",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"updateEncoderConfig"),Xq.prototype),sV(Xq.prototype,"updateSendParameters",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"updateSendParameters"),Xq.prototype),sV(Xq.prototype,"replaceTrack",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"replaceTrack"),Xq.prototype),sV(Xq.prototype,"muteLocal",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"muteLocal"),Xq.prototype),sV(Xq.prototype,"unmuteLocal",[$q],Object.getOwnPropertyDescriptor(Xq.prototype,"unmuteLocal"),Xq.prototype),Xq);function $q(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<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}let eX=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var tX,iX,nX,rX,oX,sX,aX,cX,dX,lX,uX,hX;function pX(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 _X(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pX(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pX(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let EX=(tX=mX(eX.SEND_ONLY),iX=mX(eX.SEND_ONLY),nX=mX(),rX=mX(eX.RECEIVE_ONLY),oX=mX(eX.RECEIVE_ONLY),sX=mX(eX.RECEIVE_ONLY),aX=mX(eX.RECEIVE_ONLY),cX=mX(eX.RECEIVE_ONLY),dX=mX(eX.RECEIVE_ONLY),lX=mX(),uX=mX(eX.RECEIVE_ONLY),hX=class extends rO{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(ZV.StateChange,t,this._state)}constructor(e,t){super(),bI(this,"isPlanB",!1),bI(this,"store",void 0),bI(this,"statsUploader",void 0),bI(this,"sendConnection",void 0),bI(this,"recvConnection",void 0),bI(this,"localTrackMap",new Map),bI(this,"remoteUserMap",new Map),bI(this,"localDataChannels",[]),bI(this,"pendingLocalTracks",[]),bI(this,"pendingRemoteTracks",[]),bI(this,"statsCollector",void 0),bI(this,"dtlsFailedCount",0),bI(this,"sendMutex",void 0),bI(this,"recvMutex",void 0),bI(this,"_state",QV.Disconnected),bI(this,"_restartStates",["disconnected","failed"]),bI(this,"reconnectInterval",void 0),bI(this,"uploadUnplinkStarted",!1),bI(this,"uploadDownlinkStarted",!1),bI(this,"uplinkStateUploadInterval",void 0),bI(this,"downlinkStatsUploadInterval",void 0),bI(this,"handleMuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==QV.Connected)return void i(new jw(Bw.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(JV.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(JV.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await CO(this,ZV.RequestMuteLocal,d);const l="video"===e.trackMediaType?lx.MUTE_LOCAL_VIDEO:lx.MUTE_LOCAL_AUDIO;await CO(this,ZV.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==QV.Connected)return void i(new jw(Bw.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?lx.UNMUTE_LOCAL_VIDEO:lx.UNMUTE_LOCAL_AUDIO;await CO(this,ZV.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleUpdateVideoEncoder",(async(e,t,i,n)=>{let r;"boolean"==typeof n&&n||(r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(JV.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==QV.Connected)return void t();const{id:n,track:s}=i;n&&(await this.sendConnection.updateSendParameters(n,s),await this.sendConnection.updateEncoderConfig(n,s),this.emit(ZV.UpdateVideoEncoder,s)),t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),bI(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(JV.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==QV.Connected)return void t();const{id:r,track:o}=i;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),bI(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;ND.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!==QV.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),i[0]===JV.LocalVideoTrack&&jD().supportDualStreamEncoding){const t=this.localTrackMap.get(JV.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),bI(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),bI(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),bI(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),bI(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Dj(e),this.bindStatsUploaderEvents(),this.sendMutex=new sN("P2PChannel2-sen
6d-mutex",e.clientId),this.recvMutex=new sN("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),JN("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(ND.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 Zq(e,this.store,fV.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=QV.New,this.sendConnection&&(ND.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 Zq(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 jw(Bw.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=QV.Connected}async addRemoteCandidate(e,t){if(t===fV.RECEIVE_ONLY){if(!this.sendConnection)throw new jw(Bw.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new jw(Bw.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return ub((function*(){const r=yield hb(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==QV.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,NB.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield hb(n.tryToUnmuteAudio(e)));o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===JV.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(o);const s=yield hb(n.sendConnection.send(o.map((e=>{let{track:t}=e;return t})),n.store.codec,n.store.audioCodec)),a=(yield hb(s.next())).value,c=n.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===Bw.WS_ABORT&&o.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(o),e}yield hb(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===JV.LocalAudioTrack?"audio":"video",void 0,r)})),n.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==QV.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===QV.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=[];
6Array.from(this.localTrackMap.entries()).forEach((i=>{let[n,{track:r,ssrcs:o}]=i;const s={stream_type:rj(r,n),ssrcs:o};r._muted||!r._enabled?e.push(s):t.push(s)})),e.length>0&&e.forEach((e=>{CO(this,ZV.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{CO(this,ZV.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return ub((function*(){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(ND.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await RO(this,ZV.RequestRePublish,this.pendingLocalTracks),this.emit(ZV.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new jw(Bw.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===YV.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new wM(o,e.uid,e._uintid,this.store),ND.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 bM(o,e.uid,e._uintid,this.store),ND.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(ZV.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new jw(Bw.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===YV.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===YV.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===YV.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===YV.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===YV.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;CO(this,ZV.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>
vendor: 13,108 bytes, line 6
6Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[YV.VIDEO,YV.AUDIO].forEach((e=>{t.has(e)?CO(this,ZV.RequestP2PUnmuteRemote,e):CO(this,ZV.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 jw(Bw.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new jw(Bw.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new jw(Bw.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 ND.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void ND.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===YV.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 ND.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||ND.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(JV.LocalAudioTrack);if((null==t?void 0:t.track)instanceof Sk){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==JV.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===JV.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===JV.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(JV.LocalAudioTrack),o=n?this.localTrackMap.get(JV.LocalVideoLowTrack):this.localTrackMap.get(JV.LocalVideoTrack);xD.publish(this.store.sessionId,{eventElapse:NB.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(hP.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 Ek)),a=n?null===(o=this.localTrackMap.get(JV.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof dM));xD.publish(this.store.sessionId,{eventElapse:NB.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(hP.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===YV.VIDEO?i._videoSSRC:i._audioSSRC;r&&xD.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===YV.VIDEO,audio:n===YV.AUDIO,peerid:i.uid,subscribeRequestid:n===YV.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:NB.measureFromSubscribeStart(this.store.clientId,r)})}reset(){ND.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new sN("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new sN("P2PChannel2-recv-mutex",this.store.clientId),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(JV.LocalAudioTrack);if((null==e?void 0:e.track)instanceof Sk){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=QV.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(JV.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(JV.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 dM||t&&t.track instanceof Ek?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(fD(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(JV.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=qp(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(ND.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=QV.Reconnecting,JN("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 JV.LocalVideoTrack:Dn(t=n._hints).call(t,hP.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case JV.LocalAudioTrack:n instanceof Sk?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case JV.LocalVideoLowTrack:}})),this.emit(ZV.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(fD(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(ZV.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),ND.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 UB?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===fV.SEND_ONLY){if(!this.sendConnection)throw new jw(Bw.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 jw(Bw.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 RO(this,ZV.RequestP2PRestartICE,{direction:fV.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(JV.LocalVideoTrack),i=this.localTrackMap.get(JV.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=vO(this,ZV.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(hP.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return gU[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=vO(this,ZV.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 Wh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=jD(),o=this.getAllTracks();e=PO(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof dM&&(this.localTrackMap.has(JV.LocalVideoTrack)||s?new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:JV.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:JV.LocalVideoLowTrack})}if(o instanceof Ek){const e=this.localTrackMap.get(JV.LocalAudioTrack);if(e){if(!(e.track instanceof Sk))throw new jw(Bw.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 jw(Bw.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===JV.LocalAudioTrack}));if(!(e.track instanceof Sk))throw new jw(Bw.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 jw(Bw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof Sk||o._bypassWebAudio)n.push({track:o,type:JV.LocalAudioTrack});else{const e=new Sk;e.addAudioTrack(o),n.push({track:e,type:JV.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=PO(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof Ek){const e=this.localTrackMap.get(JV.LocalAudioTrack);if(!e)continue;e.track instanceof Sk?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([JV.LocalAudioTrack,e]),e.track.close())):t.push([JV.LocalAudioTrack,e])}if(i instanceof dM){const e=this.localTrackMap.get(JV.LocalVideoTrack);if(!e)continue;t.push([JV.LocalVideoTrack,e]);const i=this.localTrackMap.get(JV.LocalVideoLowTrack);
6i&&t.push([JV.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case JV.LocalVideoTrack:t.addListener(uP.GET_STATS,this.handleGetLocalVideoStats),t.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(uP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(uP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case JV.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case JV.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof Sk?e.trackList.forEach((e=>{e.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(uP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(uP.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 JV.LocalVideoTrack:t.off(uP.GET_STATS,this.handleGetLocalVideoStats),t.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(uP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(uP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case JV.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case JV.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof Sk?e.trackList.forEach((e=>{e.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uP.GET_STATS,this.handleGetLocalAudioStats),e.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(uP.GET_STATS,this.handleGetLocalAudioStats),e.off(uP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(uP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof bM&&t.addListener(uP.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof wM&&t.addListener(uP.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(uP.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(YV.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(YV.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 JV.LocalAudioTrack:r=kV.Audio;break;case JV.LocalVideoTrack:r=Dn(n=o._hints).call(n,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:r=kV.Low}return{kind:s===JV.LocalAudioTrack?YV.AUDIO:YV.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 JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoLowTrack:i=kV.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;ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit
vendor: 54,778 bytes, line 6
6(ZV.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 KO(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),xD.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:cO.TRACER}).onSuccess(),this.emit(ZV.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(fD(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(SP.FIRST_FRAME_DECODED),xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_AUDIO_DECODE,MD.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:NB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(fD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_AUDIO_RECEIVED,MD.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:NB.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(fD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&xD.firstRemoteFrame(this.store.sessionId,kD.FIRST_VIDEO_RECEIVED,MD.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:NB.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(ZV.ConnectionTypeChange,i),ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Hx(t))," -> ").concat(JSON.stringify(Hx(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{ND.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Hx(t))," -> ").concat(JSON.stringify(Hx(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(ZV.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===fV.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,ND.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===fV.SEND_ONLY?this.restartICE(e):RO(this,ZV.RequestP2PRestartICE,{direction:fV.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(JV.LocalAudioTrack);if(e instanceof Ek&&(null==i?void 0:i.track)instanceof Sk)return i.track.isActive||t.push([JV.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]===JV.LocalVideoTrack)){const e=this.localTrackMap.get(JV.LocalVideoLowTrack);e&&t.push([JV.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(JV.LocalAudioTrack);if(e instanceof Ek&&(null==i?void 0:i.track)instanceof Sk)return i.track.isActive&&t.push([JV.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===JV.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(JV.LocalVideoLowTrack);e&&t.push([JV.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 JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:i=kV.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 JV.LocalAudioTrack:i=kV.Audio;break;case JV.LocalVideoTrack:i=Dn(t=r._hints).call(t,hP.SCREEN_TRACK)?kV.Screen:kV.High;break;case JV.LocalVideoLowTrack:i=kV.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 YV.VIDEO:return void(i._videoSSRC&&t.push({stream_type:YV.VIDEO,ssrcId:i._videoSSRC}));case YV.AUDIO:return void(i._audioSSRC&&t.push({stream_type:YV.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(JV.LocalVideoTrack),i=this.localTrackMap.get(JV.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!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;t<e.length;t++)if(e[t]instanceof Ek){const i=this.filterTobeUnmutedTracks(e[t]);if(0===i.length)continue;const n=this.createUnmuteMessage(i);return void await CO(this,ZV.RequestUnmuteLocal,n)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.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(ZV.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(ZV.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 KO(dN(this.dtlsFailedCount,cN)),this.emit(ZV.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(JV.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof dM))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof dM)).length>1)throw new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof Ek)).length>1&&(e.some((e=>e instanceof Ek&&e._bypassWebAudio))||!jD().webAudioMediaStreamDest))throw new jw(Bw.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 dM&&this.pendingLocalTracks.some((e=>e instanceof dM)))throw new jw(Bw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof Ek&&this.pendingLocalTracks.some((e=>e instanceof Ek))&&(!jD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof Ek&&e._bypassWebAudio))))throw new jw(Bw.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=!JN("DISABLE_DUAL_STREAM_USE_ENCODING")&&jD().supportDualStreamEncoding,n=_X(_X({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():mj(e,n);const o=YO(8,"track-low-"),s=new dM(r,_X(_X({},i&&{scaleResolutionDownBy:Wx(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(mP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,pP.LOW_STREAM)})),s._hints.push(hP.LOW_STREAM),e.addListener(uP.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(fD(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));xD.firstRemoteVideoDecode(this.store.sessionId,kD.FIRST_VIDEO_DECODE,MD.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:NB.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 jw(Bw.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new jw(Bw.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new jw(Bw.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new jw(Bw.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new jw(Bw.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new jw(Bw.NOT_SUPPORTED)}async preConnect(e){throw new jw(Bw.NOT_SUPPORTED)}getEstablishParams(){throw new jw(Bw.NOT_SUPPORTED)}async reSubscribe(e){throw new jw(Bw.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new jw(Bw.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===JV.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,pP.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},sV(hX.prototype,"p2pConnect",[tX],Object.getOwnPropertyDescriptor(hX.prototype,"p2pConnect"),hX.prototype),sV(hX.prototype,"unpublish",[iX],Object.getOwnPropertyDescriptor(hX.prototype,"unpublish"),hX.prototype),sV(hX.prototype,"unpublishLowStream",[nX],Object.getOwnPropertyDescriptor(hX.prototype,"unpublishLowStream"),hX.prototype),sV(hX.prototype,"subscribe",[rX],Object.getOwnPropertyDescriptor(hX.prototype,"subscribe"),hX.prototype),sV(hX.prototype,"mockSubscribe",[oX],Object.getOwnPropertyDescriptor(hX.prototype,"mockSubscribe"),hX.prototype),sV(hX.prototype,"unsubscribe",[sX],Object.getOwnPropertyDescriptor(hX.prototype,"unsubscribe"),hX.prototype),sV(hX.prototype,"muteRemote",[aX],Object.getOwnPropertyDescriptor(hX.prototype,"muteRemote"),hX.prototype),sV(hX.prototype,"unmuteRemote",[cX],Object.getOwnPropertyDescriptor(hX.prototype,"unmuteRemote"),hX.prototype),sV(hX.prototype,"hasRemoteMediaWithLock",[dX],Object.getOwnPropertyDescriptor(hX.prototype,"hasRemoteMediaWithLock"),hX.prototype),sV(hX.prototype,"disconnectForReconnect",[lX],Object.getOwnPropertyDescriptor(hX.prototype,"disconnectForReconnect"),hX.prototype),sV(hX.prototype,"remoteMediaSsrcChanged",[uX],Object.getOwnPropertyDescriptor(hX.prototype,"remoteMediaSsrcChanged"),hX.prototype),hX);function mX(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<t;o++)n[o]=arguments[o];switch(e){case eX.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e()}}case eX.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i)),t=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e(),t()}}}},n}}class fX extends rO{constructor(e,t){super(),bI(this,"signal",void 0),bI(this,"token",void 0),bI(this,"tokenTimeout",void 0),bI(this,"tokenInterval",void 0),bI(this,"_sequence",0),bI(this,"userMap",new Map),bI(this,"encoder",new TextEncoder),this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===hV.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*JN("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(Zh(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(s=n)&&void 0!==s?s:YO(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)};JN("SHOW_P2P_LOG")&&ND.debug("send message",d,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(d)).forEach((e=>{this.signal.request(_V.DATA_STREAM,{payload:FO(this.encoder.encode(e))})}));const l=new Wh(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),this.off(dx.ABORT,a),ND.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?r(new jw(Bw.INVALID_REMOTE_USER)):r(new jw(Bw.TIMEOUT))}),JN("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off(dx.ABORT,a),i&&t()},a=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),r(new jw(Bw.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)))};this.once(dx.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(dx.ABORT,a),"success"===i?t(c):r(new jw(Bw.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)))};let l=!1;i||(this.once("res-@".concat(n),c),KO(JN("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||ND.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(d))})))}));try{return await l}catch(o){if(o.code===Bw.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!==cx.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(mV.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=qp(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=[cx.ACK,cx.CHECK]).call(t,s))return s===cx.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):ND.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:YO(6,""),token:this.token,_type:cx.CHECK};JN("SHOW_P2P_LOG")&&ND.debug("send message",e),this.signal.request(_V.DATA_STREAM,{payload:FO(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:cx.ACK,token:this.token};JN("SHOW_P2P_LOG")&&ND.debug("send message",t),this.signal.request(_V.DATA_STREAM,{payload:FO(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(cx.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<a)return this.ack(e._id),void ND.debug("[external-signal] receive old message, seq: ".concat(n,", ").concat(e._message));o.set(n,e),s&&n===a&&(this.receiveMessage(e),o.delete(a),r.nextExpectedSequenceNumber++,t())}receiveMessage(e){const{_id:t,_type:i,_message:n,_uid:r}=e;if(JN("SHOW_P2P_LOG")&&ND.debug("receive message",e),t){let o;switch(e._type!==cx.ACK&&(n&&(o=JSON.parse(n)),this.ack(e._id)),e._type){case cx.CANDIDATE:case cx.CONTROL:this.signal.emit(i,o,r);break;case cx.PUBLISH:case cx.UNPUBLISH:case cx.RESTART_ICE:case cx.CALL:o.uid=r,RO(this.signal,i,o).then((t=>{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case cx.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case cx.RESPONSE:{const{success:e,message:i}=o;this.emit("res-@".concat(t),e?"success":"failed",i);break}}}}splitMessage(e){if(e.length<fX.MAX_MESSAGE_SIZE)return[e];const t=[],{remoteToken:i}=JSON.parse(e),n=YO(6,"");let r=0,o=800;const s=Math.ceil(e.length/o);for(;e.length>0;){r++;const a={id:n,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(i)};JSON.stringify(a).length>fX.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?(ND.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((()=>{ND.debug("token timeout, ".concat(t)),this.reset(e.uid)}),JN("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await RO(this.signal,cx.CALL,void 0),t=await this.send(cx.CALL,e);this.signal.emit(pV.P2P_CONNECTION,t,!0)}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(dx.ABORT),this.signal.emit(mV.ON_USER_OFFLINE,{uid:i.uid,reason:ux.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(ND.debug("change local token from ".concat(t," to ").concat(t)),this.token=YO(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(dx.ABORT)}}bI(fX,"MAX_SIZE",1),bI(fX,"MAX_MESSAGE_SIZE",1024);class SX extends rO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===hV.CONNECTED?this.emit(pV.WS_CONNECTED):e===hV.RECONNECTING?this.emit(pV.WS_RECONNECTING,this._websocketReconnectReason):e===hV.CLOSED&&this.emit(pV.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(),bI(this,"__name__","P2PSignal"),bI(this,"_disconnectedReason",void 0),bI(this,"_websocketReconnectReason",void 0),bI(this,"_connectionState",hV.CLOSED),bI(this,"reconnectToken",void 0),bI(this,"p2pToken",void 0),bI(this,"websocket",void 0),bI(this,"openConnectionTime",void 0),bI(this,"clientId",void 0),bI(this,"lastMsgTime",Date.now()),bI(this,"uploadCache",[]),bI(this,"uploadCacheInterval",void 0),bI(this,"rttRolling",new hN(5)),bI(this,"pingpongTimer",void 0),bI(this,"pingpongTimeoutCount",0),bI(this,"joinResponse",void 0),bI(this,"multiIpOption",void 0),bI(this,"initError",void 0),bI(this,"spec",void 0),bI(this,"store",void 0),bI(this,"_external_signal",void 0),bI(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(pV.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 mV.ON_DATA_STREAM:return void this.handleDataStream(t._message);case mV.MUTE_AUDIO:case mV.MUTE_VIDEO:case mV.ON_P2P_LOST:case mV.ON_USER_ONLINE:return;case mV.ON_USER_OFFLINE:const{uid:e}=t._message;return ND.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===mV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===mV.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(uO.UID_BANNED);break;case 15:this.close(uO.IP_BANNED);break;case 16:this.close(uO.CHANNEL_BANNED)}if(t._type===mV.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case uV.ERR_LICENSE_MISSING:this.close(uO.LICENSE_MISSING);break;case uV.ERR_LICENSE_EXPIRED:this.close(uO.LICENSE_EXPIRED);break;case uV.ERR_LICENSE_MINUTES_EXCEEDED:this.close(uO.LICENSE_MINUTES_EXCEEDED);break;case uV.ERR_LICENSE_PERIOD_INVALID:this.close(uO.LICENSE_PERIOD_INVALID);break;case uV.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(uO.LICENSE_MULTIPLE_SDK_SERVICE);break;case uV.ERR_LICENSE_ILLEGAL:this.close(uO.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new bx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,JN("JOIN_GATEWAY_USE_DUAL_DOMAIN"),JN("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===hV.CONNECTED&&this.reconnect("retry",SO.OFFLINE)})),this.p2pToken=YO(6,""),this._external_signal=new fX(this,this.p2pToken)}async request(e,t,i,n){const r=YO(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((e,t)=>{if(this.connectionState===hV.CONNECTED)return e();const i=()=>{this.off(pV.WS_CLOSED,n),e()},n=()=>{this.off(pV.WS_CONNECTED,i),t(new jw(Bw.WS_ABORT))};this.once(pV.WS_CONNECTED,i),this.once(pV.WS_CLOSED,n)}));if(this.connectionState!==hV.CONNECTING&&this.connectionState!==hV.RECONNECTING||e===_V.JOIN||e===_V.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Wh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.emit(pV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new jw(Bw.WS_ABORT,"type: ".concat(e))),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(pV.WS_CLOSED,c),this.once(pV.WS_RECONNECTING,c),KO(JN("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(ND.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(pV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===hV.CLOSED||e===_V.LEAVE)throw new jw(Bw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===_V.JOIN||e===_V.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=Ex(l),h=new jw(Bw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(ND.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===uV.ERR_TOO_MANY_BROADCASTERS?e===_V.JOIN||e===_V.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===uV.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,ND.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",SO.MULTI_IP)):this.reconnect(u.action,SO.SERVER_ERROR),e===_V.JOIN||e===_V.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((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 ND.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(EV.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=JN("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!==hV.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)}),JN("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 Wh(((t,i)=>{this.once(pV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(pV.WS_CLOSED,(()=>i(this.initError||new jw(Bw.WS_ABORT)))),this.connectionState=hV.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||uO.LEAVE,this.connectionState=hV.CLOSED,ND.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=YO(6,""),this._external_signal.clear(),this._external_signal=new fX(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(pV.ABORT_P2P_EXECUTION);const e=await RO(this,pV.REQUEST_JOIN_INFO),t=await this.request(_V.JOIN,e);if(!t)return this.emit(pV.REPORT_JOIN_GATEWAY,Bw.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(pV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=hV.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)}async downgradeCodec(e){return!1}handleDataStream(e){try{var t;const i=xO(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);"total"in r&&"id"in r||Dn(t=Object.values(cx)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(mV.ON_DATA_STREAM,e)}catch(t){this.emit(mV.ON_DATA_STREAM,e)}}handleNotification(e){ND.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Ex(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===uV.ERR_REPEAT_JOIN_CHANNEL&&JN("IGNORE_UID_CHECK")?void this.close(uO.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(uO.UID_BANNED),void this.close()):void this.reconnect(t.action,SO.SERVER_ERROR);ND.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=JN("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(ND.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>JN("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",SO.TIMEOUT):this.request(_V.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),JN("REPORT_STATS")&&this.send(_V.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(SV.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(pV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(SV.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SV.CLOSED,(()=>{this.connectionState=hV.CLOSED})),this.websocket.on(SV.FAILED,(()=>{this._disconnectedReason=uO.NETWORK_ERROR,this.connectionState=hV.CLOSED})),this.websocket.on(SV.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===hV.CONNECTED?this.connectionState=hV.RECONNECTING:this.connectionState=hV.CONNECTING})),this.websocket.on(SV.WILL_RECONNECT,((e,t,i)=>{"retry"!==e?(ND.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):ND.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e)})),this.websocket.on(SV.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(pV.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof jw&&e.code===Bw.UNEXPECTED_RESPONSE&&e.data.code===uV.ERR_NO_AUTHORIZED)return ND.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",SO.SERVER_ERROR);ND.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",SO.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(SV.REQUEST_NEW_URLS,((e,t)=>{RO(this,pV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(SV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(mV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const gX={name:"P2PChannel",create:function(e){let{store:t,statsCollector:i}=e;return new EX(t,i)},createSubmodule:function(e){let{store:t,spec:i}=e;return new SX(i,t)}};function TX(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 RX(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?TX(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):TX(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class CX{constructor(e){bI(this,"sessionDesc",void 0),bI(this,"localCapabilities",void 0),bI(this,"rtpCapabilities",void 0),bI(this,"candidates",void 0),bI(this,"_originCandidates",void 0),bI(this,"iceParameters",void 0),bI(this,"dtlsParameters",void 0),bI(this,"setup",void 0),bI(this,"currentMidIndex",void 0),bI(this,"cname",void 0),e=kO(e);const{iceParameters:t,dtlsParameters:i,candidates:n,rtpCapabilities:r,setup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=aD("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._originCandidates=kO(n),this.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=s,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){const s=d.mediaDescriptions[e];if(s.attributes.iceUfrag=t.iceUfrag,s.attributes.icePwd=t.icePwd,s.attributes.fingerprints=i.fingerprints,s.attributes.candidates=n,s.attributes.setup=o,"video"===s.media.mediaType){s.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10)));const 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)})),t=r.videoCodecs.filter((t=>!Dn(e).call(e,t)));s.attributes.payloads=[...e,...t],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 cD(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=cF(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===YV.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){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(RX(RX({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case zV.TCP_RELAY:this.candidates=i;break;case zV.UDP_TCP_RELAY:case zV.RELAY:this.candidates=[...t,...i];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=kO(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<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}mungRecvMediaDsec(e,t){const i=kO(e);return dF(i,t),uF(i,t),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}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===YV.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;if(e)e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i)}}mungMediaDesc(e){const t=kO(e);return lF(t),function(e){const t=e.attributes.extmaps.find((e=>eF(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]}getPtFromCodec(e){const t=this.rtpCapabilities.audioCodecs.find((t=>{var i;if((null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)===e)return!0}));return null==t?void 0:t.payloadType}}var vX;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 IX(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yX(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yX(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let AX=(vX=class e extends KV{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(eD)).call(t,e)})))]}constructor(t,i){super(t,i),bI(this,"store",void 0),bI(this,"peerConnection",void 0),bI(this,"remoteSDP",void 0),bI(this,"initialOffer",void 0),bI(this,"statsFilter",void 0),bI(this,"useRTX",!1),bI(this,"localCapabilities",void 0),bI(this,"localCandidateCount",0),bI(this,"allCandidatesReceived",!1),bI(this,"establishPromise",void 0),bI(this,"mutex",void 0),this.store=i,this.mutex=new sN("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=VN(this.peerConnection,JN("STATS_UPDATE_INTERVAL"),void 0,_w()?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=rF(e.sdp),i=nF(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:JN("FILTER_VIDEO_FEC"),filterAudioFec:JN("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,IX(IX({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new jw(Bw.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 CX(IX(IX({},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 jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new jw(Bw.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var i=this;return ub((function*(){const n=yield hb(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 hb(i.peerConnection.createOffer()),s=aD(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=>{hw()&&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 hb(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(i.applySendEncodings(r,e)),yield hb(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 jw(Bw.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=>{hw()&&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 jw(Bw.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 Wh(((t,n)=>{const o=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=n=>{const a=sw();if(("Safari"===a.name&&11===Number(a.version)||Ew())&&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);const c=await o;let d;return"audio"==e&&(d=this.remoteSDP.getPtFromCodec(this.store.audioCodec)),{track:c,id:i,pt:d}}catch(e){throw new jw(Bw.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 jw(Bw.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(hw()&&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 jw(Bw.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(hw()&&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 jw(Bw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return ub((function*(){const i=yield hb(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=jD().supportPCSetConfiguration;if(e===zV.RELAY&&!n)return;if(n){const i=t.peerConnection.getConfiguration(),n=e===zV.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(ND.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}e!==zV.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield hb(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=rF(r.sdp),{remoteIceParameters:s}=yield o.iceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield hb(t.peerConnection.setLocalDescription(r)),yield hb(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){ND.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 jw(Bw.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 jw(Bw.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new jw(Bw.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,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),JN("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&&(hO(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),JN("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 ND.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!jD().supportSetRtpSenderParameters)return ND.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof dM)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(JN("DSCP_TYPE")&&kw()){var o;const e=JN("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),ND.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!jD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];n&&r&&await this.updateRtpSenderEncodings(r,n)}}catch(e){ND.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const i=aD(e);return t.forEach(((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&dF(r,e)})),cD(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 Wh(((e,t)=>{const i=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=sw();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 Wh.all(t)}catch(e){throw new jw(Bw.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(jD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}
6,sV(vX.prototype,"connect",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"connect"),vX.prototype),sV(vX.prototype,"stopSending",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"stopSending"),vX.prototype),sV(vX.prototype,"receive",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"receive"),vX.prototype),sV(vX.prototype,"stopReceiving",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"stopReceiving"),vX.prototype),sV(vX.prototype,"muteRemote",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"muteRemote"),vX.prototype),sV(vX.prototype,"unmuteRemote",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"unmuteRemote"),vX.prototype),sV(vX.prototype,"muteLocal",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"muteLocal"),vX.prototype),sV(vX.prototype,"unmuteLocal",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"unmuteLocal"),vX.prototype),sV(vX.prototype,"close",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"close"),vX.prototype),sV(vX.prototype,"updateEncoderConfig",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"updateEncoderConfig"),vX.prototype),sV(vX.prototype,"updateSendParameters",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"updateSendParameters"),vX.prototype),sV(vX.prototype,"replaceTrack",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"replaceTrack"),vX.prototype),sV(vX.prototype,"getRemoteSSRC",[bX],Object.getOwnPropertyDescriptor(vX.prototype,"getRemoteSSRC"),vX.prototype),vX);function bX(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;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}const wX={name:"PlanBConnection",create:function(e){let{store:t,spec:i}=e;return new AX(i,t)}},OX={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!jD().supportWebRTCEncodedTransform)return void ND.warning("browser not support audio encoded transform");if(jM.has(e))return;if(!e.track)return;const i={track:e.track};if(!uw()&&!Dw()||Ew()){if("undefined"==typeof RTCRtpScriptTransform)return void ND.warning("browser not support RTCRtpScriptTransform");const r=LM(),o=new MessageChannel;await new Wh((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=s,await new Wh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var s;if(r.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id)ND.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n);else if(r.data.getMetadata){const e=t.metadata&&t.metadata(),i=t.pts&&t.pts();(e||void 0!==i)&&o.port1.postMessage({metadata:e,pts:i})}},i.worker=r}else{if(!e.createEncodedStreams)return void ND.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void ND.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(ND.debug("audio 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=t.metadata&&t.metadata(),a=t.pts&&t.pts();s||a?function(e,t,i){const{chunk:n,controller:r}=i,o=function(e,t){if(void 0===e&&void 0===t)return null;let i=0,n=null,r=null;if(e){const t=e.length,r=VM+xM+t;n=new Uint8Array(r);const o=new DataView(n.buffer);o.setUint8(0,FM.METADATA),o.setUint16(VM,t),n.set(e,VM+xM),i+=r}if(t){const e=8,n=VM+xM+e;r=new Uint8Array(n);const o=new DataView(r.buffer);o.setUint8(0,FM.AUDIO_64_BIT_PTS),o.setUint16(VM,e),o.setBigUint64(VM+xM,t.valueOf(),!0),i+=n}const o=new Uint8Array(MM+UM+i),s=new DataView(o.buffer);s.setUint8(0,kM),s.setUint16(MM,i);let a=MM+UM;return n&&(o.set(n,a),a+=n.length),r&&o.set(r,a),o}(e,t);if(o){const e=new Uint8Array(o.length+n.data.byteLength);e.set(o,0),e.set(new Uint8Array(n.data),o.byteLength),n.data=e.buffer}r.enqueue(n)}(s,a,{sender:e,chunk:r,controller:o}):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}const t=jM.get(e);if(t){jM.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){ND.warning(e&&e.message)}}}jM.set(e,i),e.track.addEventListener("ended",n)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!jD().supportWebRTCEncodedTransform)return void ND.warning("browser not support audio encoded transform");if(dU.has(e))return;const i={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};
vendor: 33,382 bytes, line 6
6if(!uw()&&!Dw()||Ew()){if("undefined"==typeof RTCRtpScriptTransform)return void ND.warning("browser not support RTCRtpScriptTransform");const r=LM(),o=new MessageChannel;await new Wh((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-rx",port:o.port2,pt:t.pt},[o.port2]);e.transform=s,await new Wh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),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?(ND.debug("audio 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.metadata&&i.onMetadata?i.onMetadata(t.data.metadata):t.data.pts&&i.onPts&&i.onPts(t.data.pts)},i.worker=r}else{if(!e.createEncodedStreams)return void ND.warning("browser not support createEncodedStreams() API");Sw(iw.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(e){return void ND.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(ND.debug("audio 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.enableTopn?function(e,t,i){var n;const r=BM(new DataView(t.data));if(!r)return i.enqueue(t);const o=e.track.id;lU.set(o,e.track);const s=null===(n=r.tlv.find((e=>e.tag===FM.AUDIO_LEVEL)))||void 0===n?void 0:n.value;let a=0;"number"==typeof s&&(a=127-s);const c=Math.round(Math.pow(10,a/60)-1),{selected:d,speaker:l}=function(e,t){let i=$M.get(e);if(i||(i=function(e){const t=new XM;return $M.set(e,t),eU||(eU=new ZM(JN("TOPN_SILENCE_THRESHOLD")||500),eU.on("ActiveSpeakerChanged",(e=>{null!=e&&(tU=e)}))),eU.addSpeakers([t]),t}(e)),$M.size<=iU)return{selected:!0,speaker:i};if(!eU)throw new Error("no active speaker detector");return eU.levelChanged(i.id,t),nU=eU.loudest.map((e=>e.id)),tU&&!Dn(nU).call(nU,tU)&&nU.length>=iU&&nU.pop(),{selected:Dn(nU).call(nU,i.id)||i.id===tU,speaker:i}}(e,c),u=function(e,t,i){const n=rU.get(e)||new sU(e,t);return n.score=i,rU.set(e,n),function(e){if(oU.set(e,!0),!aU)return void(aU=Date.now());const t=Date.now();t-aU>1e3&&(oU.get(e)?oU.set(e,!1):(cU(e),oU.delete(e)),aU=t)}(e),n}(o,e.track,l.energyScore);u.addSample(d),u.active&&(t.data=r.frame.buffer,i.enqueue(t))}(e,r,o):t.enableMetadata||t.enablePts?function(e,t,i,n,r){const o=new DataView(e.data),s=e.getMetadata();let a,c=!1;if(c=s&&void 0!==s.mimeType?"audio/red"===s.mimeType:function(e,t){if(void 0===t)return!1;const i=e.getUint8(0);return 71!==i&&!!(128&i&&(127&i)===t)}(o,t),c){const t=function(e){if(e.byteLength<=0)return[];const t=[];let i=0;for(;i<e.byteLength;){const n=(128&e.getUint8(i))>>7,r=127&e.getUint8(i);if(!(n&&i+4<=e.byteLength)){i++;break}{const n=e.getUint32(i,!1),o=(16776192&n)>>10,s=1023&n;t.push({pt:r,ts_offset:o,length:s,data:new Uint8Array}),i+=4}}let n=e.byteLength-i;for(const r of t){if(r.length>n)return console.warn("Broken red payload"),[];r.length>0&&(r.data=new Uint8Array(e.buffer,e.byteOffset+i,r.length),i+=r.length,n-=r.length)}if(n>0){const r={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:n,data:new Uint8Array(e.buffer,e.byteOffset+i,n)};t.push(r)}return t}(o);if(t.length>0){const i=function(e){let t=0;for(let i=0;i<e.length;i++)t+=i<e.length-1?4:1,t+=e[i].length;const i=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++)if(t<e.length-1){const r=(2147483648|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].length)>>>0;i[n++]=r>>24&255,i[n++]=r>>16&255,i[n++]=r>>8&255,i[n++]=255&r}else i[n++]=127&e[t].pt;for(const t of e)i.set(t.data,n),n+=t.length;return i}(t.map((e=>{const t=new Uint8Array(e.length);t.set(e.data);const i=BM(new DataView(t.buffer));return null!=i&&i.frame&&(e.data=null==i?void 0:i.frame),a=i,e})));e.data=i.buffer}}else a=BM(o),a&&(e.data=a.frame.buffer);if(i.enqueue(e),!a)return;const d=a.tlv.find((e=>e.tag===FM.METADATA));d&&n&&d.value instanceof Uint8Array&&n(d.value);const l=a.tlv.find((e=>e.tag===FM.AUDIO_64_BIT_PTS));l&&r&&l.value instanceof Uint8Array&&8==l.value.length&&r(new DataView(l.value.buffer).getBigUint64(0,!0))}(r,t.pt,o,t.onMetadata,t.onPts):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}function n(){e.track.removeEventListener("ended",n),function(e){const t=dU.get(e);if(t){!function(e){const t=$M.get(e);t&&($M.delete(e),eU&&(eU.removeSpeakers([t]),0===$M.size&&(eU.destroy(),eU=null)))}(e),cU(e.track.id),dU.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){ND.warning(e&&e.message)}}}(e)}dU.set(e,i),e.track.addEventListener("ended",n)},interceptLocalVideoFrame:async function(e,t){if(!jD().supportWebRTCEncodedTransform)return void ND.warning("browser not support video encoded transform");if(mU.has(e))return;if(!e.track)return;const i={track:e.track};if(!uw()&&!Dw()||Ew()){if("undefined"==typeof RTCRtpScriptTransform)return void ND.warning("browser not support RTCRtpScriptTransform");const r=LM(),o=new MessageChannel;await new Wh((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=s,await new Wh((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&&(ND.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}else{if(!e.createEncodedStreams)return void ND.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void ND.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const s=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(ND.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=EU(new Uint8Array(t.data)),a=o.shift();if(a){const e=function(e,t,i){switch(i){case uU:return function(e,t){const i=_U(t),n=i.length,r=Math.floor(n/255),o=n%255,s=new Uint8Array(6+r+1+n+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=6,s[5]=101;let a=0;for(;a<r;)s[6+a]=255,a++;return s[6+a]=o,a++,s.set(i,6+a),s.set(new Uint8Array(e),6+a+n),s.buffer}(e,t);case hU:return function(e,t){const i=_U(t),n=i.length,r=Math.floor(n/255),o=n%255,s=new Uint8Array(7+r+1+n+1+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=78,s[5]=1,s[6]=101;let a=0;for(;a<r;)s[7+a]=255,a++;return s[7+a]=o,a++,s.set(i,7+a),a+=n,s[7+a]=128,a++,s.set(new Uint8Array(e),7+a),s.buffer}(e,t);default:return null}}(t.data,a,s);e&&(t.data=e)}r.enqueue(t)}});r.readable.pipeThrough(s).pipeTo(r.writable)}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}const t=mU.get(e);if(t){mU.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){ND.warning(e&&e.message)}}}mU.set(e,i),e.track.addEventListener("ended",n)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!jD().supportWebRTCEncodedTransform)return void ND.warning("browser not support video encoded transform");if(!e.track)return;if(fU.has(e)){const i=fU.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(!uw()&&!Dw()||Ew()){if("undefined"==typeof RTCRtpScriptTransform)return void ND.warning("browser not support RTCRtpScriptTransform");const r=LM(),o=new MessageChannel;await new Wh((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-rx",port:o.port2},[o.port2]);e.transform=s,await new Wh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var o;if(r.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==i.track.id)ND.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);else if(r.data.sei&&i.onSei)i.onSei(r.data.sei);else if(r.data.firstFrameInfo&&t.onFirstFrame){var s;null===(s=t.onFirstFrame)||void 0===s||s.call(t,r.data.firstFrameInfo)}},i.worker=r}else{if(!e.createEncodedStreams)return void ND.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void ND.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){if(i.controller||(i.controller=o),!i.firstFrameInfo){var s;const e=r.getMetadata()||{};i.firstFrameInfo=MP({type:r.type,rtpTimestamp:r.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:r.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null===(s=t.onFirstFrame)||void 0===s||s.call(t,i.firstFrameInfo)}e.track&&e.track.id!==i.track.id&&(ND.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 a=function(e,t){switch(t){case uU:return function(e){const t=new DataView(e.data);let i=0;for(;i+4<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&6===t.getUint8(i+4)){let n=i+6,r=0,o=0;for(;255===(o=t.getUint8(n++));)r+=255;r+=o;const s=pU(e.data,n,r);return new Uint8Array(s)}i++}return null}(e);case hU:return function(e){const t=new DataView(e.data);let i=0;for(;i+5<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&78===t.getUint8(i+4)&&1===t.getUint8(i+5)&&101===t.getUint8(i+6)){let n=i+7,r=0,o=0;for(;255===(o=t.getUint8(n++));)r+=255;r+=o;const s=pU(e.data,n,r);return new Uint8Array(s)}i++}return null}(e);default:return null}}(r,EU(new Uint8Array(r.data)));a&&i.onSei&&i.onSei(a),o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}!function(e){const t=fU.get(e);if(t){fU.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){ND.warning(e&&e.message)}}}(e)}fU.set(e,i),e.track.addEventListener("ended",n)}},NX={name:"InterceptFrame",create:()=>OX};var DX;function PX(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 LX(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?PX(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):PX(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let kX=(DX=class e extends KV{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(eD)).call(t,e)})))]}constructor(e,t,i){super(e,t),bI(this,"id",YO(5,"connection-")),bI(this,"store",void 0),bI(this,"peerConnection",void 0),bI(this,"forceTurn",!1),bI(this,"remoteSDP",void 0),bI(this,"initialOffer",void 0),bI(this,"transportEventReceiver",void 0),bI(this,"statsFilter",void 0),bI(this,"extension",{useXR:JN("USE_XR")}),bI(this,"localCapabilities",void 0),bI(this,"remoteCodecs",void 0),bI(this,"localCandidateCount",0),bI(this,"allCandidatesReceived",!1),bI(this,"isPreallocation",!1),bI(this,"preMediaMap",new Map),bI(this,"dataStreamChannelMap",new Map),bI(this,"establishPromise",void 0),bI(this,"recoveredDataChannelIds",[]),bI(this,"currentDataChannelId",1),bI(this,"supportAV1RtpSpec",!1),bI(this,"mutex",void 0),bI(this,"qualityLimitationReason",ON.NONE),bI(this,"isFirstConnected",!1),this.store=t,this.forceTurn=lj(e),this.mutex=new sN("NVConnectionExtension-mutex",t.clientId),this.peerConnection=i,this.isFirstConnected=!1,this.statsFilter=VN(this.peerConnection,JN("STATS_UPDATE_INTERVAL"),void 0,_w()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void ND.debug("[NVConnectionExtension] 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 ND.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const i=rF(t.sdp),n=await mF({filterRTX:!JN("USE_PUB_RTX")&&!JN("USE_SUB_RTX"),filterVideoFec:JN("FILTER_VIDEO_FEC"),filterAudioFec:JN("FILTER_AUDIO_FEC"),filterVideoCodec:JN("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:JN("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:JN("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=gF(n),this.initialOffer=t,JN("ENABLE_SVC")&&"av1"==this.store.codec){const t=await EF();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=n.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&bF(t.sdp)&&(r=kO(n),Xx(r)),LX(LX({},i),{},{rtpCapabilities:r||n,offerSDP:t.sdp})}catch(e){throw new jw(Bw.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");this.initialOffer.sdp&&bF(this.initialOffer.sdp)&&Jx(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new WB(LX(LX({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!JN("ENABLE_PRE_SUB_WITH_PRE_PC")||!JN("PRE_USE_LOCAL_CODECS"))&&KD(this.store),!0),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=yF(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),KD(this.store))if(e.preallocation&&JN("ENABLE_PRE_SUB_WITH_PRE_PC")){const e=JN("PRE_SUB_NUM"),{mids:t,preSSRCs:i}=this.remoteSDP.preloadRemoteMedia(e);await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] preload media, in pre pc,add preload ssrcs ").concat(i)),this.presetMedia(t,i)}else{const{preSSRCs:t=[]}=e,i=t.map((e=>e.ssrcMsg[0].ssrcId));if(0===t.length)return;const{mids:n}=this.remoteSDP.batchSend(t.map((e=>Object.assign({},e))));await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[NVConnectionExtension.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(n,i)}}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,i)=>{this.peerConnection.getTransceivers().forEach((n=>{if(null!=n.mid&&e===n.mid&&n.receiver.track){const r=n.receiver.track;let o;"video"===r.kind&&JN("ENABLE_PRE_RENDER")&&(o=new yk({trackId:"track-".concat(r.kind,"-unknown-").concat(this.store.clientId,"_").concat(YO(5,""))},!0),o.updateVideoTrack(r),o.onFirstVideoFrameRender=()=>{var e;const n=this.preMediaMap.get(t[i]);n&&(n.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[i])},o.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[i])},o.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[i],{mid:e,track:r,player:o,transceiver:n})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1;const{rtpCapabilities:i}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const{preSSRCs:n=[]}=e,r=n.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(r)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((i=>{let[n,{mid:r,player:o,track:s}]=i;return e.push(r),t.push(n),this.preMediaMap.delete(n),o&&o.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await vF(this.peerConnection,this.remoteSDP,this.extension),ND.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),xD.reportApiInvoke(this.store.sessionId,{name:aO.PRELOAD_MEDIA_FAILED,options:[n,t],tag:cO.TRACER}).onSuccess()),n.length>0){const{mids:e}=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e))));await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(r)),this.presetMedia(e,r)}}t?(await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):ND.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return ub((function*(){const r=yield hb(n.mutex.lock("From NVConnectionExtension.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const o=[],s=zx();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,LX({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),_w()&&!0===JN("SIMULCAST")&&(yield hb(n.applySimulcastForFirefox(o,e)));const a=yield hb(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(a.sdp,e,c),l=aD(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return oF(t,JN("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield hb(n.stopSending(c,!0)),r}n.remoteSDP.receive(e,t,i,h);const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return yield hb(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield hb(n.applySimulcastEncodings(o,e)),yield hb(n.applySendEncodings(o,e)),null==_||_(p),yield hb(n.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=c[t];return{localSSRC:u[t],id:i,transceiver:e}}))}catch(e){throw e instanceof jw?e:new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)ND.debug("[NVConnectionExtension] 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:JN("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),ND.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else ND.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof jw?e:new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.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 jw?e:new jw(Bw.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.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 NVConnectionExtension.stopSending.");t.map((e=>{var t;nj(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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);o&&(await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] 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,pt:void 0,transceiver:s}}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await vF(this.peerConnection,this.remoteSDP,this.extension),ND.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] 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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let[i,{mid:n,player:r}]=t;if(n===e)return this.preMediaMap.delete(i),r&&r.destroy(),!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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.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 jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.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),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new jw(Bw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return ub((function*(){const i=yield hb(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=jD().supportPCSetConfiguration,r=JN("FORCE_TURN_TCP")||t.forceTurn;if(e===zV.RELAY&&!n)return;if(n&&!r){const i=e===zV.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(ND.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const o=yield hb(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=rF(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield hb(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield hb(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){ND.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(zV.TCP_RELAY),await vF(this.peerConnection,this.remoteSDP,this.extension)}catch(e){ND.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{nj(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let{player:t}=e;t&&t.destroy()})),this.preMediaMap.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 LX(LX({},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 NVConnectionExtension.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 jw(Bw.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)?_w()||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:LX(LX({},RN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:LX(LX({},RN),{},{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;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",r=Kx(e.url||"");ND.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(i,"), url: ").concat(r||"",", host_c
6andidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,ND.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),JN("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:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(hO(t.turnServer.servers)?i.iceServers=t.turnServer.servers:JN("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(JN("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),JN("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),JN("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),JN("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),JN("ENABLE_ENCODED_TRANSFORM")&&jD().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(Mx(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!JN("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}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=JN("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Mx(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Mx(e.turnServerURL),":443?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}
6=i.getSelectedCandidatePair()||{};if(e&&t){const i=e.address+":"+e.port,n=t.address+":"+t.port;ND.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Kx(i)),", remote ").concat(JSON.stringify(Kx(n))))}}}))}}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 ND.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return ND.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!jD().supportSetRtpSenderParameters)return ND.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=Yx(this.peerConnection,e._mediaStreamTrack),a=IL(e);if(ej(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,hP.CUSTOM_TRACK)?JN("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");ij(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,hP.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=xx(i)),n&&n>=1&&(o.scaleResolutionDownBy=n))}const{maxFramerate:l}=JN("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),JN("DSCP_TYPE")&&kw()){var u;const e=JN("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];_w()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),ND.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await AF(this.store.codec,t,JN("SVC_MODE"))}async updateAdaptation(e,t){var i,n;if(!e)return ND.debug("[updateAdaptation] no rtpSender found");if(!jD().supportSetRtpSenderParameters)return ND.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=xx(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),ND.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?ND.debug("[updateAdaptation] peerConnection not connected}"):ND.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):ND.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!jD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof dM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){ND.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=aD(e);return t.forEach(((e,t)=>{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(dF(o,e),_F(o,e,this.store.codec))})),cD(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;a<e.length;a++){var i,n,r,o,s;const c=e[a],d=t[a];if(d instanceof dM&&!Dn(i=d._hints).call(i,hP.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>
vendor: 58,269 bytes, line 6
6200&&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(!_w()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof dM&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r,o;return!!(e instanceof dM&&JN("SIMULCAST")&&"vp8"===this.store.codec&&!Dn(t=e._hints).call(t,hP.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&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(JN("SDP_LOGGING"))return ND.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during NVConnectionExtension.").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(jD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},sV(DX.prototype,"updateRemoteRTPCapabilities",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"updateRemoteRTPCapabilities"),DX.prototype),sV(DX.prototype,"connect",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"connect"),DX.prototype),sV(DX.prototype,"updateRemoteConnect",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"updateRemoteConnect"),DX.prototype),sV(DX.prototype,"createDataChannels",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"createDataChannels"),DX.prototype),sV(DX.prototype,"receive",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"receive"),DX.prototype),sV(DX.prototype,"batchReceive",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"batchReceive"),DX.prototype),sV(DX.prototype,"stopReceiving",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"stopReceiving"),DX.prototype),sV(DX.prototype,"muteRemote",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"muteRemote"),DX.prototype),sV(DX.prototype,"unmuteRemote",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"unmuteRemote"),DX.prototype),sV(DX.prototype,"muteLocal",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"muteLocal"),DX.prototype),sV(DX.prototype,"unmuteLocal",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"unmuteLocal"),DX.prototype),sV(DX.prototype,"close",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"close"),DX.prototype),sV(DX.prototype,"updateEncoderConfig",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"updateEncoderConfig"),DX.prototype),sV(DX.prototype,"updateSendParameters",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"updateSendParameters"),DX.prototype),sV(DX.prototype,"replaceTrack",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"replaceTrack"),DX.prototype),sV(DX.prototype,"updateAdaptation",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"updateAdaptation"),DX.prototype),sV(DX.prototype,"getRemoteSSRC",[MX],Object.getOwnPropertyDescriptor(DX.prototype,"getRemoteSSRC"),DX.prototype),DX);function MX(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 NVConnectionExtension.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}var UX;function VX(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=_b,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new xX(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function xX(e){function t(e){if(Object(e)!==e)return Wh.reject(new TypeError(e+" is not an object."));var t=e.done;return Wh.resolve(e.value).then((function(e){return{value:e,done:t}}))}return xX=function(e){this.s=e,this.n=e.next},xX.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Wh.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Wh.reject(e):t(i.apply(this.s,arguments))}},new xX(e)}let FX=(UX=class e extends KV{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,i){super(t,i),bI(this,"name","DataChannelConnection"),bI(this,"store",void 0),bI(this,"peerConnection",void 0),bI(this,"cname",void 0),bI(this,"mutex",new sN("DataChannelConnection-mutex")),bI(this,"dataChannel",void 0),bI(this,"_p2pConnection",void 0),bI(this,"establishPromise",void 0),bI(this,"_nvMedia",void 0),this.store=i,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new kX(t,i,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(e){var t;return null===(t=this._p2pConnection)||void 0===t?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!==(e=null===(t=this._p2pConnection)||void 0===t?void 0:t.isPreSub())&&void 0!==e&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new Wh(((t,i)=>{const n=setTimeout((()=>{this.closeSignal(),i(new FD(Bw.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),JN("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),i(e)},this.dataChannel.addEventListener("close",(()=>{i(new FD(Bw.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,i){var n=this;return ub((function*(){const r=yield hb(n.mutex.lock("From DataChannelConnection.send"));try{return yield*pb(VX(n._p2pConnection.send(e,t,i)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,n){return this._nvMedia?(ND.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(ND.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return ub((function*(){return yield*pb(VX(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;return null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,n){if(JN("SDP_LOGGING"))return ND.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(hO(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),JN("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),JN("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),JN("ENABLE_ENCODED_TRANSFORM")&&jD().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(Mx(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!JN("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}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null===(t=this.onFirstVideoRender)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null===(t=this.onFirstVideoBufferReady)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}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}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},sV(UX.prototype,"connect",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"connect"),UX.prototype),sV(UX.prototype,"updateRemoteRTPCapabilities",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"updateRemoteRTPCapabilities"),UX.prototype),sV(UX.prototype,"createDataChannels",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"createDataChannels"),UX.prototype),sV(UX.prototype,"receive",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"receive"),UX.prototype),sV(UX.prototype,"stopReceiving",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"stopReceiving"),UX.prototype),sV(UX.prototype,"muteRemote",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"muteRemote"),UX.prototype),sV(UX.prototype,"unmuteRemote",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"unmuteRemote"),UX.prototype),sV(UX.prototype,"muteLocal",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"muteLocal"),UX.prototype),sV(UX.prototype,"unmuteLocal",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"unmuteLocal"),UX.prototype),sV(UX.prototype,"close",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"close"),UX.prototype),sV(UX.prototype,"updateEncoderConfig",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"updateEncoderConfig"),UX.prototype),sV(UX.prototype,"updateSendParameters",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"updateSendParameters"),UX.prototype),sV(UX.prototype,"replaceTrack",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"replaceTrack"),UX.prototype),sV(UX.prototype,"getRemoteSSRC",[BX],Object.getOwnPropertyDescriptor(UX.prototype,"getRemoteSSRC"),UX.prototype),UX);function BX(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 DataChannelConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function jX(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 GX extends rO{get url(){return this._url?this._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(nx.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(nx.CONNECTED):"closed"===this._state?this.emit(nx.CLOSED):"failed"===this._state&&this.emit(nx.FAILED))}constructor(e,t,i,n){super(),bI(this,"connectionID",0),bI(this,"currentURLIndex",0),bI(this,"reconnectReason",void 0),bI(this,"_reconnectMode","tryNext"),bI(this,"_initMutex",void 0),bI(this,"_name",void 0),bI(this,"_state","closed"),bI(this,"_reconnectInterrupter",void 0),bI(this,"_url",void 0),bI(this,"_retryConfig",void 0),bI(this,"_reconnectCount",0),bI(this,"_forceCloseTimeout",5e3),bI(this,"_onlineReconnectListener",void 0),bI(this,"_closeEstablishingTransmitter",(()=>{})),bI(this,"_store",void 0),bI(this,"_joinChannelServiceRecordIndex",void 0),bI(this,"_transmitter",void 0),bI(this,"_useCompress",void 0),bI(this,"_inflateLength",0),bI(this,"_deflateLength",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?jX(Object(i),!0).forEach((function(t){bI(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):jX(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this._useCompress=i}resetReconnectCount(e){ND.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void ND.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),ND.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let WX=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class HX{constructor(e,t,i){bI(this,"version",1),bI(this,"initialRTO",void 0),bI(this,"maxBatchAckCount",void 0),bI(this,"maxRTO",void 0),bI(this,"initialRTT",void 0),bI(this,"ID",void 0),bI(this,"rtt",void 0),bI(this,"packetNumber",1),bI(this,"rtoRatioMap",new Map),bI(this,"timeoutMap",new Map),bI(this,"unorderedPacketQueue",[]),bI(this,"batchAckPacketQueue",[]),bI(this,"lastOrderedPacketNumber",0),bI(this,"batchAckTimer",void 0),bI(this,"sendImpl",void 0),bI(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=YO(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:JN("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:JN("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:JN("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:JN("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:JN("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:WX.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case WX.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),Qw(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i}case WX.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),Qw(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case WX.Default:{const r=t.getUint32(3),o=Jw(t,7),s=e.slice(15),a=new Uint8Array(s);return{version:i,type:n,packetNumber:r,sendTs:Number(o),payload:a}}case WX.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=Jw(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw ND.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n))}}sendMessage(e){JN("DC_DEBUG_LOG")&&"string"==typeof e&&ND.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(e));const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout((()=>{this.resendMessage(t)}),i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===WX.Default?this.ack(t):t.type===WX.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let[t,i]=e;window.clearTimeout(i)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout((()=>{JN("DC_DEBUG_LOG")&&"string"==typeof e.payload&&ND.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:WX.Ack,version:this.version};JN("DC_DEBUG_LOG")&&ND.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:WX.Ack,version:this.version};JN("DC_DEBUG_LOG")&&ND.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:WX.Ack,version:this.version};JN("DC_DEBUG_LOG")&&ND.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===WX.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class KX extends GX{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),bI(this,"_initMutex",void 0),bI(this,"_reconnectInterrupter",void 0),bI(this,"_url",void 0),bI(this,"_transmitter",void 0),bI(this,"_addresses",void 0),bI(this,"_reliableTransmission",void 0),bI(this,"_textEncoder",void 0),bI(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new sN("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),o=Math.max(1.2,Math.floor(8*n)/10);gO.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),IO.on(TO.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gO.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||JN("FINGERPRINT")));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(nx.CLOSED,(()=>i(new FD(Bw.WS_DISCONNECT)))),this.once(nx.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new Wh(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new FD(Bw.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const i=this._textEncoder.encode(e),n=jz(i,{raw:!0});this._reliableTransmission.sendMessage(n)}catch(e){throw new FD(Bw.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new Wh(((t,i)=>{var n;const r=()=>{ND.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),ND.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const n=vO(this,nx.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void ND.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new FD(Bw.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new FD(Bw.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},s=async e=>{try{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),ND.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();RO(this,nx.TO_CONNECT_DATACHANNEL).then((e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;ND.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new HX((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{if("string"==typeof e)this.emit(nx.ON_MESSAGE,e);else{const t=Wz(e,{raw:!0}).buffer,i=this._textDecoder.decode(t);this.emit(nx.ON_MESSAGE,i)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),n.onclose=o,n.onmessage=s,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof FD&&e.code===Bw.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof FD&&e.code===Bw.WS_ERR){const t=new FD(Bw.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return ND.error("[".concat(this._name,"]").concat(t)),void i(t)}o&&o(e)}else i(new FD(Bw.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||IO.networkState!==gO.OFFLINE||(this._onlineReconnectListener=IO.onlineWaiter&&IO.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=dN(this._reconnectCount,this._retryConfig);ND.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await Wh.race([KO(t),this._onlineReconnectListener||new Wh((()=>{}))])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(nx.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];await n(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||JN("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return ND.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);ND.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];await n(t,e)}else"recover"===e&&(ND.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(nx.FAILBACK));return!0}catch(i){var r,o;return ND.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&Dn(o=i.data.desc).call(o,"dynamic key expired")?(this.emit(nx.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class YX extends rO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===hV.CONNECTED?this.emit(pV.WS_CONNECTED):e===hV.RECONNECTING?this.emit(pV.WS_RECONNECTING,this._websocketReconnectReason):e===hV.CLOSED&&this.emit(pV.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()}processPendingNotifications(){0!==this.pendingNotifications.length&&(ND.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let{type:t,message:i}=e;this.emit(t,i),t===mV.ON_NOTIFICATION&&this.handleNotification(i),t===mV.ON_USER_BANNED&&this.handleUserBanned(i)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(uO.UID_BANNED);break;case 15:this.close(uO.IP_BANNED);break;case 16:this.close(uO.CHANNEL_BANNED)}}constructor(e,t){super(),bI(this,"__name__","DataChannelSignal"),bI(this,"_disconnectedReason",void 0),bI(this,"_websocketReconnectReason",void 0),bI(this,"_connectionState",hV.CLOSED),bI(this,"reconnectToken",void 0),bI(this,"websocket",void 0),bI(this,"openConnectionTime",void 0),bI(this,"clientId",void 0),bI(this,"lastMsgTime",Date.now()),bI(this,"uploadCache",[]),bI(this,"uploadCacheInterval",void 0),bI(this,"rttRolling",new hN(5)),bI(this,"pingpongTimer",void 0),bI(this,"inflateDataTimer",void 0),bI(this,"pingpongTimeoutCount",0),bI(this,"ortc",void 0),bI(this,"joinResponse",void 0),bI(this,"multiIpOption",void 0),bI(this,"initError",void 0),bI(this,"spec",void 0),bI(this,"store",void 0),bI(this,"isJoining",!1),bI(this,"pendingNotifications",[]),bI(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(pV.ON_BINARY_DATA,e);const t=JSON.parse(e);if(JN("DC_DEBUG_LOG")&&ND.debug("[datachannel-signal] received packet",t),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else Object.prototype.hasOwnProperty.call(t,"_type")&&(this.isJoining?t._type===mV.ON_NOTIFICATION||t._type===mV.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===mV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===mV.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),ND.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===mV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===mV.ON_USER_BANNED&&this.handleUserBanned(t._message)))})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new KX("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===hV.CONNECTED&&this.reconnect("retry",ix.OFFLINE)}))}async request(e,t,i,n){const r=YO(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((t,i)=>{if(this.connectionState===hV.CONNECTED)return t();const n=()=>{this.off(pV.WS_CLOSED,r),t()},r=()=>{this.off(pV.WS_CONNECTED,n),i(new FD(Bw.WS_ABORT))};this.once(pV.WS_CONNECTED,n),this.once(pV.WS_CLOSED,r),e!==_V.PUBLISH&&e!==_V.SUBSCRIBE&&e!==_V.UNSUBSCRIBE&&e!==_V.UNPUBLISH&&e!==_V.CONTROL&&e!==_V.RESTART_ICE||this.once(pV.DISCONNECT_P2P,(()=>{i(new FD(Bw.DISCONNECT_P2P))})),e!==_V.PUBLISH&&e!==_V.RESTART_ICE||this.once(pV.ABORT_P2P_EXECUTION,(()=>{i(new FD(Bw.DISCONNECT_P2P))}))}));if(this.connectionState!==hV.CONNECTING&&this.connectionState!==hV.RECONNECTING||e===_V.JOIN||e===_V.REJOIN||await a(),e===_V.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),JN("DC_DEBUG_LOG")&&ND.debug("[datachannel-signal] sendMessage",o),await this.websocket.sendMessage(o,!0,!1),n)return;const c=new Wh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.emit(pV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new FD(Bw.WS_ABORT,"type: ".concat(e))),this.off(pV.WS_CLOSED,c),this.off(pV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(pV.WS_CLOSED,c),this.once(pV.WS_RECONNECTING,c),KO(JN("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(ND.warning("dc request timeout, type: ".concat(e)),this.emit(pV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===hV.CLOSED||e===_V.LEAVE)throw new FD(Bw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===_V.JOIN||e===_V.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=Ex(l),h=new FD(Bw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(ND.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===uV.ERR_TOO_MANY_BROADCASTERS?e===_V.JOIN||e===_V.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===uV.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,ND.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",ix.MULTI_IP)):this.reconnect(u.action,ix.SERVER_ERROR),e===_V.JOIN||e===_V.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((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 ND.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(EV.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=JN("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!==hV.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)}),JN("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const i={_type:e,_message:t};await this.websocket.sendMessage(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 Wh(((t,i)=>{this.once(pV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(pV.WS_CLOSED,(()=>i(this.initError||new FD(Bw.WS_ABORT)))),this.connectionState=hV.CONNECTING,this.websocket.init(e).catch(i),this.websocket.once(nx.FAILBACK,(()=>{i(new FD(Bw.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(ND.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),i(new FD(Bw.INIT_DATACHANNEL_TIMEOUT)))}),JN("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=e||uO.LEAVE,this.connectionState=hV.CLOSED,ND.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===uO.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new KX("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),JN("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(pV.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await RO(this,pV.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];const t=await this.request(_V.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(pV.REPORT_JOIN_GATEWAY,Bw.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(pV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=hV.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new FD(Bw.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=yO(this,pV.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(_V.REJOIN,e);return!!t&&(this.connectionState=hV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),JN("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(mV.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(mV.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(mV.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(mV.MUTE_AUDIO,{uid:e.uid}):this.emit(mV.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(mV.MUTE_VIDEO,{uid:e.uid}):this.emit(mV.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(mV.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(mV.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(mV.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(mV.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(mV.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)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(_V.DOWNGRADE_CODEC,t)}handleNotification(e){ND.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Ex(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(uO.UID_BANNED),void this.close()):void this.reconnect(t.action,ix.SERVER_ERROR);ND.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,JN("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const e=JN("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(ND.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>JN("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",ix.FALLBACK):this.request(_V.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),JN("REPORT_STATS")&&this.send(_V.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(EV.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(nx.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(pV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(nx.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(nx.CLOSED,(()=>{this.connectionState=hV.CLOSED})),this.websocket.on(nx.FAILED,(()=>{this._disconnectedReason=uO.NETWORK_ERROR,this.connectionState=hV.CLOSED})),this.websocket.on(nx.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===hV.CONNECTED?this.connectionState=hV.RECONNECTING:this.connectionState=hV.CONNECTING})),this.websocket.on(nx.WILL_RECONNECT,((e,t)=>{if(yO(this,pV.IS_P2P_DISCONNECTED)&&"retry"===e)return ND.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(pV.NEED_RENEW_SESSION),this.emit(pV.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(ND.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(pV.NEED_RENEW_SESSION),this.emit(pV.DISCONNECT_P2P)),t(e)})),this.websocket.on(nx.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{ND.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",ix.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(pV.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof FD&&e.code===Bw.UNEXPECTED_RESPONSE&&e.data.code===uV.ERR_NO_AUTHORIZED)return ND.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",ix.SERVER_ERROR);ND.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",ix.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(nx.REQUEST_NEW_URLS,((e,t)=>{RO(this,pV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(nx.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(mV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(nx.TO_CONNECT_DATACHANNEL,((e,t)=>{RO(this,pV.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(nx.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(pV.DATACHANNEL_FAILBACK)}))}}const zX={name:"DataChannelConnection",create:function(e){let{store:t,spec:i}=e;return new FX(i,t)}};const qX={name:"DataChannelSignal",create:function(e){let{store:t,spec:i}=e;return new YX(i,t)}};FN(),XN("PROCESS_ID","process-".concat(YO(8,""),"-").concat(YO(4,""),"-").concat(YO(4,""),"-").concat(YO(4,""),"-").concat(YO(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void ND.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();ND.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(qN,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;ZN[e]=n,qN[e]=n}}))}catch(t){ND.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(ZN.AREAS)&&ZN.AREAS.length>0&&ZF(ZN.AREAS,!0);const XX=(e,t,i)=>{ND.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),XN(e,t,i)};LF(Xz,!1),LF(iq,!1),LF(aW,!1),LF(Lq,!1),LF(Yz,!1),LF(gX,!1),LF(wX,!1),LF(NX,!1),LF(zX,!1),LF(qX,!1);const JX=function(e){const t=new rO,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===rx.SECURITY_POLICY_VIOLATION&&lH(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 cH(cH({},i),n)}({__TRACK_LIST__:dP,VERSION:BN,BUILD:YN,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:XX,getParameter:JN,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return jD().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 FD(Bw.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];const t=xD.reportApiInvoke(null,{name:aO.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:cO.TRACER}),i=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const i=window.RTCPeerConnection,n=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,r=window.WebSocket;t=!(!i||!r),e&&!n&&(t=!1),t&&Mw()&&fw(75)&&(new i).close()}catch(e){ND.error("check system requirement failed: ",e),t=!1}return t}(e),n=tH();ND.debug("checkSystemRequirements, api:",i,"browser",n);const r=i&&n;return t.onSuccess(r),JN("IGNORE_RTC_DEVICE_CHECK")?i:r},getDevices:function(e){return aL.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return aL.getRecordingDevices(e)},getCameras:function(e){return aL.getCamerasDevices(e)},getElectronScreenSources:$P,getPlaybackDevices:function(e){return aL.getSpeakers(e)},createClient:eH,createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=JN("CAMERA_CAPTURE_CONFIG"),i=YO(8,"track-cam-"),n=xD.reportApiInvoke(null,{id:i,tag:cO.TRACER,name:aO.CREATE_CAM_VIDEO_TRACK,options:[MP({},e),t]});t&&(e.encoderConfig=t);const r=CL(e);let o=null;ND.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await nL({video:r},i)).getVideoTracks()[0]||null}catch(e){throw n.onError(e),e}if(!o){const e=new jw(Bw.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(ND)}if(e.optimizationMode&&hM(i,o,e,rP(e.encoderConfig)),JN("USE_STANDARD_BITRATE_DEFAULT")){const t=rP(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const s=new lM(o,e,r,e.scalabiltyMode?sP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return n.onSuccess(s.getTrackId()),ND.info("create camera video success, trackId:",i),s},createCustomVideoTrack:function(e){const t=YO(8,"track-cus-"),i=xD.reportApiInvoke(null,{id:t,tag:cO.TRACER,name:aO.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});JN("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const n=new dM(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?sP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[hP.CUSTOM_TRACK]);return i.onSuccess(n.getTrackId()),ND.info("create custom video track success with config",e,"trackId",n.getTrackId()),n},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="object"==typeof t?function(e){const t=vL(e);return qD()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),XD()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;i&&(t="auto");const n=YO(8,"track-scr-v-"),r=xD.reportApiInvoke(null,{id:n,tag:cO.TRACER,name:aO.CREATE_SCREEN_VIDEO_TRACK,options:[MP({},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 o=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&uw()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:o,preferCurrentTab:s,windowAudio:a,monitorTypeSurfaces:c}=e;(mw(107)||gw(107)||Iw(93))&&(i&&(Ww(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(Ww(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(Ww(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(mw(105)||gw(105)||Iw(91))&&o&&(Ww(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(mw(94)||gw(94)||Iw(80))&&s&&(t.preferCurrentTab=!0),(mw(141)||gw(141)||Iw(125))&&a&&(Ww(a,"windowAudio",["exclude","system"]),t.windowAudio=a),(mw(119)||gw(119)||Iw(105))&&c&&(Ww(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const d=e.encoderConfig?oP(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:d?d.width:void 0,maxHeight:d?d.height:void 0},d&&(d.frameRate&&("number"==typeof d.frameRate?(t.mandatory.maxFrameRate=d.frameRate,t.mandatory.minFrameRate=d.frameRate):(t.mandatory.maxFrameRate=d.frameRate.max||d.frameRate.ideal||d.frameRate.exact||void 0,t.mandatory.minFrameRate=d.frameRate.min||d.frameRate.ideal||d.frameRate.exact||void 0),t.frameRate=d.frameRate),d.width&&(t.width=d.width),d.height&&(t.height=d.height)),t}(e);let s=null,a=null;const c=jD();if(!c.supportShareAudio&&"enable"===t){const e=new jw(Bw.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(ND)}ND.info("start create screen video track with config",e,"withAudio",t,"trackId",n);const d=c.supportShareAudio&&"disable"!==t;try{const e=await nL({screen:o,screenAudio:d?i||!0:void 0},n);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!s){const e=new jw(Bw.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(ND)}if(!a&&"enable"===t){s&&s.stop();const e=new jw(Bw.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(ND)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(hM(n,s,e,e.encoderConfig&&oP(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new dM(s,e.encoderConfig?oP(e.encoderConfig):{},e.scalabiltyMode?sP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n,[hP.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),ND.info("create screen video track success","video:",l.getTrackId()),l;const u=new Ek(a,void 0,YO(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),ND.info("create screen video track success","video:",l.getTrackId(),"audio:",u.getTrackId()),[l,u]},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=JN("CAMERA_CAPTURE_CONFIG"),n=YO(8,"track-mic-"),r=YO(8,"track-cam-"),o=xD.reportApiInvoke(null,{id:"".concat(n,"-").concat(r),tag:cO.TRACER,name:aO.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const s=CL(t),a=yL(e);let c=null,d=null;ND.info("start create camera video track(".concat(r,") and microphone audio track(").concat(n,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await nL({audio:a,video:s},"".concat(n,"-").concat(r));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new jw(Bw.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(ND)}if(t.optimizationMode&&hM(r,d,t,rP(t.encoderConfig)),JN("USE_STANDARD_BITRATE_DEFAULT")){const e=rP(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const l=new mk(c,e,a,n),u=new lM(d,t,s,t.scalabiltyMode?sP(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),ND.info("create camera video track(".concat(r,") and microphone audio track(").concat(n,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=YO(8,"track-mic-"),i=xD.reportApiInvoke(null,{id:t,tag:cO.TRACER,name:aO.CREATE_MIC_AUDIO_TRACK,options:[e]}),n=yL(e);let r=null;ND.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await nL({audio:n},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!r){const e=new jw(Bw.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(ND)}const o=new mk(r,e,n,t);return i.onSuccess(o.getTrackId()),ND.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:uM,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=YO(8,"track-buf-"),a=xD.reportApiInvoke(null,{id:s,tag:cO.TRACER,name:aO.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(JN("DISABLE_WEBAUDIO"))throw new jw(Bw.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");ND.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(e,t){let i=null;if("string"==typeof e){const t=Tk.get(e);if(t)return ND.debug("use cached audio resource: ",e),t;try{i=(await lN((()=>Xb.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new jw(Bw.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Wh(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new jw(Bw.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new jw(Bw.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=HP();return new Wh(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new jw(Bw.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&Tk.set(e,n),n}(r,i)}catch(e){return a.onError(e),e.throw(ND)}const d=new gk(r),l=new fk(c,d,n?cP(n):{},s);return ND.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(ND.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw ND.debug("Invalid appType"),new FD(Bw.INVALID_PARAMS,"invalid app type",e);XN("APP_TYPE",Math.floor(e))}
vendor: 6,655 bytes, line 6
6,setLogLevel:function(e){ND.setLogLevel(e)},enableLogUpload:function(){JN("USE_NEW_LOG")?XN("UPLOAD_LOG",!0):ND.enableLogUpload()},disableLogUpload:function(){JN("USE_NEW_LOG")?XN("UPLOAD_LOG",!1):ND.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new kB},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=xD.reportApiInvoke(null,{tag:cO.TRACER,name:aO.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Ek||e instanceof wM)){const e=new FD(Bw.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof Ek?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new Wh((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d<s?d:s;const l=o-s>1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:n,maxVolumeLevel:o,result:t};ND.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=xD.reportApiInvoke(null,{tag:cO.TRACER,name:aO.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof dM||e instanceof bM)){const e=new FD(Bw.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof dM?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,(hw()||lw())&&(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 Wh(((a,c)=>{function d(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new FD(Bw.UNEXPECTED_ERROR,"can not get canvas 2d context.");return ND.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<l;e+=3)if(d.data[e]!==s[e])return o+=1,void(s=d.data);s=d.data}else s=d.data}setTimeout((()=>{r&&(r(),a(o))}),t),r=zP((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw i.onError(e),e}tG===iw.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return ND.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:ZF,audioElementPlayCenter:pL,resumeAudioContext:function(){return pL.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){sH.processExternalMediaAEC(e)},registerExtensions:function(e){const t=JN("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=ND.extLog,i.reporter.hookApiInvoke=xD.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach((e=>{i.parameters[e]=JN(e)}))})),XX("PLUGIN_INFO",t)},ChannelMediaRelayError:LV,ChannelMediaRelayEvent:DV,ChannelMediaRelayState:PV,RemoteStreamFallbackType:EP,RemoteStreamType:_P,ConnectionDisconnectedReason:uO,AudienceLatencyLevelType:lO,AREAS:xV,preload:async function(e,t,i,n){return fG(e,t,i,n)},startLastmileProbeTest:async function(e,t,i,n){let r={state:"unavailable"};await fG(e,t,i,n);const o=await SG({appId:e,cname:t,token:i||e,uid:n,cloudProxyServer:"disabled"});if(!o)return r;await TG(o);let s,a=eH({mode:"rtc",codec:"vp8"});try{s=await a.join(e,t,i,n,{networkQualityProbe:!0})}catch(e){return r}const c=new mG,d=c.createMuteAudioTrack();let l=await uM({mediaStreamTrack:d});await a.publish([l]);let[u,h,p]=await new Wh(((e,t)=>{const i=setTimeout((()=>{clearTimeout(i),e([!0,null,"audio"])}),5e3);a.on("user-published",(async(t,n)=>{t.uid===s&&(clearTimeout(i),e([!1,t,n]))}))}));if(u||!h)return await a.unpublish([l]),await a.leave(),l.close(),c.close(),r;await a.subscribe(h,p),await new Wh(((e,t)=>{const i=setTimeout((()=>{clearTimeout(i),e(null)}),5e3)}));let _=a.getRTCStats(),E=a.getLocalAudioStats();const m=_.RTT,f=E.sendJitterMs,S=E.currentPacketLossRate;return r={state:"complete",rtt:m,packetLossRate:S,jitter:f,networkQuality:((e,t,i)=>{let n=1;if(i>0){let e=Math.log(100*i)/Math.log(2)+1;e=Math.min(5,Math.max(0,e)),n=1-e/5}let r=1;if(e>0){let t=Math.log(e/40)/Math.log(2)+1;t=Math.min(5,Math.max(0,t)),r=1-t/5}let o=1;if(t>0){let e=Math.log(t/10)/Math.log(2.5)+1;e=Math.min(5,Math.max(0,e)),o=1-e/5}const s=.5*n+.3*r+.2*o;let a=0;return a=s>=.8?1:s>=.6?2:s>=.4?3:s>=.2?4:5,a})(m,f,S)},await a.unsubscribe(h),await a.unpublish([l]),await a.leave(),l.close(),c.close(),await TG(o),r}});return Object.defineProperties(JX,{onAudioAutoplayFailed:{get:()=>dL.onAudioAutoplayFailed,set:e=>{dL.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>dL.onAutoplayFailed,set:e=>{dL.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>JX._onSecurityPolicyViolation,set(e){JX._onSecurityPolicyViolation=e,lH(e)}},__CLIENT_LIST__:{get:()=>JN("SHOW_GLOBAL_CLIENT_LIST")?TU:[]}}),aL.on(OP.CAMERA_DEVICE_CHANGED,(e=>{ND.info("camera device changed",JSON.stringify(e)),JX.onCameraChanged&&JX.onCameraChanged(e),JX.safeEmit(rx.CAMERA_CHANGED,e)})),aL.on(OP.RECORDING_DEVICE_CHANGED,(e=>{ND.info("microphone device changed",JSON.stringify(e)),JX.onMicrophoneChanged&&JX.onMicrophoneChanged(e),JX.safeEmit(rx.MICROPHONE_CHANGED,e)})),aL.on(OP.PLAYOUT_DEVICE_CHANGED,(e=>{ND.debug("playout device changed",JSON.stringify(e)),JX.onPlaybackDeviceChanged&&JX.onPlaybackDeviceChanged(e),JX.safeEmit(rx.PLAYBACK_DEVICE_CHANGED,e)})),pL.onAutoplayFailed=()=>{ND.info("detect audio element autoplay failed"),dL.onAudioAutoplayFailed&&dL.onAudioAutoplayFailed()},WP.on("autoplay-failed",(()=>{ND.info("detect webaudio autoplay failed"),dL.onAudioAutoplayFailed&&dL.onAudioAutoplayFailed(),JX.safeEmit(rx.AUTOPLAY_FAILED)})),WP.on(JD.STATE_CHANGE,((e,t)=>{ND.info("audio context state changed: ".concat(t," => ").concat(e)),JX.onAudioContextStateChanged&&JX.onAudioContextStateChanged(e,t),JX.safeEmit(rx.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),IO.on(TO.NETWORK_STATE_CHANGE,((e,t)=>{ND.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=JX),JX}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.