/**
 * AgoraWebSDK_N-v4.24.3-0-g6cc16b0bb-dirty Copyright AgoraInc.
 */

function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i=function(e){try{return!!e()}catch(e){return!0}},r=!i((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)}),g=d,S=g({}.toString),T=g("".slice),R=function(e){return T(S(e),8,-1)},v=R,y=d,C=function(e){if("Function"===v(e))return y(e)},b="object"==typeof document&&document.all,I={all:b,IS_HTMLDDA:void 0===b&&void 0!==b},A=I.all,w=I.IS_HTMLDDA?function(e){return"function"==typeof e||e===A}:function(e){return"function"==typeof e},O={},N=!i((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}},G=i,j=R,W=Object,K=d("".split),Y=G((function(){return!W("z").propertyIsEnumerable(0)}))?function(e){return"String"==j(e)?K(e,""):W(e)}:W,H=function(e){return null==e},X=H,J=TypeError,z=function(e){if(X(e))throw J("Can't call method on "+e);return e},Z=Y,q=z,Q=function(e){return Z(q(e))},$=w,ee=I.all,te=I.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:$(e)||e===ee}:function(e){return"object"==typeof e?null!==e:$(e)},ne={},ie=ne,re=h,oe=w,se=function(e){return oe(e)?e:void 0},ae=function(e,t){return arguments.length<2?se(ie[e])||se(re[e]):ie[e]&&ie[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=i,ge=h.String,Se=!!Object.getOwnPropertySymbols&&!fe((function(){var e=Symbol();return!ge(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41})),Te=Se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,ve=w,ye=l,Ce=Object,be=Te?function(e){return"symbol"==typeof e}:function(e){var t=Re("Symbol");return ve(t)&&ye(t.prototype,Ce(e))},Ie=String,Ae=function(e){try{return Ie(e)}catch(e){return"Object"}},we=w,Oe=Ae,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+" is not a function")},Pe=De,Le=H,ke=function(e,t){var n=e[t];return Le(n)?void 0:Pe(n)},Me=L,Ue=w,Ve=te,xe=TypeError,Fe={exports:{}},Be=h,Ge=Object.defineProperty,je=function(e,t){try{Ge(Be,e,{value:t,configurable:!0,writable:!0})}catch(n){Be[e]=t}return t},We="__core-js_shared__",Ke=h[We]||je(We,{}),Ye=Ke;(Fe.exports=function(e,t){return Ye[e]||(Ye[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 He=Fe.exports,Xe=z,Je=Object,ze=function(e){return Je(Xe(e))},Ze=ze,qe=d({}.hasOwnProperty),Qe=Object.hasOwn||function(e,t){return qe(Ze(e),t)},$e=d,et=0,tt=Math.random(),nt=$e(1..toString),it=function(e){return"Symbol("+(void 0===e?"":e)+")_"+nt(++et+tt,36)},rt=He,ot=Qe,st=it,at=Se,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=be,mt=ke,ft=function(e,t){var n,i;if("string"===t&&Ue(n=e.toString)&&!Ve(i=Me(n,e)))return i;if(Ue(n=e.valueOf)&&!Ve(i=Me(n,e)))return i;if("string"!==t&&Ue(n=e.toString)&&!Ve(i=Me(n,e)))return i;throw xe("Can't convert object to primitive value")},gt=TypeError,St=ht("toPrimitive"),Tt=function(e,t){if(!_t(e)||Et(e))return e;var n,i=mt(e,St);if(i){if(void 0===t&&(t="default"),n=pt(i,e,t),!_t(n)||Et(n))return n;throw gt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ft(e,t)},Rt=be,vt=function(e){var t=Tt(e,"string");return Rt(t)?t:t+""},yt=te,Ct=h.document,bt=yt(Ct)&&yt(Ct.createElement),It=function(e){return bt?Ct.createElement(e):{}},At=It,wt=!N&&!i((function(){return 7!=Object.defineProperty(At("div"),"a",{get:function(){return 7}}).a})),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Q,kt=vt,Mt=Qe,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=i,Ft=w,Bt=/#|\.prototype\./,Gt=function(e,t){var n=Wt[jt(e)];return n==Yt||n!=Kt&&(Ft(t)?xt(t):!!t)},jt=Gt.normalize=function(e){return String(e).replace(Bt,".").toLowerCase()},Wt=Gt.data={},Kt=Gt.NATIVE="N",Yt=Gt.POLYFILL="P",Ht=Gt,Xt=De,Jt=r,zt=C(C.bind),Zt=function(e,t){return Xt(e),void 0===t?e:Jt?zt(e,t):function(){return e.apply(t,arguments)}},qt={},Qt=N&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),$t=te,en=String,tn=TypeError,nn=function(e){if($t(e))return e;throw tn(en(e)+" is not an object")},rn=N,on=wt,sn=Qt,an=nn,cn=vt,dn=TypeError,ln=Object.defineProperty,un=Object.getOwnPropertyDescriptor,hn="enumerable",pn="configurable",_n="writable";qt.f=rn?sn?function(e,t,n){if(an(e),t=cn(t),an(n),"function"==typeof e&&"prototype"===t&&"value"in n&&_n in n&&!n[_n]){var i=un(e,t);i&&i[_n]&&(e[t]=n.value,n={configurable:pn in n?n[pn]:i[pn],enumerable:hn in n?n[hn]:i[hn],writable:!1})}return ln(e,t,n)}:ln:function(e,t,n){if(an(e),t=cn(t),an(n),on)try{return ln(e,t,n)}catch(e){}if("get"in n||"set"in n)throw dn("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var En=qt,mn=B,fn=N?function(e,t,n){return En.f(e,t,mn(1,n))}:function(e,t,n){return e[t]=n,e},gn=h,Sn=f,Tn=C,Rn=w,vn=O.f,yn=Ht,Cn=ne,bn=Zt,In=fn,An=Qe,wn=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return Sn(e,this,arguments)};return t.prototype=e.prototype,t},On=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?gn:p?gn[u]:(gn[u]||{}).prototype,m=h?Cn:Cn[u]||In(Cn,u,{})[u],f=m.prototype;for(o in t)i=!(n=yn(h?o:u+(p?".":"#")+o,e.forced))&&E&&An(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=vn(E,o))&&l.value:E[o]),s=i&&c?c:t[o],i&&typeof a==typeof s||(d=e.bind&&i?bn(s,gn):e.wrap&&i?wn(s):_&&Rn(s)?Tn(s):s,(e.sham||s&&s.sham||a&&a.sham)&&In(d,"sham",!0),In(m,o,d),_&&(An(Cn,r=u+"Prototype")||In(Cn,r,{}),In(Cn[r],o,s),e.real&&f&&(n||!f[o])&&In(f,o,s)))},Nn=Math.ceil,Dn=Math.floor,Pn=Math.trunc||function(e){var t=+e;return(t>0?Dn:Nn)(t)},Ln=Pn,kn=function(e){var t=+e;return t!=t||0===t?0:Ln(t)},Mn=kn,Un=Math.max,Vn=Math.min,xn=function(e,t){var n=Mn(e);return n<0?Un(n+t,0):Vn(n,t)},Fn=kn,Bn=Math.min,Gn=function(e){return e>0?Bn(Fn(e),9007199254740991):0},jn=Gn,Wn=function(e){return jn(e.length)},Kn=Q,Yn=xn,Hn=Wn,Xn=function(e){return function(t,n,i){var r,o=Kn(t),s=Hn(o),a=Yn(i,s);if(e&&n!=n){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===n)return e||a||0;return!e&&-1}},Jn={includes:Xn(!0),indexOf:Xn(!1)},zn=Jn.includes;On({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return zn(this,e,arguments.length>1?arguments[1]:void 0)}});var Zn=ne,qn=function(e){return Zn[e+"Prototype"]},Qn=qn("Array").includes,$n=te,ei=R,ti=ht("match"),ni=function(e){var t;return $n(e)&&(void 0!==(t=e[ti])?!!t:"RegExp"==ei(e))},ii=ni,ri=TypeError,oi={};oi[ht("toStringTag")]="z";var si="[object z]"===String(oi),ai=si,ci=w,di=R,li=ht("toStringTag"),ui=Object,hi="Arguments"==di(function(){return arguments}()),pi=ai?di:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=ui(e),li))?n:hi?di(t):"Object"==(i=di(t))&&ci(t.callee)?"Arguments":i},_i=pi,Ei=String,mi=function(e){if("Symbol"===_i(e))throw TypeError("Cannot convert a Symbol value to a string");return Ei(e)},fi=ht("match"),gi=On,Si=function(e){if(ii(e))throw ri("The method doesn't accept regular expressions");return e},Ti=z,Ri=mi,vi=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[fi]=!1,"/./"[e](t)}catch(e){}}return!1},yi=d("".indexOf);gi({target:"String",proto:!0,forced:!vi("includes")},{includes:function(e){return!!~yi(Ri(Ti(this)),Ri(Si(e)),arguments.length>1?arguments[1]:void 0)}});var Ci=qn("String").includes,bi=l,Ii=Qn,Ai=Ci,wi=Array.prototype,Oi=String.prototype,Ni=function(e){var t=e.includes;return e===wi||bi(wi,e)&&t===wi.includes?Ii:"string"==typeof e||e===Oi||bi(Oi,e)&&t===Oi.includes?Ai:t},Di=n(Ni),Pi=De,Li=ze,ki=Y,Mi=Wn,Ui=TypeError,Vi=function(e){return function(t,n,i,r){Pi(n);var o=Li(t),s=ki(o),a=Mi(o),c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw Ui("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},xi={left:Vi(!1),right:Vi(!0)},Fi=i,Bi=function(e,t){var n=[][e];return!!n&&Fi((function(){n.call(null,t||function(){return 1},1)}))},Gi="undefined"!=typeof process&&"process"==R(process),ji=xi.left;On({target:"Array",proto:!0,forced:!Gi&&Ee>79&&Ee<83||!Bi("reduce")},{reduce:function(e){var t=arguments.length;return ji(this,e,t,t>1?arguments[1]:void 0)}});var Wi=qn("Array").reduce,Ki=l,Yi=Wi,Hi=Array.prototype,Xi=function(e){var t=e.reduce;return e===Hi||Ki(Hi,e)&&t===Hi.reduce?Yi:t},Ji=Xi,zi=n(Ji),Zi=R,qi=Array.isArray||function(e){return"Array"==Zi(e)},Qi=On,$i=qi,er=d([].reverse),tr=[1,2];Qi({target:"Array",proto:!0,forced:String(tr)===String(tr.reverse())},{reverse:function(){return $i(this)&&(this.length=this.length),er(this)}});var nr=qn("Array").reverse,ir=l,rr=nr,or=Array.prototype,sr=function(e){var t=e.reverse;return e===or||ir(or,e)&&t===or.reverse?rr:t},ar=sr,cr=n(ar),dr=it,lr=He("keys"),ur=function(e){return lr[e]||(lr[e]=dr(e))},hr=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),pr=Qe,_r=w,Er=ze,mr=hr,fr=ur("IE_PROTO"),gr=Object,Sr=gr.prototype,Tr=mr?gr.getPrototypeOf:function(e){var t=Er(e);if(pr(t,fr))return t[fr];var n=t.constructor;return _r(n)&&t instanceof n?n.prototype:t instanceof gr?Sr:null},Rr=d,vr=De,yr=w,Cr=String,br=TypeError,Ir=function(e,t,n){try{return Rr(vr(Object.getOwnPropertyDescriptor(e,t)[n]))}catch(e){}},Ar=nn,wr=function(e){if("object"==typeof e||yr(e))return e;throw br("Can't set "+Cr(e)+" as a prototype")},Or=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Ir(Object.prototype,"__proto__","set"))(n,[]),t=n instanceof Array}catch(e){}return function(n,i){return Ar(n),wr(i),t?e(n,i):n.__proto__=i,n}}():void 0),Nr={},Dr={},Pr=Qe,Lr=Q,kr=Jn.indexOf,Mr=Dr,Ur=d([].push),Vr=function(e,t){var n,i=Lr(e),r=0,o=[];for(n in i)!Pr(Mr,n)&&Pr(i,n)&&Ur(o,n);for(;t.length>r;)Pr(i,n=t[r++])&&(~kr(o,n)||Ur(o,n));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 Gr={};Gr.f=Object.getOwnPropertySymbols;var jr=ae,Wr=Nr,Kr=Gr,Yr=nn,Hr=d([].concat),Xr=jr("Reflect","ownKeys")||function(e){var t=Wr.f(Yr(e)),n=Kr.f;return n?Hr(t,n(e)):t},Jr=Qe,zr=Xr,Zr=O,qr=qt,Qr={},$r=Vr,eo=xr,to=Object.keys||function(e){return $r(e,eo)},no=N,io=Qt,ro=qt,oo=nn,so=Q,ao=to;Qr.f=no&&!io?Object.defineProperties:function(e,t){oo(e);for(var n,i=so(t),r=ao(t),o=r.length,s=0;o>s;)ro.f(e,n=r[s++],i[n]);return e};var co,lo=ae("document","documentElement"),uo=nn,ho=Qr,po=xr,_o=Dr,Eo=lo,mo=It,fo="prototype",go="script",So=ur("IE_PROTO"),To=function(){},Ro=function(e){return"<"+go+">"+e+"</"+go+">"},vo=function(e){e.write(Ro("")),e.close();var t=e.parentWindow.Object;return e=null,t},yo=function(){try{co=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;yo="undefined"!=typeof document?document.domain&&co?vo(co):(t=mo("iframe"),n="java"+go+":",t.style.display="none",Eo.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(Ro("document.F=Object")),e.close(),e.F):vo(co);for(var i=po.length;i--;)delete yo[fo][po[i]];return yo()};_o[So]=!0;var Co=Object.create||function(e,t){var n;return null!==e?(To[fo]=uo(e),n=new To,To[fo]=null,n[So]=e):n=yo(),void 0===t?n:ho.f(n,t)},bo=te,Io=fn,Ao=Error,wo=d("".replace),Oo=String(Ao("zxcasd").stack),No=/\n\s*at [^:]*:[^\n]*/,Do=No.test(Oo),Po=B,Lo=!i((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Po(1,7)),7!==e.stack)})),ko=fn,Mo=function(e,t){if(Do&&"string"==typeof e&&!Ao.prepareStackTrace)for(;t--;)e=wo(e,No,"");return e},Uo=Lo,Vo=Error.captureStackTrace,xo={},Fo=xo,Bo=ht("iterator"),Go=Array.prototype,jo=function(e){return void 0!==e&&(Fo.Array===e||Go[Bo]===e)},Wo=pi,Ko=ke,Yo=H,Ho=xo,Xo=ht("iterator"),Jo=function(e){if(!Yo(e))return Ko(e,Xo)||Ko(e,"@@iterator")||Ho[Wo(e)]},zo=L,Zo=De,qo=nn,Qo=Ae,$o=Jo,es=TypeError,ts=function(e,t){var n=arguments.length<2?$o(e):t;if(Zo(n))return qo(zo(n,e));throw es(Qo(e)+" is not iterable")},ns=L,is=nn,rs=ke,os=function(e,t,n){var i,r;is(e);try{if(!(i=rs(e,"return"))){if("throw"===t)throw n;return n}i=ns(i,e)}catch(e){r=!0,i=e}if("throw"===t)throw n;if(r)throw i;return is(i),n},ss=Zt,as=L,cs=nn,ds=Ae,ls=jo,us=Wn,hs=l,ps=ts,_s=Jo,Es=os,ms=TypeError,fs=function(e,t){this.stopped=e,this.result=t},gs=fs.prototype,Ss=function(e,t,n){var i,r,o,s,a,c,d,l=n&&n.that,u=!(!n||!n.AS_ENTRIES),h=!(!n||!n.IS_RECORD),p=!(!n||!n.IS_ITERATOR),_=!(!n||!n.INTERRUPTED),E=ss(t,l),m=function(e){return i&&Es(i,"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)i=e.iterator;else if(p)i=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(gs,a))return a;return new fs(!1)}i=ps(e,r)}for(c=h?e.next:i.next;!(d=as(c,i)).done;){try{a=f(d.value)}catch(e){Es(i,"throw",e)}if("object"==typeof a&&a&&hs(gs,a))return a}return new fs(!1)},Ts=mi,Rs=On,vs=l,ys=Tr,Cs=Or,bs=function(e,t,n){for(var i=zr(t),r=qr.f,o=Zr.f,s=0;s<i.length;s++){var a=i[s];Jr(e,a)||n&&Jr(n,a)||r(e,a,o(t,a))}},Is=Co,As=fn,ws=B,Os=function(e,t){bo(t)&&"cause"in t&&Io(e,"cause",t.cause)},Ns=function(e,t,n,i){Uo&&(Vo?Vo(e,t):ko(e,"stack",Mo(n,i)))},Ds=Ss,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 n,i=vs(Vs,this);Cs?n=Cs(ks(),i?ys(this):Vs):(n=i?this:Is(Vs),As(n,Ls,"Error")),void 0!==t&&As(n,"message",Ps(t)),Ns(n,Us,n.stack,1),arguments.length>2&&Os(n,arguments[2]);var r=[];return Ds(e,Ms,{that:r}),As(n,"errors",r),n};Cs?Cs(Us,ks):bs(Us,ks,{name:!0});var Vs=Us.prototype=Is(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,Gs=w,js=h.WeakMap,Ws=Gs(js)&&/native code/.test(String(js)),Ks=h,Ys=te,Hs=fn,Xs=Qe,Js=Ke,zs=ur,Zs=Dr,qs="Object already initialized",Qs=Ks.TypeError,$s=Ks.WeakMap;if(Ws||Js.state){var ea=Js.state||(Js.state=new $s);ea.get=ea.get,ea.has=ea.has,ea.set=ea.set,xs=function(e,t){if(ea.has(e))throw Qs(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=zs("state");Zs[ta]=!0,xs=function(e,t){if(Xs(e,ta))throw Qs(qs);return t.facade=e,Hs(e,ta,t),t},Fs=function(e){return Xs(e,ta)?e[ta]:{}},Bs=function(e){return Xs(e,ta)}}var na,ia,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 n;if(!Ys(t)||(n=Fs(t)).type!==e)throw Qs("Incompatible receiver, "+e+" required");return n}}},sa=N,aa=Qe,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=fn,pa=function(e,t,n,i){return i&&i.enumerable?e[t]=n:ha(e,t,n),e},_a=i,Ea=w,ma=te,fa=Co,ga=Tr,Sa=pa,Ta=ht("iterator"),Ra=!1;[].keys&&("next"in(ra=[].keys())?(ia=ga(ga(ra)))!==Object.prototype&&(na=ia):Ra=!0);var va=!ma(na)||_a((function(){var e={};return na[Ta].call(e)!==e}));Ea((na=va?{}:fa(na))[Ta])||Sa(na,Ta,(function(){return this}));var ya={IteratorPrototype:na,BUGGY_SAFARI_ITERATORS:Ra},Ca=pi,ba=si?{}.toString:function(){return"[object "+Ca(this)+"]"},Ia=si,Aa=qt.f,wa=fn,Oa=Qe,Na=ba,Da=ht("toStringTag"),Pa=function(e,t,n,i){if(e){var r=n?e:e.prototype;Oa(r,Da)||Aa(r,Da,{configurable:!0,value:t}),i&&!Ia&&wa(r,"toString",Na)}},La=ya.IteratorPrototype,ka=Co,Ma=B,Ua=Pa,Va=xo,xa=function(){return this},Fa=function(e,t,n,i){var r=t+" Iterator";return e.prototype=ka(La,{next:Ma(+!i,n)}),Ua(e,r,!1,!0),Va[r]=xa,e},Ba=On,Ga=L,ja=ua,Wa=Fa,Ka=Tr,Ya=Pa,Ha=pa,Xa=xo,Ja=ya,za=ja.PROPER,Za=Ja.BUGGY_SAFARI_ITERATORS,qa=ht("iterator"),Qa="keys",$a="values",ec="entries",tc=function(){return this},nc=function(e,t,n,i,r,o,s){Wa(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Za&&e in p)return p[e];switch(e){case Qa:case $a:case ec:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[qa]||p["@@iterator"]||r&&p[r],E=!Za&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=Ka(m.call(new e)))!==Object.prototype&&a.next&&(Ya(a,u,!0,!0),Xa[u]=tc),za&&r==$a&&_&&_.name!==$a&&(h=!0,E=function(){return Ga(_,this)}),r)if(c={values:l($a),keys:o?E:l(Qa),entries:l(ec)},s)for(d in c)(Za||h||!(d in p))&&Ha(p,d,c[d]);else Ba({target:t,proto:!0,forced:Za||h},c);return s&&p[qa]!==E&&Ha(p,qa,E,{name:r}),Xa[t]=E,c},ic=function(e,t){return{value:e,done:t}},rc=Q,oc=xo,sc=oa;qt.f;var ac=nc,cc=ic,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,n=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,cc(void 0,!0)):cc("keys"==n?i:"values"==n?t[i]:[i,t[i]],!1)}),"values"),oc.Arguments=oc.Array;var hc=qt,pc=function(e,t,n){return hc.f(e,t,n)},_c=ae,Ec=pc,mc=N,fc=ht("species"),gc=l,Sc=TypeError,Tc=function(e,t){if(gc(t,e))return e;throw Sc("Incorrect invocation")},Rc=w,vc=Ke,yc=d(Function.toString);Rc(vc.inspectSource)||(vc.inspectSource=function(e){return yc(e)});var Cc=vc.inspectSource,bc=d,Ic=i,Ac=w,wc=pi,Oc=Cc,Nc=function(){},Dc=[],Pc=ae("Reflect","construct"),Lc=/^\s*(?:class|function)\b/,kc=bc(Lc.exec),Mc=!Lc.exec(Nc),Uc=function(e){if(!Ac(e))return!1;try{return Pc(Nc,Dc,e),!0}catch(e){return!1}},Vc=function(e){if(!Ac(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,Gc,jc=!Pc||Ic((function(){var e;return Uc(Uc.call)||!Uc(Object)||!Uc((function(){e=!0}))||e}))?Vc:Uc,Wc=jc,Kc=Ae,Yc=TypeError,Hc=nn,Xc=function(e){if(Wc(e))return e;throw Yc(Kc(e)+" is not a constructor")},Jc=H,zc=ht("species"),Zc=function(e,t){var n,i=Hc(e).constructor;return void 0===i||Jc(n=Hc(i)[zc])?t:Xc(n)},qc=d([].slice),Qc=TypeError,$c=function(e,t){if(e<t)throw Qc("Not enough arguments");return e},ed=/(?:ipad|iphone|ipod).*applewebkit/i.test(ce),td=h,nd=f,id=Zt,rd=w,od=Qe,sd=i,ad=lo,cd=qc,dd=It,ld=$c,ud=ed,hd=Gi,pd=td.setImmediate,_d=td.clearImmediate,Ed=td.process,md=td.Dispatch,fd=td.Function,gd=td.MessageChannel,Sd=td.String,Td=0,Rd={},vd="onreadystatechange";sd((function(){xc=td.location}));var yd=function(e){if(od(Rd,e)){var t=Rd[e];delete Rd[e],t()}},Cd=function(e){return function(){yd(e)}},bd=function(e){yd(e.data)},Id=function(e){td.postMessage(Sd(e),xc.protocol+"//"+xc.host)};pd&&_d||(pd=function(e){ld(arguments.length,1);var t=rd(e)?e:fd(e),n=cd(arguments,1);return Rd[++Td]=function(){nd(t,void 0,n)},Fc(Td),Td},_d=function(e){delete Rd[e]},hd?Fc=function(e){Ed.nextTick(Cd(e))}:md&&md.now?Fc=function(e){md.now(Cd(e))}:gd&&!ud?(Gc=(Bc=new gd).port2,Bc.port1.onmessage=bd,Fc=id(Gc.postMessage,Gc)):td.addEventListener&&rd(td.postMessage)&&!td.importScripts&&xc&&"file:"!==xc.protocol&&!sd(Id)?(Fc=Id,td.addEventListener("message",bd,!1)):Fc=vd in dd("script")?function(e){ad.appendChild(dd("script"))[vd]=function(){ad.removeChild(this),yd(e)}}:function(e){setTimeout(Cd(e),0)});var Ad={set:pd,clear:_d},wd=function(){this.head=null,this.tail=null};wd.prototype={add:function(e){var t={item:e,next:null},n=this.tail;n?n.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=Zt,Fd=O.f,Bd=Ad.set,Gd=kd,jd=ed,Wd=Md,Kd=Ud,Yd=Gi,Hd=Vd.MutationObserver||Vd.WebKitMutationObserver,Xd=Vd.document,Jd=Vd.process,zd=Vd.Promise,Zd=Fd(Vd,"queueMicrotask"),qd=Zd&&Zd.value;if(!qd){var Qd=new Gd,$d=function(){var e,t;for(Yd&&(e=Jd.domain)&&e.exit();t=Qd.get();)try{t()}catch(e){throw Qd.head&&Od(),e}e&&e.enter()};jd||Yd||Kd||!Hd||!Xd?!Wd&&zd&&zd.resolve?((Pd=zd.resolve(void 0)).constructor=zd,Ld=xd(Pd.then,Pd),Od=function(){Ld($d)}):Yd?Od=function(){Jd.nextTick($d)}:(Bd=xd(Bd,Vd),Od=function(){Bd($d)}):(Nd=!0,Dd=Xd.createTextNode(""),new Hd($d).observe(Dd,{characterData:!0}),Od=function(){Dd.data=Nd=!Nd}),qd=function(e){Qd.head||Od(),Qd.add(e)}}var el=qd,tl=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},nl=h.Promise,il="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,rl=!il&&!Gi&&"object"==typeof window&&"object"==typeof document,ol=h,sl=nl,al=w,cl=Ht,dl=Cc,ll=ht,ul=rl,hl=il,pl=Ee,_l=sl&&sl.prototype,El=ll("species"),ml=!1,fl=al(ol.PromiseRejectionEvent),gl=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 n=new sl((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((n.constructor={})[El]=i,!(ml=n.then((function(){}))instanceof i))return!0}return!t&&(ul||hl)&&!fl})),Sl={CONSTRUCTOR:gl,REJECTION_EVENT:fl,SUBCLASSING:ml},Tl={},Rl=De,vl=TypeError,yl=function(e){var t,n;this.promise=new e((function(e,i){if(void 0!==t||void 0!==n)throw vl("Bad Promise constructor");t=e,n=i})),this.resolve=Rl(t),this.reject=Rl(n)};Tl.f=function(e){return new yl(e)};var Cl,bl,Il=On,Al=Gi,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=Zc,xl=Ad.set,Fl=el,Bl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},Gl=tl,jl=kd,Wl=oa,Kl=nl,Yl=Sl,Hl=Tl,Xl="Promise",Jl=Yl.CONSTRUCTOR,zl=Yl.REJECTION_EVENT,Zl=Wl.getterFor(Xl),ql=Wl.set,Ql=Kl&&Kl.prototype,$l=Kl,eu=Ql,tu=wl.TypeError,nu=wl.document,iu=wl.process,ru=Hl.f,ou=ru,su=!!(nu&&nu.createEvent&&wl.dispatchEvent),au="unhandledrejection",cu=function(e){var t;return!(!Ml(e)||!kl(t=e.then))&&t},du=function(e,t){var n,i,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?n=o:(l&&l.enter(),n=a(o),l&&(l.exit(),r=!0)),n===e.promise?d(tu("Promise-chain cycle")):(i=cu(n))?Ol(i,n,c,d):c(n)):d(o)}catch(e){l&&!r&&l.exit(),d(e)}},lu=function(e,t){e.notified||(e.notified=!0,Fl((function(){for(var n,i=e.reactions;n=i.get();)du(n,e);e.notified=!1,t&&!e.rejection&&hu(e)})))},uu=function(e,t,n){var i,r;su?((i=nu.createEvent("Event")).promise=t,i.reason=n,i.initEvent(e,!1,!0),wl.dispatchEvent(i)):i={promise:t,reason:n},!zl&&(r=wl["on"+e])?r(i):e===au&&Bl("Unhandled promise rejection",n)},hu=function(e){Ol(xl,wl,(function(){var t,n=e.facade,i=e.value;if(pu(e)&&(t=Gl((function(){Al?iu.emit("unhandledRejection",i,n):uu(au,n,i)})),e.rejection=Al||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;Al?iu.emit("rejectionHandled",t):uu("rejectionhandled",t,e.value)}))},Eu=function(e,t,n){return function(i){e(t,i,n)}},mu=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,lu(e,!0))},fu=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw tu("Promise can't be resolved itself");var i=cu(t);i?Fl((function(){var n={done:!1};try{Ol(i,t,Eu(fu,n,e),Eu(mu,n,e))}catch(t){mu(n,t,e)}})):(e.value=t,e.state=1,lu(e,!1))}catch(t){mu({done:!1},t,e)}}};Jl&&(eu=($l=function(e){Ul(this,eu),Ll(e),Ol(Cl,this);var t=Zl(this);try{e(Eu(fu,t),Eu(mu,t))}catch(e){mu(t,e)}}).prototype,(Cl=function(e){ql(this,{type:Xl,done:!1,notified:!1,parent:!1,reactions:new jl,rejection:!1,state:0,value:void 0})}).prototype=Nl(eu,"then",(function(e,t){var n=Zl(this),i=ru(Vl(this,$l));return n.parent=!0,i.ok=!kl(e)||e,i.fail=kl(t)&&t,i.domain=Al?iu.domain:void 0,0==n.state?n.reactions.add(i):Fl((function(){du(i,n)})),i.promise})),bl=function(){var e=new Cl,t=Zl(e);this.promise=e,this.resolve=Eu(fu,t),this.reject=Eu(mu,t)},Hl.f=ru=function(e){return e===$l||undefined===e?new bl(e):ou(e)}),Il({global:!0,constructor:!0,wrap:!0,forced:Jl},{Promise:$l}),Dl($l,Xl,!1,!0),Pl(Xl);var gu=ht("iterator"),Su=!1;try{var Tu=0,Ru={next:function(){return{done:!!Tu++}},return:function(){Su=!0}};Ru[gu]=function(){return this},Array.from(Ru,(function(){throw 2}))}catch(e){}var vu=nl,yu=function(e,t){if(!t&&!Su)return!1;var n=!1;try{var i={};i[gu]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch(e){}return n},Cu=Sl.CONSTRUCTOR||!yu((function(e){vu.all(e).then(void 0,(function(){}))})),bu=L,Iu=De,Au=Tl,wu=tl,Ou=Ss;On({target:"Promise",stat:!0,forced:Cu},{all:function(e){var t=this,n=Au.f(t),i=n.resolve,r=n.reject,o=wu((function(){var n=Iu(t.resolve),o=[],s=0,a=1;Ou(e,(function(e){var c=s++,d=!1;a++,bu(n,t,e).then((function(e){d||(d=!0,o[c]=e,--a||i(o))}),r)})),--a||i(o)}));return o.error&&r(o.value),n.promise}});var Nu=On,Du=Sl.CONSTRUCTOR;nl&&nl.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=Ss;On({target:"Promise",stat:!0,forced:Cu},{race:function(e){var t=this,n=ku.f(t),i=n.reject,r=Mu((function(){var r=Lu(t.resolve);Uu(e,(function(e){Pu(r,t,e).then(n.resolve,i)}))}));return r.error&&i(r.value),n.promise}});var Vu=L,xu=Tl;On({target:"Promise",stat:!0,forced:Sl.CONSTRUCTOR},{reject:function(e){var t=xu.f(this);return Vu(t.reject,void 0,e),t.promise}});var Fu=nn,Bu=te,Gu=Tl,ju=function(e,t){if(Fu(e),Bu(t)&&t.constructor===e)return t;var n=Gu.f(e);return(0,n.resolve)(t),n.promise},Wu=On,Ku=nl,Yu=Sl.CONSTRUCTOR,Hu=ju,Xu=ae("Promise"),Ju=!Yu;Wu({target:"Promise",stat:!0,forced:true},{resolve:function(e){return Hu(Ju&&this===Xu?Ku:this,e)}});var zu=L,Zu=De,qu=Tl,Qu=tl,$u=Ss;On({target:"Promise",stat:!0,forced:Cu},{allSettled:function(e){var t=this,n=qu.f(t),i=n.resolve,r=n.reject,o=Qu((function(){var n=Zu(t.resolve),r=[],o=0,s=1;$u(e,(function(e){var a=o++,c=!1;s++,zu(n,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||i(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||i(r))}))})),--s||i(r)}));return o.error&&r(o.value),n.promise}});var eh=L,th=De,nh=ae,ih=Tl,rh=tl,oh=Ss,sh="No one promise resolved";On({target:"Promise",stat:!0,forced:Cu},{any:function(e){var t=this,n=nh("AggregateError"),i=ih.f(t),r=i.resolve,o=i.reject,s=rh((function(){var i=th(t.resolve),s=[],a=0,c=1,d=!1;oh(e,(function(e){var l=a++,u=!1;c++,eh(i,t,e).then((function(e){u||d||(d=!0,r(e))}),(function(e){u||d||(u=!0,s[l]=e,--c||o(new n(s,sh)))}))})),--c||o(new n(s,sh))}));return s.error&&o(s.value),i.promise}});var ah=On,ch=nl,dh=i,lh=ae,uh=w,hh=Zc,ph=ju,_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")),n=uh(e);return this.then(n?function(n){return ph(t,e()).then((function(){return n}))}:e,n?function(n){return ph(t,e()).then((function(){throw n}))}:e)}});var Eh=d,mh=kn,fh=mi,gh=z,Sh=Eh("".charAt),Th=Eh("".charCodeAt),Rh=Eh("".slice),vh=function(e){return function(t,n){var i,r,o=fh(gh(t)),s=mh(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=Th(o,s))<55296||i>56319||s+1===a||(r=Th(o,s+1))<56320||r>57343?e?Sh(o,s):i:e?Rh(o,s,s+2):r-56320+(i-55296<<10)+65536}},yh={codeAt:vh(!1),charAt:vh(!0)},Ch=yh.charAt,bh=mi,Ih=oa,Ah=nc,wh=ic,Oh="String Iterator",Nh=Ih.set,Dh=Ih.getterFor(Oh);Ah(String,"String",(function(e){Nh(this,{type:Oh,string:bh(e),index:0})}),(function(){var e,t=Dh(this),n=t.string,i=t.index;return i>=n.length?wh(void 0,!0):(e=Ch(n,i),t.index+=e.length,wh(e,!1))}));var Ph=ne.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=pi,Uh=fn,Vh=xo,xh=ht("toStringTag");for(var Fh in Lh){var Bh=kh[Fh],Gh=Bh&&Bh.prototype;Gh&&Mh(Gh)!==xh&&Uh(Gh,xh,Fh),Vh[Fh]=Vh.Array}var jh=Ph,Wh=n(jh),Kh=qn("Array").values,Yh=pi,Hh=Qe,Xh=l,Jh=Kh,zh=Array.prototype,Zh={DOMTokenList:!0,NodeList:!0},qh=function(e){var t=e.values;return e===zh||Xh(zh,e)&&t===zh.values||Hh(Zh,Yh(e))?Jh:t},Qh=n(qh),$h=Ae,ep=TypeError,tp=vt,np=qt,ip=B,rp=function(e,t,n){var i=tp(t);i in e?np.f(e,i,ip(0,n)):e[i]=n},op=xn,sp=Wn,ap=rp,cp=Array,dp=Math.max,lp=function(e,t,n){for(var i=sp(e),r=op(t,i),o=op(void 0===n?i:n,i),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 n=e.length,i=hp(n/2);return n<8?_p(e,t):Ep(e,pp(up(e,0,i),t),pp(up(e,i),t),t)},_p=function(e,t){for(var n,i,r=e.length,o=1;o<r;){for(i=o,n=e[o];i&&t(e[i-1],n)>0;)e[i]=e[--i];i!==o++&&(e[i]=n)}return e},Ep=function(e,t,n,i){for(var r=t.length,o=n.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?i(t[s],n[a])<=0?t[s++]:n[a++]:s<r?t[s++]:n[a++];return e},mp=pp,fp=ce.match(/firefox\/(\d+)/i),gp=!!fp&&+fp[1],Sp=/MSIE|Trident/.test(ce),Tp=ce.match(/AppleWebKit\/(\d+)\./),Rp=!!Tp&&+Tp[1],vp=On,yp=d,Cp=De,bp=ze,Ip=Wn,Ap=function(e,t){if(!delete e[t])throw ep("Cannot delete property "+$h(t)+" of "+$h(e))},wp=mi,Op=i,Np=mp,Dp=Bi,Pp=gp,Lp=Sp,kp=Ee,Mp=Rp,Up=[],Vp=yp(Up.sort),xp=yp(Up.push),Fp=Op((function(){Up.sort(void 0)})),Bp=Op((function(){Up.sort(null)})),Gp=Dp("sort"),jp=!Op((function(){if(kp)return kp<70;if(!(Pp&&Pp>3)){if(Lp)return!0;if(Mp)return Mp<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)Up.push({k:t+i,v:n})}for(Up.sort((function(e,t){return t.v-e.v})),i=0;i<Up.length;i++)t=Up[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));vp({target:"Array",proto:!0,forced:Fp||!Bp||!Gp||!jp},{sort:function(e){void 0!==e&&Cp(e);var t=bp(this);if(jp)return void 0===e?Vp(t):Vp(t,e);var n,i,r=[],o=Ip(t);for(i=0;i<o;i++)i in t&&xp(r,t[i]);for(Np(r,function(e){return function(t,n){return void 0===n?-1:void 0===t?1:void 0!==e?+e(t,n)||0:wp(t)>wp(n)?1:-1}}(e)),n=Ip(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)Ap(t,i++);return t}});var Wp=qn("Array").sort,Kp=l,Yp=Wp,Hp=Array.prototype,Xp=function(e){var t=e.sort;return e===Hp||Kp(Hp,e)&&t===Hp.sort?Yp:t},Jp=n(Xp),zp=i,Zp=ht("iterator"),qp=!zp((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n=new URLSearchParams("a=1&a=2"),i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),n.delete("a",2),!e.toJSON||!n.has("a",1)||n.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[Zp]||"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"!==i||"x"!==new URL("http://x",void 0).host})),Qp=pa,$p=On,e_=h,t_=L,n_=d,i_=N,r_=qp,o_=pa,s_=pc,a_=function(e,t,n){for(var i in t)n&&n.unsafe&&e[i]?e[i]=t[i]:Qp(e,i,t[i],n);return e},c_=Pa,d_=Fa,l_=oa,u_=Tc,h_=w,p_=Qe,__=Zt,E_=pi,m_=nn,f_=te,g_=mi,S_=Co,T_=B,R_=ts,v_=Jo,y_=$c,C_=mp,b_=ht("iterator"),I_="URLSearchParams",A_=I_+"Iterator",w_=l_.set,O_=l_.getterFor(I_),N_=l_.getterFor(A_),D_=Object.getOwnPropertyDescriptor,P_=function(e){if(!i_)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,G_=e_.encodeURIComponent,j_=n_("".charAt),W_=n_([].join),K_=n_([].push),Y_=n_("".replace),H_=n_([].shift),X_=n_([].splice),J_=n_("".split),z_=n_("".slice),Z_=/\+/g,q_=Array(4),Q_=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=Y_(e,Z_," "),n=4;try{return B_(t)}catch(e){for(;n;)t=Y_(t,Q_(n--),$_);return t}},tE=/[!'()~]|%20/g,nE={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},iE=function(e){return nE[e]},rE=function(e){return Y_(G_(e),tE,iE)},oE=d_((function(e,t){w_(this,{type:A_,iterator:R_(O_(e).entries),kind:t})}),"Iterator",(function(){var e=N_(this),t=e.kind,n=e.iterator.next(),i=n.value;return n.done||(n.value="keys"===t?i.key:"values"===t?i.value:[i.key,i.value]),n}),!0),sE=function(e){this.entries=[],this.url=null,void 0!==e&&(f_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===j_(e,0)?z_(e,1):e:g_(e)))};sE.prototype={type:I_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,n,i,r,o,s,a,c=v_(e);if(c)for(n=(t=R_(e,c)).next;!(i=t_(n,t)).done;){if(o=(r=R_(m_(i.value))).next,(s=t_(o,r)).done||(a=t_(o,r)).done||!t_(o,r).done)throw F_("Expected sequence with length 2");K_(this.entries,{key:g_(s.value),value:g_(a.value)})}else for(var d in e)p_(e,d)&&K_(this.entries,{key:d,value:g_(e[d])})},parseQuery:function(e){if(e)for(var t,n,i=J_(e,"&"),r=0;r<i.length;)(t=i[r++]).length&&(n=J_(t,"="),K_(this.entries,{key:eE(H_(n)),value:eE(W_(n,"="))}))},serialize:function(){for(var e,t=this.entries,n=[],i=0;i<t.length;)e=t[i++],K_(n,rE(e.key)+"="+rE(e.value));return W_(n,"&")},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));i_||(this.size=e.entries.length)},cE=aE.prototype;if(a_(cE,{append:function(e,t){var n=O_(this);y_(arguments.length,2),K_(n.entries,{key:g_(e),value:g_(t)}),i_||this.length++,n.updateURL()},delete:function(e){for(var t=O_(this),n=y_(arguments.length,1),i=t.entries,r=g_(e),o=n<2?void 0:arguments[1],s=void 0===o?o:g_(o),a=0;a<i.length;){var c=i[a];if(c.key!==r||void 0!==s&&c.value!==s)a++;else if(X_(i,a,1),void 0!==s)break}i_||(this.size=i.length),t.updateURL()},get:function(e){var t=O_(this).entries;y_(arguments.length,1);for(var n=g_(e),i=0;i<t.length;i++)if(t[i].key===n)return t[i].value;return null},getAll:function(e){var t=O_(this).entries;y_(arguments.length,1);for(var n=g_(e),i=[],r=0;r<t.length;r++)t[r].key===n&&K_(i,t[r].value);return i},has:function(e){for(var t=O_(this).entries,n=y_(arguments.length,1),i=g_(e),r=n<2?void 0:arguments[1],o=void 0===r?r:g_(r),s=0;s<t.length;){var a=t[s++];if(a.key===i&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var n=O_(this);y_(arguments.length,1);for(var i,r=n.entries,o=!1,s=g_(e),a=g_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?X_(r,c--,1):(o=!0,i.value=a));o||K_(r,{key:s,value:a}),i_||(this.size=r.length),n.updateURL()},sort:function(){var e=O_(this);C_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,n=O_(this).entries,i=__(e,arguments.length>1?arguments[1]:void 0),r=0;r<n.length;)i((t=n[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,b_,cE.entries,{name:"entries"}),o_(cE,"toString",(function(){return O_(this).serialize()}),{enumerable:!0}),i_&&s_(cE,"size",{get:function(){return O_(this).entries.length},configurable:!0,enumerable:!0}),c_(aE,I_),$p({global:!0,constructor:!0,forced:!r_},{URLSearchParams:aE}),!r_&&h_(M_)){var dE=n_(V_.has),lE=n_(V_.set),uE=function(e){if(f_(e)){var t,n=e.body;if(E_(n)===I_)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"),S_(e,{body:T_(0,g_(n)),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=ne.URLSearchParams,mE=N,fE=d,gE=L,SE=i,TE=to,RE=Gr,vE=k,yE=ze,CE=Y,bE=Object.assign,IE=Object.defineProperty,AE=fE([].concat),wE=!bE||SE((function(){if(mE&&1!==bE({b:1},bE(IE({},"a",{enumerable:!0,get:function(){IE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),i="abcdefghijklmnopqrst";return e[n]=7,i.split("").forEach((function(e){t[e]=e})),7!=bE({},e)[n]||TE(bE({},t)).join("")!=i}))?function(e,t){for(var n=yE(e),i=arguments.length,r=1,o=RE.f,s=vE.f;i>r;)for(var a,c=CE(arguments[r++]),d=o?AE(TE(c),o(c)):TE(c),l=d.length,u=0;l>u;)a=d[u++],mE&&!gE(s,c,a)||(n[a]=c[a]);return n}:bE,OE=nn,NE=os,DE=Zt,PE=L,LE=ze,kE=function(e,t,n,i){try{return i?t(OE(n)[0],n[1]):t(n)}catch(t){NE(e,"throw",t)}},ME=jo,UE=jc,VE=Wn,xE=rp,FE=ts,BE=Jo,GE=Array,jE=d,WE=2147483647,KE=/[^\0-\u007E]/,YE=/[.\u3002\uFF0E\uFF61]/g,HE="Overflow: input needs wider integers to process",XE=RangeError,JE=jE(YE.exec),zE=Math.floor,ZE=String.fromCharCode,qE=jE("".charCodeAt),QE=jE([].join),$E=jE([].push),em=jE("".replace),tm=jE("".split),nm=jE("".toLowerCase),im=function(e){return e+22+75*(e<26)},rm=function(e,t,n){var i=0;for(e=n?zE(e/700):e>>1,e+=zE(e/t);e>455;)e=zE(e/35),i+=36;return zE(i+36*e/(e+38))},om=function(e){var t=[];e=function(e){for(var t=[],n=0,i=e.length;n<i;){var r=qE(e,n++);if(r>=55296&&r<=56319&&n<i){var o=qE(e,n++);56320==(64512&o)?$E(t,((1023&r)<<10)+(1023&o)+65536):($E(t,r),n--)}else $E(t,r)}return t}(e);var n,i,r=e.length,o=128,s=0,a=72;for(n=0;n<e.length;n++)(i=e[n])<128&&$E(t,ZE(i));var c=t.length,d=c;for(c&&$E(t,"-");d<r;){var l=WE;for(n=0;n<e.length;n++)(i=e[n])>=o&&i<l&&(l=i);var u=d+1;if(l-o>zE((WE-s)/u))throw XE(HE);for(s+=(l-o)*u,o=l,n=0;n<e.length;n++){if((i=e[n])<o&&++s>WE)throw XE(HE);if(i==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,ZE(im(_+E%m))),h=zE(E/m),p+=36}$E(t,ZE(im(h))),a=rm(s,u,d==c),s=0,d++}}s++,o++}return QE(t,"")},sm=On,am=N,cm=qp,dm=h,lm=Zt,um=d,hm=pa,pm=pc,_m=Tc,Em=Qe,mm=wE,fm=function(e){var t=LE(e),n=UE(this),i=arguments.length,r=i>1?arguments[1]:void 0,o=void 0!==r;o&&(r=DE(r,i>2?arguments[2]:void 0));var s,a,c,d,l,u,h=BE(t),p=0;if(!h||this===GE&&ME(h))for(s=VE(t),a=n?new this(s):GE(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=n?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},gm=lp,Sm=yh.codeAt,Tm=function(e){var t,n,i=[],r=tm(em(nm(e),YE,"."),".");for(t=0;t<r.length;t++)n=r[t],$E(i,JE(KE,n)?"xn--"+om(n):n);return QE(i,".")},Rm=mi,vm=Pa,ym=$c,Cm=_E,bm=oa,Im=bm.set,Am=bm.getterFor("URL"),wm=Cm.URLSearchParams,Om=Cm.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),Gm=um("".replace),jm=um([].shift),Wm=um("".split),Km=um("".slice),Ym=um("".toLowerCase),Hm=um([].unshift),Xm="Invalid scheme",Jm="Invalid host",zm="Invalid port",Zm=/[a-z]/i,qm=/[\d+-.a-z]/i,Qm=/\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,n,i,r;if("number"==typeof e){for(t=[],n=0;n<4;n++)Hm(t,e%256),e=Lm(e/256);return Vm(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,n=1,i=null,r=0,o=0;o<8;o++)0!==e[o]?(r>n&&(t=i,n=r),i=null,r=0):(null===i&&(i=o),++r);return r>n&&(t=i,n=r),t}(e),n=0;n<8;n++)r&&0===e[n]||(r&&(r=!1),i===n?(t+=n?":":"::",r=!0):(t+=xm(e[n],16),n<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 n=Sm(e,0);return n>32&&n<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 n;return 2==e.length&&Um(Zm,Mm(e,0))&&(":"==(n=Mm(e,1))||!t&&"|"==n)},ff=function(e){var t;return e.length>1&&mf(Km(e,0,2))&&(2==e.length||"/"===(t=Mm(e,2))||"\\"===t||"?"===t||"#"===t)},gf=function(e){return"."===e||"%2e"===Ym(e)},Sf={},Tf={},Rf={},vf={},yf={},Cf={},bf={},If={},Af={},wf={},Of={},Nf={},Df={},Pf={},Lf={},kf={},Mf={},Uf={},Vf={},xf={},Ff={},Bf=function(e,t,n){var i,r,o,s=Rm(e);if(t){if(r=this.parse(s))throw Dm(r);this.searchParams=null}else{if(void 0!==n&&(i=new Bf(n,!0)),r=this.parse(s,null,i))throw Dm(r);(o=Om(new wm)).bindURL(this),this.searchParams=o}};Bf.prototype={type:"URL",parse:function(e,t,n){var i,r,o,s,a,c=this,d=t||Sf,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=Gm(e,sf,""),e=Gm(e,af,"$1")),e=Gm(e,cf,""),i=fm(e);l<=i.length;){switch(r=i[l],d){case Sf:if(!r||!Um(Zm,r)){if(t)return Xm;d=Rf;continue}u+=Ym(r),d=Tf;break;case Tf:if(r&&(Um(qm,r)||"+"==r||"-"==r||"."==r))u+=Ym(r);else{if(":"!=r){if(t)return Xm;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()&&n&&n.scheme==c.scheme?d=vf:c.isSpecial()?d=If:"/"==i[l+1]?(d=yf,l++):(c.cannotBeABaseURL=!0,Bm(c.path,""),d=Vf)}break;case Rf:if(!n||n.cannotBeABaseURL&&"#"!=r)return Xm;if(n.cannotBeABaseURL&&"#"==r){c.scheme=n.scheme,c.path=gm(n.path),c.query=n.query,c.fragment="",c.cannotBeABaseURL=!0,d=Ff;break}d="file"==n.scheme?Pf:Cf;continue;case vf:if("/"!=r||"/"!=i[l+1]){d=Cf;continue}d=Af,l++;break;case yf:if("/"==r){d=wf;break}d=Uf;continue;case Cf:if(c.scheme=n.scheme,r==pE)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=gm(n.path),c.query=n.query;else if("/"==r||"\\"==r&&c.isSpecial())d=bf;else if("?"==r)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=gm(n.path),c.query="",d=xf;else{if("#"!=r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=gm(n.path),c.path.length--,d=Uf;continue}c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=gm(n.path),c.query=n.query,c.fragment="",d=Ff}break;case bf:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,d=Uf;continue}d=wf}else d=Af;break;case If:if(d=Af,"/"!=r||"/"!=Mm(u,l+1))continue;l++;break;case Af: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 Jm;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 Jm;if(s=c.parseHost(u))return s;if(u="",d=Df,t==Nf)return}break;case Df:if(!Um(Qm,r)){if(r==pE||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var g=Pm(u,10);if(g>65535)return zm;c.port=c.isSpecial()&&g===Ef[c.scheme]?null:g,u=""}if(t)return;d=Mf;continue}return zm}u+=r;break;case Pf:if(c.scheme="file","/"==r||"\\"==r)d=Lf;else{if(!n||"file"!=n.scheme){d=Uf;continue}if(r==pE)c.host=n.host,c.path=gm(n.path),c.query=n.query;else if("?"==r)c.host=n.host,c.path=gm(n.path),c.query="",d=xf;else{if("#"!=r){ff(Vm(gm(i,l),""))||(c.host=n.host,c.path=gm(n.path),c.shortenPath()),d=Uf;continue}c.host=n.host,c.path=gm(n.path),c.query=n.query,c.fragment="",d=Ff}}break;case Lf:if("/"==r||"\\"==r){d=kf;break}n&&"file"==n.scheme&&!ff(Vm(gm(i,l),""))&&(mf(n.path[0],!0)?Bm(c.path,n.path[0]):c.host=n.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=Ym(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||Bm(c.path,"")):gf(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];)jm(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,n,i;if("["==Mm(e,0)){if("]"!=Mm(e,e.length-1))return Jm;if(t=function(e){var t,n,i,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=n=0;n<4&&Um(nf,h());)t=16*t+Pm(h(),16),u++,n++;if("."==h()){if(0==n)return;if(u-=n,d>6)return;for(i=0;h();){if(r=null,i>0){if(!("."==h()&&i<4))return;u++}if(!Um(Qm,h()))return;for(;Um(Qm,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!=++i&&4!=i||d++}if(4!=i)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}(Km(e,1,-1)),!t)return Jm;this.host=t}else if(this.isSpecial()){if(e=Tm(e),Um(rf,e))return Jm;if(t=function(e){var t,n,i,r,o,s,a,c=Wm(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(n=[],i=0;i<t;i++){if(""==(r=c[i]))return e;if(o=10,r.length>1&&"0"==Mm(r,0)&&(o=Um($m,r)?16:8,r=Km(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(n,s)}for(i=0;i<t;i++)if(s=n[i],i==t-1){if(s>=km(256,5-t))return null}else if(s>255)return null;for(a=Fm(n),i=0;i<n.length;i++)a+=n[i]*km(256,3-i);return a}(e),null===t)return Jm;this.host=t}else{if(Um(of,e))return Jm;for(t="",n=fm(e),i=0;i<n.length;i++)t+=_f(n[i],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,n=e.username,i=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+=n+(i?":"+i:"")+"@"),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 Gf(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)+":",Sf)},getUsername:function(){return this.username},setUsername:function(e){var t=fm(Rm(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var n=0;n<t.length;n++)this.username+=_f(t[n],pf)}},getPassword:function(){return this.password},setPassword:function(e){var t=fm(Rm(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var n=0;n<t.length;n++)this.password+=_f(t[n],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)},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=Km(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=Km(e,1)),this.fragment="",this.parse(e,Ff)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Gf=function(e){var t=_m(this,jf),n=ym(arguments.length,1)>1?arguments[1]:void 0,i=Im(t,new Bf(e,!1,n));am||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},jf=Gf.prototype,Wf=function(e,t){return{get:function(){return Am(this)[e]()},set:t&&function(e){return Am(this)[t](e)},configurable:!0,enumerable:!0}};if(am&&(pm(jf,"href",Wf("serialize","setHref")),pm(jf,"origin",Wf("getOrigin")),pm(jf,"protocol",Wf("getProtocol","setProtocol")),pm(jf,"username",Wf("getUsername","setUsername")),pm(jf,"password",Wf("getPassword","setPassword")),pm(jf,"host",Wf("getHost","setHost")),pm(jf,"hostname",Wf("getHostname","setHostname")),pm(jf,"port",Wf("getPort","setPort")),pm(jf,"pathname",Wf("getPathname","setPathname")),pm(jf,"search",Wf("getSearch","setSearch")),pm(jf,"searchParams",Wf("getSearchParams")),pm(jf,"hash",Wf("getHash","setHash"))),hm(jf,"toJSON",(function(){return Am(this).serialize()}),{enumerable:!0}),hm(jf,"toString",(function(){return Am(this).serialize()}),{enumerable:!0}),Nm){var Kf=Nm.createObjectURL,Yf=Nm.revokeObjectURL;Kf&&hm(Gf,"createObjectURL",lm(Kf,Nm)),Yf&&hm(Gf,"revokeObjectURL",lm(Yf,Nm))}vm(Gf,"URL"),sm({global:!0,constructor:!0,forced:!cm,sham:!am},{URL:Gf});var Hf=On,Xf=i,Jf=$c,zf=mi,Zf=qp,qf=ae("URL");Hf({target:"URL",stat:!0,forced:!(Zf&&Xf((function(){qf.canParse()})))},{canParse:function(e){var t=Jf(arguments.length,1),n=zf(e),i=t<2||void 0===arguments[1]?void 0:zf(arguments[1]);try{return!!new qf(n,i)}catch(e){return!1}}});var Qf=n(ne.URL);let $f=!0,eg=!0;function tg(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function ng(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ig(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 rg(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(eg=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function og(){if("object"==typeof window){if($f)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function sg(e,t){eg&&console.warn(e+" is deprecated, please use "+t+" instead.")}function ag(e){return"[object Object]"===Object.prototype.toString.call(e)}function cg(e){var t;return ag(e)?zi(t=Object.keys(e)).call(t,(function(t,n){const i=ag(e[n]),r=i?cg(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})}),{}):e}function dg(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?dg(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{dg(e,e.get(t),n)}))})))}function lg(e,t,n){const i=n?"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((n=>{n.type===i&&n.trackId===t.id&&dg(e,n,r)}))})),r}const ug=og;function hg(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[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,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.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 n.mediaDevices.enumerateDevices().then((n=>{n=n.filter((e=>"videoinput"===e.kind));let s=n.find((e=>t.some((t=>{var n;return Di(n=e.label.toLowerCase()).call(n,t)}))));return!s&&n.length&&Di(t).call(t,"back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),ug("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return ug("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(n.getUserMedia=function(e,t,i){r(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.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 pg(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function _g(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",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ng(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Eg(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 n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function mg(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t[n.id]=n})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){n(o(r(e)))};return t.apply(this,[i,e])}return new Wh(((e,n)=>{t.apply(this,[function(t){e(o(r(t)))},n])})).then(n,i)}}function fg(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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>lg(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}),ng(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>lg(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,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Wh.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Wh.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function gg(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,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Sg(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return gg(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}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,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");const 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[n.id];if(o)o.addTrack(t),Wh.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(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((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Tg(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Rg(e,t){ng(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var vg=Object.freeze({__proto__:null,fixNegotiationNeeded:Rg,shimAddTrackRemoveTrack:Sg,shimAddTrackRemoveTrackWithNative:gg,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((t=>{const i=n.video&&n.video.width,r=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(n.video.mandatory.maxWidth=i),r&&(n.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:Eg,shimGetStats:mg,shimGetUserMedia:hg,shimMediaStream:pg,shimOnTrack:_g,shimPeerConnection:Tg,shimSenderReceiverGetStats:fg});function yg(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){sg("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function Cg(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 bg(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 n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(r,o)}}function Ig(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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.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 Ag(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}),ng(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function wg(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){sg("removeStream","removeTrack"),this.getSenders().forEach((t=>{var n;t.track&&Di(n=e.getTracks()).call(n,t.track)&&this.removeTrack(t)}))})}function Og(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ng(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 n=e.length>0;n&&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 i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Dg(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 Pg(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 Lg(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 kg=Object.freeze({__proto__:null,shimAddTransceiver:Ng,shimCreateAnswer:Lg,shimCreateOffer:Pg,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Wh.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:Dg,shimGetUserMedia:yg,shimOnTrack:Cg,shimPeerConnection:bg,shimRTCDataChannel:Og,shimReceiverGetStats:Ag,shimRemoveStream:wg,shimSenderGetStats:Ig});function Mg(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var n;this._localStreams||(this._localStreams=[]),Di(n=this._localStreams).call(n,e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i&&i.forEach((e=>{var t;this._localStreams?Di(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 n=e.getTracks();this.getSenders().forEach((e=>{Di(n).call(n,e.track)&&this.removeTrack(e)}))})}}function Ug(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=[]),Di(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const n=new Event("addstream");n.stream=e,this.dispatchEvent(n)}))})}});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 n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function Vg(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=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},t.createAnswer=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};let a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Wh.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Wh.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Wh.resolve()):i},t.addIceCandidate=a}function xg(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Fg(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Fg(e){return e&&void 0!==e.video?Object.assign({},e,{video:cg(e.video)}):e}function Bg(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(sg("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Gg(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 jg(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 n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Wg(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Kg=Object.freeze({__proto__:null,shimAudioContext:Wg,shimCallbacksAPI:Vg,shimConstraints:Fg,shimCreateOfferLegacy:jg,shimGetUserMedia:xg,shimLocalStreamsAPI:Mg,shimRTCIceServerUrls:Bg,shimRemoteStreamsAPI:Ug,shimTrackEventTransceiver:Gg}),Yg="\t\n\v\f\r                　\u2028\u2029\ufeff",Hg=z,Xg=mi,Jg=Yg,zg=d("".replace),Zg=RegExp("^["+Jg+"]+"),qg=RegExp("(^|[^"+Jg+"])["+Jg+"]+$"),Qg=function(e){return function(t){var n=Xg(Hg(t));return 1&e&&(n=zg(n,Zg,"")),2&e&&(n=zg(n,qg,"$1")),n}},$g={start:Qg(1),end:Qg(2),trim:Qg(3)},eS=ua.PROPER,tS=i,nS=Yg,iS=$g.trim;On({target:"String",proto:!0,forced:function(e){return tS((function(){return!!nS[e]()||"​᠎"!=="​᠎"[e]()||eS&&nS[e].name!==e}))}("trim")},{trim:function(){return iS(this)}});var rS=qn("String").trim,oS=l,sS=rS,aS=String.prototype,cS=function(e){var t=e.trim;return"string"==typeof e||e===aS||oS(aS,e)&&t===aS.trim?sS:t},dS=n(cS),lS={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 n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={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":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(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 n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\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 n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},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 n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.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,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},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,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.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 n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let r=3;r<i.length;r++){const o=i[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const i=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const 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]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.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,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},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 n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[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:n.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 n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const o=void 0!==n?n:2;r=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"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 n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(lS);var uS=lS.exports,hS=n(uS),pS=e({__proto__:null,default:hS},[uS]);function _S(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 n=new t(e),i=hS.parseCandidate(e.candidate),r=Object.assign(n,i);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ng(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ES(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ng(e,"icecandidate",(e=>{if(e.candidate){const t=hS.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function mS(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 n=function(e){if(!e||!e.sdp)return!1;const t=hS.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=hS.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n},r=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n},o=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=hS.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i},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(n(arguments[0])){const e=i(arguments[0]),t=r(e),n=o(arguments[0],e);let s;s=0===t&&0===n?Number.POSITIVE_INFINITY:0===t||0===n?Math.max(t,n):Math.min(t,n);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function fS(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.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 n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},ng(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function gS(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 n=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 n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function SS(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==dS(e).call(e))).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function TS(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.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():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Wh.resolve())})}function RS(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.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 n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var vS=Object.freeze({__proto__:null,removeExtmapAllowMixed:SS,shimAddIceCandidateNullOrEmpty:TS,shimConnectionState:gS,shimMaxMessageSize:mS,shimParameterlessSetLocalDescription:RS,shimRTCIceCandidate:_S,shimRTCIceCandidateRelayProtocol:ES,shimSendThrowTypeError:fS});!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 n=og,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.mozGetUserMedia)t.browser="firefox",t.version=tg(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=tg(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=tg(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:i,commonShim:vS,extractVersion:tg,disableLog:ig,disableWarnings:rg,sdp:pS};switch(i.browser){case"chrome":if(!vg||!Tg||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=vg,TS(e,i),RS(e),hg(e,i),pg(e),Tg(e,i),_g(e),Sg(e,i),Eg(e),mg(e),fg(e),Rg(e,i),_S(e),ES(e),gS(e),mS(e,i),fS(e),SS(e,i);break;case"firefox":if(!kg||!bg||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=kg,TS(e,i),RS(e),yg(e,i),bg(e,i),Cg(e),wg(e),Ig(e),Ag(e),Og(e),Ng(e),Dg(e),Pg(e),Lg(e),_S(e),gS(e),mS(e,i),fS(e);break;case"safari":if(!Kg||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=Kg,TS(e,i),RS(e),Bg(e),jg(e),Vg(e),Mg(e),Ug(e),Gg(e),xg(e),Wg(e),_S(e),ES(e),mS(e,i),fS(e),SS(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var yS=nn,CS=L,bS=Qe,IS=l,AS=function(){var e=yS(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},wS=RegExp.prototype,OS=function(e){var t=e.flags;return void 0!==t||"flags"in wS||bS(e,"flags")||!IS(wS,e)?t:CS(AS,e)},NS=d,DS=ze,PS=Math.floor,LS=NS("".charAt),kS=NS("".replace),MS=NS("".slice),US=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,VS=/\$([$&'`]|\d{1,2})/g,xS=On,FS=L,BS=d,GS=z,jS=w,WS=H,KS=ni,YS=mi,HS=ke,XS=OS,JS=function(e,t,n,i,r,o){var s=n+e.length,a=i.length,c=VS;return void 0!==r&&(r=DS(r),c=US),kS(o,c,(function(o,c){var d;switch(LS(c,0)){case"$":return"$";case"&":return e;case"`":return MS(t,0,n);case"'":return MS(t,s);case"<":d=r[MS(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>a){var u=PS(l/10);return 0===u?o:u<=a?void 0===i[u-1]?LS(c,1):i[u-1]+LS(c,1):o}d=i[l-1]}return void 0===d?"":d}))},zS=ht("replace"),ZS=TypeError,qS=BS("".indexOf),QS=BS("".replace),$S=BS("".slice),eT=Math.max,tT=function(e,t,n){return n>e.length?-1:""===t?n:qS(e,t,n)};xS({target:"String",proto:!0},{replaceAll:function(e,t){var n,i,r,o,s,a,c,d,l,u=GS(this),h=0,p=0,_="";if(!WS(e)){if((n=KS(e))&&(i=YS(GS(XS(e))),!~qS(i,"g")))throw ZS("`.replaceAll` does not allow non-global regexes");if(r=HS(e,zS))return FS(r,e,u,t);if(n)return QS(YS(u),e,t)}for(o=YS(u),s=YS(e),(a=jS(t))||(t=YS(t)),c=s.length,d=eT(1,c),h=tT(o,s,0);-1!==h;)l=a?YS(t(s,h,o)):JS(s,o,h,[],void 0,t),_+=$S(o,p,h)+l,p=h+c,h=tT(o,s,h+d);return p<o.length&&(_+=$S(o,p)),_}});var nT=qn("String").replaceAll,iT=l,rT=nT,oT=String.prototype,sT=function(e){var t=e.replaceAll;return"string"==typeof e||e===oT||iT(oT,e)&&t===oT.replaceAll?rT:t},aT=n(sT),cT=h;On({global:!0,forced:cT.globalThis!==cT},{globalThis:cT});var dT,lT,uT=n(h),hT={exports:{}};dT=hT,lT=hT.exports,function(e,t){var n="function",i="undefined",r="object",o="string",s="major",a="model",c="name",d="type",l="vendor",u="version",h="architecture",p="console",_="mobile",E="tablet",m="smarttv",f="wearable",g="embedded",S="Amazon",T="Apple",R="ASUS",v="BlackBerry",y="Browser",C="Chrome",b="Firefox",I="Google",A="Huawei",w="LG",O="Microsoft",N="Motorola",D="Opera",P="Samsung",L="Sharp",k="Sony",M="Xiaomi",U="Zebra",V="Facebook",x="Chromium OS",F="Mac OS",B=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},G=function(e,t){return typeof e===o&&-1!==j(t).indexOf(j(e))},j=function(e){return e.toLowerCase()},W=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===i?e:e.substring(0,350)},K=function(e,i){for(var o,s,a,c,d,l,u=0;u<i.length&&!d;){var h=i[u],p=i[u+1];for(o=s=0;o<h.length&&!d&&h[o];)if(d=h[o++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===r&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):t:this[c[0]]=l?c[1].call(this,l,c[2]):t:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):t):this[c]=l||t;u+=2}},Y=function(e,n){for(var i in n)if(typeof n[i]===r&&n[i].length>0){for(var o=0;o<n[i].length;o++)if(G(n[i][o],e))return"?"===i?t:i}else if(G(n[i],e))return"?"===i?t:i;return e},H={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],[u,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,u],[/opios[\/ ]+([\w\.]+)/i],[u,[c,D+" Mini"]],[/\bopr\/([\w\.]+)/i],[u,[c,D]],[/(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],[c,u],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[c,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[u,[c,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[u,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[c,"IE"]],[/yabrowser\/([\w\.]+)/i],[u,[c,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+y],u],[/\bfocus\/([\w\.]+)/i],[u,[c,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[c,D+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[c,D+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[c,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[u,[c,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[c,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1 "+y],u],[/(comodo_dragon)\/([\w\.]+)/i],[[c,/_/g," "],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[c,u],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,V],u],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[c,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[c,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[c,C+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,C+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[c,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[u,Y,{"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],[c,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[c,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],[c,u],[/(cobalt)\/([\w\.]+)/i],[c,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[h,"amd64"]],[/(ia32(?=;))/i],[[h,j]],[/((?:i[346]|x)86)[;\)]/i],[[h,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/windows (ce|mobile); ppc;/i],[[h,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[h,/ower/,"",j]],[/(sun4\w)[;\)]/i],[[h,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[h,j]]],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],[a,[l,P],[d,E]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[a,[l,P],[d,_]],[/\((ip(?:hone|od)[\w ]*);/i],[a,[l,T],[d,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[a,[l,T],[d,E]],[/(macintosh);/i],[a,[l,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[a,[l,L],[d,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[a,[l,A],[d,E]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[a,[l,A],[d,_]],[/\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],[[a,/_/g," "],[l,M],[d,_]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[a,/_/g," "],[l,M],[d,E]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[a,[l,"OPPO"],[d,_]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[a,[l,"Vivo"],[d,_]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[a,[l,"Realme"],[d,_]],[/\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],[a,[l,N],[d,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[a,[l,N],[d,E]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[a,[l,w],[d,E]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[a,[l,w],[d,_]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[a,[l,"Lenovo"],[d,E]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[a,/_/g," "],[l,"Nokia"],[d,_]],[/(pixel c)\b/i],[a,[l,I],[d,E]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[a,[l,I],[d,_]],[/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],[a,[l,k],[d,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[a,"Xperia Tablet"],[l,k],[d,E]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[a,[l,"OnePlus"],[d,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[a,[l,S],[d,E]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[a,/(.+)/g,"Fire Phone $1"],[l,S],[d,_]],[/(playbook);[-\w\),; ]+(rim)/i],[a,l,[d,E]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[a,[l,v],[d,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[a,[l,R],[d,E]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[a,[l,R],[d,_]],[/(nexus 9)/i],[a,[l,"HTC"],[d,E]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[a,/_/g," "],[d,_]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[a,[l,"Acer"],[d,E]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[a,[l,"Meizu"],[d,_]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[l,a,[d,_]],[/(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],[l,a,[d,E]],[/(surface duo)/i],[a,[l,O],[d,E]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[a,[l,"Fairphone"],[d,_]],[/(u304aa)/i],[a,[l,"AT&T"],[d,_]],[/\bsie-(\w*)/i],[a,[l,"Siemens"],[d,_]],[/\b(rct\w+) b/i],[a,[l,"RCA"],[d,E]],[/\b(venue[\d ]{2,7}) b/i],[a,[l,"Dell"],[d,E]],[/\b(q(?:mv|ta)\w+) b/i],[a,[l,"Verizon"],[d,E]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[a,[l,"Barnes & Noble"],[d,E]],[/\b(tm\d{3}\w+) b/i],[a,[l,"NuVision"],[d,E]],[/\b(k88) b/i],[a,[l,"ZTE"],[d,E]],[/\b(nx\d{3}j) b/i],[a,[l,"ZTE"],[d,_]],[/\b(gen\d{3}) b.+49h/i],[a,[l,"Swiss"],[d,_]],[/\b(zur\d{3}) b/i],[a,[l,"Swiss"],[d,E]],[/\b((zeki)?tb.*\b) b/i],[a,[l,"Zeki"],[d,E]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],a,[d,E]],[/\b(ns-?\w{0,9}) b/i],[a,[l,"Insignia"],[d,E]],[/\b((nxa|next)-?\w{0,9}) b/i],[a,[l,"NextBook"],[d,E]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],a,[d,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],a,[d,_]],[/\b(ph-1) /i],[a,[l,"Essential"],[d,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[a,[l,"Envizen"],[d,E]],[/\b(trio[-\w\. ]+) b/i],[a,[l,"MachSpeed"],[d,E]],[/\btu_(1491) b/i],[a,[l,"Rotor"],[d,E]],[/(shield[\w ]+) b/i],[a,[l,"Nvidia"],[d,E]],[/(sprint) (\w+)/i],[l,a,[d,_]],[/(kin\.[onetw]{3})/i],[[a,/\./g," "],[l,O],[d,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[a,[l,U],[d,E]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[a,[l,U],[d,_]],[/smart-tv.+(samsung)/i],[l,[d,m]],[/hbbtv.+maple;(\d+)/i],[[a,/^/,"SmartTV"],[l,P],[d,m]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,w],[d,m]],[/(apple) ?tv/i],[l,[a,T+" TV"],[d,m]],[/crkey/i],[[a,C+"cast"],[l,I],[d,m]],[/droid.+aft(\w)( bui|\))/i],[a,[l,S],[d,m]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[a,[l,L],[d,m]],[/(bravia[\w ]+)( bui|\))/i],[a,[l,k],[d,m]],[/(mitv-\w{5}) bui/i],[a,[l,M],[d,m]],[/Hbbtv.*(technisat) (.*);/i],[l,a,[d,m]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,W],[a,W],[d,m]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,m]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,a,[d,p]],[/droid.+; (shield) bui/i],[a,[l,"Nvidia"],[d,p]],[/(playstation [345portablevi]+)/i],[a,[l,k],[d,p]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[a,[l,O],[d,p]],[/((pebble))app/i],[l,a,[d,f]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[a,[l,T],[d,f]],[/droid.+; (glass) \d/i],[a,[l,I],[d,f]],[/droid.+; (wt63?0{2,3})\)/i],[a,[l,U],[d,f]],[/(quest( 2| pro)?)/i],[a,[l,V],[d,f]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[d,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[a,[d,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[a,[d,E]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,E]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,_]],[/(android[-\w\. ]{0,9});.+buil/i],[a,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[c,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[c,"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],[c,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,u],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[c,[u,Y,H]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[c,"Windows"],[u,Y,H]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,F],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,u],[/\(bb(10);/i],[u,[c,v]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[c,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[c,C+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,x],u],[/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],[c,u],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[c,u]]},J=function(p,m){if(typeof p===r&&(m=p,p=t),!(this instanceof J))return new J(p,m).getResult();var f=typeof e!==i&&e.navigator?e.navigator:t,g=p||(f&&f.userAgent?f.userAgent:""),S=f&&f.userAgentData?f.userAgentData:t,T=m?function(e,t){var n={};for(var i in e)t[i]&&t[i].length%2==0?n[i]=t[i].concat(e[i]):n[i]=e[i];return n}(X,m):X;return this.getBrowser=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.browser),e[s]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:t}(e[u]),f&&f.brave&&typeof f.brave.isBrave==n&&(e[c]="Brave"),e},this.getCPU=function(){var e={};return e[h]=t,K.call(e,g,T.cpu),e},this.getDevice=function(){var e={};return e[l]=t,e[a]=t,e[d]=t,K.call(e,g,T.device),!e[d]&&S&&S.mobile&&(e[d]=_),"Macintosh"==e[a]&&f&&typeof f.standalone!==i&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[a]="iPad",e[d]=E),e},this.getEngine=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.engine),e},this.getOS=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.os),!e[c]&&S&&"Unknown"!=S.platform&&(e[c]=S.platform.replace(/chrome os/i,x).replace(/macos/i,F)),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 g},this.setUA=function(e){return g=typeof e===o&&e.length>350?W(e,350):e,this},this.setUA(g),this};J.VERSION="0.7.34",J.BROWSER=B([c,u,s]),J.CPU=B([h]),J.DEVICE=B([a,l,d,p,_,m,E,f,g]),J.ENGINE=J.OS=B([c,u]),dT.exports&&(lT=dT.exports=J),lT.UAParser=J;var z=typeof e!==i&&(e.jQuery||e.Zepto);if(z&&!z.ua){var Z=new J;z.ua=Z.getResult(),z.ua.get=function(){return Z.getUA()},z.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var n in t)z.ua[n]=t[n]}}}("object"==typeof window?window:t);var pT=n(hT.exports),_T=Ad.clear;On({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==_T},{clearImmediate:_T});var ET="function"==typeof Bun&&Bun&&"string"==typeof Bun.version,mT=h,fT=f,gT=w,ST=ET,TT=ce,RT=qc,vT=$c,yT=mT.Function,CT=/MSIE .\./.test(TT)||ST&&function(){var e=mT.Bun.version.split(".");return e.length<3||0==e[0]&&(e[1]<3||3==e[1]&&0==e[2])}(),bT=On,IT=h,AT=Ad.set,wT=function(e,t){var n=t?2:1;return CT?function(i,r){var o=vT(arguments.length,1)>n,s=gT(i)?i:yT(i),a=o?RT(arguments,n):[],c=o?function(){fT(s,this,a)}:s;return t?e(c,r):e(c)}:e},OT=IT.setImmediate?wT(AT,!1):AT;bT({global:!0,bind:!0,enumerable:!0,forced:IT.setImmediate!==OT},{setImmediate:OT});var NT=n(ne.setImmediate),DT=On,PT=el,LT=De,kT=$c,MT=Gi,UT=h.process;DT({global:!0,enumerable:!0,dontCallGetSet:!0},{queueMicrotask:function(e){kT(arguments.length,1),LT(e);var t=MT&&UT.domain;PT(t?t.bind(e):e)}});var VT=n(ne.queueMicrotask);function xT(e,t){return function(){return e.apply(t,arguments)}}const{toString:FT}=Object.prototype,{getPrototypeOf:BT}=Object,{iterator:GT,toStringTag:jT}=Symbol,WT=(KT=Object.create(null),e=>{const t=FT.call(e);return KT[t]||(KT[t]=t.slice(8,-1).toLowerCase())});var KT;const YT=e=>(e=e.toLowerCase(),t=>WT(t)===e),HT=e=>t=>typeof t===e,{isArray:XT}=Array,JT=HT("undefined");function zT(e){return null!==e&&!JT(e)&&null!==e.constructor&&!JT(e.constructor)&&QT(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZT=YT("ArrayBuffer");const qT=HT("string"),QT=HT("function"),$T=HT("number"),eR=e=>null!==e&&"object"==typeof e,tR=e=>{if("object"!==WT(e))return!1;const t=BT(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||jT in e||GT in e)},nR=YT("Date"),iR=YT("File"),rR=YT("Blob"),oR=YT("FileList");const sR=void 0!==uT?uT:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},aR=void 0!==sR.FormData?sR.FormData:void 0,cR=YT("URLSearchParams"),[dR,lR,uR,hR]=["ReadableStream","Request","Response","Headers"].map(YT);function pR(e,t){let n,i,{allOwnKeys:r=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null!=e)if("object"!=typeof e&&(e=[e]),XT(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(zT(e))return;const i=r?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length;let s;for(n=0;n<o;n++)s=i[n],t.call(null,e[s],s,e)}}function _R(e,t){if(zT(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const ER=void 0!==uT?uT:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,mR=e=>!JT(e)&&e!==ER;const fR=(gR="undefined"!=typeof Uint8Array&&BT(Uint8Array),e=>gR&&e instanceof gR);var gR;const SR=YT("HTMLFormElement"),TR=(e=>{let{hasOwnProperty:t}=e;return(e,n)=>t.call(e,n)})(Object.prototype),RR=YT("RegExp"),vR=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};pR(n,((n,r)=>{let o;!1!==(o=t(n,r,e))&&(i[r]=o||n)})),Object.defineProperties(e,i)};const yR=YT("AsyncFunction"),CR=(bR="function"==typeof NT,IR=QT(ER.postMessage),bR?NT:IR?(AR="axios@".concat(Math.random()),wR=[],ER.addEventListener("message",(e=>{let{source:t,data:n}=e;t===ER&&n===AR&&wR.length&&wR.shift()()}),!1),e=>{wR.push(e),ER.postMessage(AR,"*")}):e=>setTimeout(e));var bR,IR,AR,wR;const OR=void 0!==VT?VT.bind(ER):"undefined"!=typeof process&&process.nextTick||CR;var NR={isArray:XT,isArrayBuffer:ZT,isBuffer:zT,isFormData:e=>{let t;return e&&(aR&&e instanceof aR||QT(e.append)&&("formdata"===(t=WT(e))||"object"===t&&QT(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ZT(e.buffer),t},isString:qT,isNumber:$T,isBoolean:e=>!0===e||!1===e,isObject:eR,isPlainObject:tR,isEmptyObject:e=>{if(!eR(e)||zT(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:dR,isRequest:lR,isResponse:uR,isHeaders:hR,isUndefined:JT,isDate:nR,isFile:iR,isReactNativeBlob:e=>!(!e||void 0===e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:rR,isRegExp:RR,isFunction:QT,isStream:e=>eR(e)&&QT(e.pipe),isURLSearchParams:cR,isTypedArray:fR,isFileList:oR,forEach:pR,merge:function e(){const{caseless:t,skipUndefined:n}=mR(this)&&this||{},i={},r=(r,o)=>{if("__proto__"===o||"constructor"===o||"prototype"===o)return;const s=t&&_R(i,o)||o;tR(i[s])&&tR(r)?i[s]=e(i[s],r):tR(r)?i[s]=e({},r):XT(r)?i[s]=r.slice():n&&JT(r)||(i[s]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&pR(arguments[e],r);return i},extend:function(e,t,n){let{allOwnKeys:i}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return pR(t,((t,i)=>{n&&QT(t)?Object.defineProperty(e,i,{value:xT(t,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:i}),e},trim:e=>dS(e)?dS(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,n,i)=>{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{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],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==n&&BT(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:WT,kindOfTest:YT,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(XT(e))return e;let t=e.length;if(!$T(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[GT]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:SR,hasOwnProperty:TR,hasOwnProp:TR,reduceDescriptors:vR,freezeMethods:e=>{vR(e,((t,n)=>{if(QT(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];QT(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach((e=>{n[e]=!0}))};return XT(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:_R,global:ER,isContextDefined:mR,isSpecCompliantForm:function(e){return!!(e&&QT(e.append)&&"FormData"===e[jT]&&e[GT])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(eR(e)){if(t.indexOf(e)>=0)return;if(zT(e))return e;if(!("toJSON"in e)){t[i]=e;const r=XT(e)?[]:{};return pR(e,((e,t)=>{const o=n(e,i+1);!JT(o)&&(r[t]=o)})),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:yR,isThenable:e=>e&&(eR(e)||QT(e))&&QT(e.then)&&QT(e.catch),setImmediate:CR,asap:OR,isIterable:e=>null!=e&&QT(e[GT])};class DR extends Error{static from(e,t,n,i,r,o){const s=new DR(e.message,t||e.code,n,i,r);return s.cause=e,s.name=e.name,null!=e.status&&null==s.status&&(s.status=e.status),o&&Object.assign(s,o),s}constructor(e,t,n,i,r){super(e),Object.defineProperty(this,"message",{value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),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:NR.toJSONObject(this.config),code:this.code,status:this.status}}}DR.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",DR.ERR_BAD_OPTION="ERR_BAD_OPTION",DR.ECONNABORTED="ECONNABORTED",DR.ETIMEDOUT="ETIMEDOUT",DR.ERR_NETWORK="ERR_NETWORK",DR.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",DR.ERR_DEPRECATED="ERR_DEPRECATED",DR.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",DR.ERR_BAD_REQUEST="ERR_BAD_REQUEST",DR.ERR_CANCELED="ERR_CANCELED",DR.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",DR.ERR_INVALID_URL="ERR_INVALID_URL";var PR=DR;function LR(e){return NR.isPlainObject(e)||NR.isArray(e)}function kR(e){return NR.endsWith(e,"[]")?e.slice(0,-2):e}function MR(e,t,n){return e?e.concat(t).map((function(e,t){return e=kR(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const UR=NR.toFlatObject(NR,{},null,(function(e){return/^is[A-Z]/.test(e)}));function VR(e,t,n){if(!NR.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=NR.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!NR.isUndefined(t[e])}))).metaTokens,r=n.visitor||d,o=n.dots,s=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&NR.isSpecCompliantForm(t);if(!NR.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(NR.isDate(e))return e.toISOString();if(NR.isBoolean(e))return e.toString();if(!a&&NR.isBlob(e))throw new PR("Blob is not supported. Use a Buffer instead.");return NR.isArrayBuffer(e)||NR.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,n,r){let a=e;if(NR.isReactNative(t)&&NR.isReactNativeBlob(e))return t.append(MR(r,n,o),c(e)),!1;if(e&&!r&&"object"==typeof e)if(NR.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else if(NR.isArray(e)&&function(e){return NR.isArray(e)&&!e.some(LR)}(e)||(NR.isFileList(e)||NR.endsWith(n,"[]"))&&(a=NR.toArray(e)))return n=kR(n),a.forEach((function(e,i){!NR.isUndefined(e)&&null!==e&&t.append(!0===s?MR([n],i,o):null===s?n:n+"[]",c(e))})),!1;return!!LR(e)||(t.append(MR(r,n,o),c(e)),!1)}const l=[],u=Object.assign(UR,{defaultVisitor:d,convertValue:c,isVisitable:LR});if(!NR.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!NR.isUndefined(n)){if(-1!==l.indexOf(n))throw Error("Circular reference detected in "+i.join("."));l.push(n),NR.forEach(n,(function(n,o){!0===(!(NR.isUndefined(n)||null===n)&&r.call(t,n,NR.isString(o)?dS(o).call(o):o,i,u))&&e(n,i?i.concat(o):[o])})),l.pop()}}(e),t}function xR(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function FR(e,t){this._pairs=[],e&&VR(e,this,t)}const BR=FR.prototype;function GR(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function jR(e,t,n){if(!t)return e;const i=n&&n.encode||GR,r=NR.isFunction(n)?{serialize:n}:n,o=r&&r.serialize;let s;if(s=o?o(t,r):NR.isURLSearchParams(t)?t.toString():new FR(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}BR.append=function(e,t){this._pairs.push([e,t])},BR.toString=function(e){const t=e?function(t){return e.call(this,t,xR)}:xR;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var WR=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){NR.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},KR={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},YR={exports:{}},HR=On,XR=N,JR=qt.f;HR({target:"Object",stat:!0,forced:Object.defineProperty!==JR,sham:!XR},{defineProperty:JR});var zR=ne.Object,ZR=YR.exports=function(e,t,n){return zR.defineProperty(e,t,n)};zR.defineProperty.sham&&(ZR.sham=!0);var qR=n(YR.exports),QR=TypeError,$R=qi,ev=jc,tv=te,nv=ht("species"),iv=Array,rv=function(e){var t;return $R(e)&&(t=e.constructor,(ev(t)&&(t===iv||$R(t.prototype))||tv(t)&&null===(t=t[nv]))&&(t=void 0)),void 0===t?iv:t},ov=function(e,t){return new(rv(e))(0===t?0:t)},sv=i,av=Ee,cv=ht("species"),dv=function(e){return av>=51||!sv((function(){var t=[];return(t.constructor={})[cv]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},lv=On,uv=i,hv=qi,pv=te,_v=ze,Ev=Wn,mv=function(e){if(e>9007199254740991)throw QR("Maximum allowed index exceeded");return e},fv=rp,gv=ov,Sv=dv,Tv=Ee,Rv=ht("isConcatSpreadable"),vv=Tv>=51||!uv((function(){var e=[];return e[Rv]=!1,e.concat()[0]!==e})),yv=function(e){if(!pv(e))return!1;var t=e[Rv];return void 0!==t?!!t:hv(e)};lv({target:"Array",proto:!0,arity:1,forced:!vv||!Sv("concat")},{concat:function(e){var t,n,i,r,o,s=_v(this),a=gv(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(yv(o=-1===t?s:arguments[t]))for(r=Ev(o),mv(c+r),n=0;n<r;n++,c++)n in o&&fv(a,c,o[n]);else mv(c+1),fv(a,c++,o);return a.length=c,a}});var Cv={},bv=R,Iv=Q,Av=Nr.f,wv=lp,Ov="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Cv.f=function(e){return Ov&&"Window"==bv(e)?function(e){try{return Av(e)}catch(e){return wv(Ov)}}(e):Av(Iv(e))};var Nv={},Dv=ht;Nv.f=Dv;var Pv=ne,Lv=Qe,kv=Nv,Mv=qt.f,Uv=function(e){var t=Pv.Symbol||(Pv.Symbol={});Lv(t,e)||Mv(t,e,{value:kv.f(e)})},Vv=L,xv=ae,Fv=ht,Bv=pa,Gv=function(){var e=xv("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=Fv("toPrimitive");t&&!t[i]&&Bv(t,i,(function(e){return Vv(n,this)}),{arity:1})},jv=Zt,Wv=Y,Kv=ze,Yv=Wn,Hv=ov,Xv=d([].push),Jv=function(e){var t=1==e,n=2==e,i=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,_=Kv(c),E=Wv(_),m=jv(d,l),f=Yv(E),g=0,S=u||Hv,T=t?S(c,f):n||s?S(c,0):void 0;f>g;g++)if((a||g in E)&&(p=m(h=E[g],g,_),e))if(t)T[g]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return g;case 2:Xv(T,h)}else switch(e){case 4:return!1;case 7:Xv(T,h)}return o?-1:i||r?r:T}},zv={forEach:Jv(0),map:Jv(1),filter:Jv(2),some:Jv(3),every:Jv(4),find:Jv(5),findIndex:Jv(6),filterReject:Jv(7)},Zv=On,qv=h,Qv=L,$v=d,ey=N,ty=Se,ny=i,iy=Qe,ry=l,oy=nn,sy=Q,ay=vt,cy=mi,dy=B,ly=Co,uy=to,hy=Nr,py=Cv,_y=Gr,Ey=O,my=qt,fy=Qr,gy=k,Sy=pa,Ty=pc,Ry=He,vy=Dr,yy=it,Cy=ht,by=Nv,Iy=Uv,Ay=Gv,wy=Pa,Oy=oa,Ny=zv.forEach,Dy=ur("hidden"),Py="Symbol",Ly="prototype",ky=Oy.set,My=Oy.getterFor(Py),Uy=Object[Ly],Vy=qv.Symbol,xy=Vy&&Vy[Ly],Fy=qv.TypeError,By=qv.QObject,Gy=Ey.f,jy=my.f,Wy=py.f,Ky=gy.f,Yy=$v([].push),Hy=Ry("symbols"),Xy=Ry("op-symbols"),Jy=Ry("wks"),zy=!By||!By[Ly]||!By[Ly].findChild,Zy=ey&&ny((function(){return 7!=ly(jy({},"a",{get:function(){return jy(this,"a",{value:7}).a}})).a}))?function(e,t,n){var i=Gy(Uy,t);i&&delete Uy[t],jy(e,t,n),i&&e!==Uy&&jy(Uy,t,i)}:jy,qy=function(e,t){var n=Hy[e]=ly(xy);return ky(n,{type:Py,tag:e,description:t}),ey||(n.description=t),n},Qy=function(e,t,n){e===Uy&&Qy(Xy,t,n),oy(e);var i=ay(t);return oy(n),iy(Hy,i)?(n.enumerable?(iy(e,Dy)&&e[Dy][i]&&(e[Dy][i]=!1),n=ly(n,{enumerable:dy(0,!1)})):(iy(e,Dy)||jy(e,Dy,dy(1,{})),e[Dy][i]=!0),Zy(e,i,n)):jy(e,i,n)},$y=function(e,t){oy(e);var n=sy(t),i=uy(n).concat(iC(n));return Ny(i,(function(t){ey&&!Qv(eC,n,t)||Qy(e,t,n[t])})),e},eC=function(e){var t=ay(e),n=Qv(Ky,this,t);return!(this===Uy&&iy(Hy,t)&&!iy(Xy,t))&&(!(n||!iy(this,t)||!iy(Hy,t)||iy(this,Dy)&&this[Dy][t])||n)},tC=function(e,t){var n=sy(e),i=ay(t);if(n!==Uy||!iy(Hy,i)||iy(Xy,i)){var r=Gy(n,i);return!r||!iy(Hy,i)||iy(n,Dy)&&n[Dy][i]||(r.enumerable=!0),r}},nC=function(e){var t=Wy(sy(e)),n=[];return Ny(t,(function(e){iy(Hy,e)||iy(vy,e)||Yy(n,e)})),n},iC=function(e){var t=e===Uy,n=Wy(t?Xy:sy(e)),i=[];return Ny(n,(function(e){!iy(Hy,e)||t&&!iy(Uy,e)||Yy(i,Hy[e])})),i};ty||(Sy(xy=(Vy=function(){if(ry(xy,this))throw Fy("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?cy(arguments[0]):void 0,t=yy(e),n=function(e){this===Uy&&Qv(n,Xy,e),iy(this,Dy)&&iy(this[Dy],t)&&(this[Dy][t]=!1),Zy(this,t,dy(1,e))};return ey&&zy&&Zy(Uy,t,{configurable:!0,set:n}),qy(t,e)})[Ly],"toString",(function(){return My(this).tag})),Sy(Vy,"withoutSetter",(function(e){return qy(yy(e),e)})),gy.f=eC,my.f=Qy,fy.f=$y,Ey.f=tC,hy.f=py.f=nC,_y.f=iC,by.f=function(e){return qy(Cy(e),e)},ey&&Ty(xy,"description",{configurable:!0,get:function(){return My(this).description}})),Zv({global:!0,constructor:!0,wrap:!0,forced:!ty,sham:!ty},{Symbol:Vy}),Ny(uy(Jy),(function(e){Iy(e)})),Zv({target:Py,stat:!0,forced:!ty},{useSetter:function(){zy=!0},useSimple:function(){zy=!1}}),Zv({target:"Object",stat:!0,forced:!ty,sham:!ey},{create:function(e,t){return void 0===t?ly(e):$y(ly(e),t)},defineProperty:Qy,defineProperties:$y,getOwnPropertyDescriptor:tC}),Zv({target:"Object",stat:!0,forced:!ty},{getOwnPropertyNames:nC}),Ay(),wy(Vy,Py),vy[Dy]=!0;var rC=Se&&!!Symbol.for&&!!Symbol.keyFor,oC=On,sC=ae,aC=Qe,cC=mi,dC=He,lC=rC,uC=dC("string-to-symbol-registry"),hC=dC("symbol-to-string-registry");oC({target:"Symbol",stat:!0,forced:!lC},{for:function(e){var t=cC(e);if(aC(uC,t))return uC[t];var n=sC("Symbol")(t);return uC[t]=n,hC[n]=t,n}});var pC=On,_C=Qe,EC=be,mC=Ae,fC=rC,gC=He("symbol-to-string-registry");pC({target:"Symbol",stat:!0,forced:!fC},{keyFor:function(e){if(!EC(e))throw TypeError(mC(e)+" is not a symbol");if(_C(gC,e))return gC[e]}});var SC=qi,TC=w,RC=R,vC=mi,yC=d([].push),CC=On,bC=ae,IC=f,AC=L,wC=d,OC=i,NC=w,DC=be,PC=qc,LC=function(e){if(TC(e))return e;if(SC(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];"string"==typeof r?yC(n,r):"number"!=typeof r&&"Number"!=RC(r)&&"String"!=RC(r)||yC(n,vC(r))}var o=n.length,s=!0;return function(e,t){if(s)return s=!1,t;if(SC(this))return t;for(var i=0;i<o;i++)if(n[i]===e)return t}}},kC=Se,MC=String,UC=bC("JSON","stringify"),VC=wC(/./.exec),xC=wC("".charAt),FC=wC("".charCodeAt),BC=wC("".replace),GC=wC(1..toString),jC=/[\uD800-\uDFFF]/g,WC=/^[\uD800-\uDBFF]$/,KC=/^[\uDC00-\uDFFF]$/,YC=!kC||OC((function(){var e=bC("Symbol")();return"[null]"!=UC([e])||"{}"!=UC({a:e})||"{}"!=UC(Object(e))})),HC=OC((function(){return'"\\udf06\\ud834"'!==UC("\udf06\ud834")||'"\\udead"'!==UC("\udead")})),XC=function(e,t){var n=PC(arguments),i=LC(t);if(NC(i)||void 0!==e&&!DC(e))return n[1]=function(e,t){if(NC(i)&&(t=AC(i,this,MC(e),t)),!DC(t))return t},IC(UC,null,n)},JC=function(e,t,n){var i=xC(n,t-1),r=xC(n,t+1);return VC(WC,e)&&!VC(KC,r)||VC(KC,e)&&!VC(WC,i)?"\\u"+GC(FC(e,0),16):e};UC&&CC({target:"JSON",stat:!0,arity:3,forced:YC||HC},{stringify:function(e,t,n){var i=PC(arguments),r=IC(YC?XC:UC,null,i);return HC&&"string"==typeof r?BC(r,jC,JC):r}});var zC=Gr,ZC=ze;On({target:"Object",stat:!0,forced:!Se||i((function(){zC.f(1)}))},{getOwnPropertySymbols:function(e){var t=zC.f;return t?t(ZC(e)):[]}}),Uv("asyncIterator"),Uv("hasInstance"),Uv("isConcatSpreadable"),Uv("iterator"),Uv("match"),Uv("matchAll"),Uv("replace"),Uv("search"),Uv("species"),Uv("split");var qC=Gv;Uv("toPrimitive"),qC();var QC=ae,$C=Pa;Uv("toStringTag"),$C(QC("Symbol"),"Symbol"),Uv("unscopables"),Pa(h.JSON,"JSON",!0);var eb=ne.Symbol,tb=ht,nb=qt.f,ib=tb("metadata"),rb=Function.prototype;void 0===rb[ib]&&nb(rb,ib,{value:null}),Uv("dispose"),Uv("metadata");var ob=eb;Uv("asyncDispose");var sb=d,ab=ae("Symbol"),cb=ab.keyFor,db=sb(ab.prototype.valueOf),lb=ab.isRegisteredSymbol||function(e){try{return void 0!==cb(db(e))}catch(e){return!1}};On({target:"Symbol",stat:!0},{isRegisteredSymbol:lb});for(var ub=He,hb=ae,pb=d,_b=be,Eb=ht,mb=hb("Symbol"),fb=mb.isWellKnownSymbol,gb=hb("Object","getOwnPropertyNames"),Sb=pb(mb.prototype.valueOf),Tb=ub("wks"),Rb=0,vb=gb(mb),yb=vb.length;Rb<yb;Rb++)try{var Cb=vb[Rb];_b(mb[Cb])&&Eb(Cb)}catch(e){}var bb=function(e){if(fb&&fb(e))return!0;try{for(var t=Sb(e),n=0,i=gb(Tb),r=i.length;n<r;n++)if(Tb[i[n]]==t)return!0}catch(e){}return!1};On({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:bb}),Uv("matcher"),Uv("observable"),On({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:lb}),On({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:bb}),Uv("metadataKey"),Uv("patternMatch"),Uv("replaceAll");var Ib=n(ob),Ab=n(Nv.f("iterator"));function wb(e){return wb="function"==typeof Ib&&"symbol"==typeof Ab?function(e){return typeof e}:function(e){return e&&"function"==typeof Ib&&e.constructor===Ib&&e!==Ib.prototype?"symbol":typeof e},wb(e)}var Ob=n(Nv.f("toPrimitive"));function Nb(e){var t=function(e,t){if("object"!==wb(e)||null===e)return e;var n=e[Ob];if(void 0!==n){var i=n.call(e,t||"default");if("object"!==wb(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===wb(t)?t:String(t)}function Db(e,t,n){return(t=Nb(t))in e?qR(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Pb=n(EE),Lb={isBrowser:!0,classes:{URLSearchParams:void 0!==Pb?Pb:FR,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const kb="undefined"!=typeof window&&"undefined"!=typeof document,Mb="object"==typeof navigator&&navigator||void 0,Ub=kb&&(!Mb||["ReactNative","NativeScript","NS"].indexOf(Mb.product)<0),Vb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,xb=kb&&window.location.href||"http://localhost";function Fb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Bb(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Fb(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Fb(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Gb=Bb(Bb({},Object.freeze({__proto__:null,hasBrowserEnv:kb,hasStandardBrowserEnv:Ub,hasStandardBrowserWebWorkerEnv:Vb,navigator:Mb,origin:xb})),Lb);function jb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Wb(e,t){return VR(e,new Gb.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?jb(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jb(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({visitor:function(e,t,n,i){return Gb.isNode&&NR.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}var Kb=yh.charAt,Yb=L,Hb=nn,Xb=w,Jb=R,zb=/./.exec,Zb=TypeError,qb=On,Qb=L,$b=C,eI=Fa,tI=ic,nI=z,iI=Gn,rI=mi,oI=nn,sI=H,aI=R,cI=ni,dI=OS,lI=ke,uI=i,hI=Zc,pI=function(e,t,n){return t+(n?Kb(e,t).length:1)},_I=function(e,t){var n=e.exec;if(Xb(n)){var i=Yb(n,e,t);return null!==i&&Hb(i),i}if("RegExp"===Jb(e))return Yb(zb,e,t);throw Zb("RegExp#exec called on incompatible receiver")},EI=oa,mI=ht("matchAll"),fI="RegExp String",gI=fI+" Iterator",SI=EI.set,TI=EI.getterFor(gI),RI=TypeError,vI=$b("".indexOf),yI=$b("".matchAll),CI=!!yI&&!uI((function(){yI("a",/./)})),bI=eI((function(e,t,n,i){SI(this,{type:gI,regexp:e,string:t,global:n,unicode:i,done:!1})}),fI,(function(){var e=TI(this);if(e.done)return tI(void 0,!0);var t=e.regexp,n=e.string,i=_I(t,n);return null===i?(e.done=!0,tI(void 0,!0)):e.global?(""===rI(i[0])&&(t.lastIndex=pI(n,iI(t.lastIndex),e.unicode)),tI(i,!1)):(e.done=!0,tI(i,!1))})),II=function(e){var t,n,i,r=oI(this),o=rI(e),s=hI(r,RegExp),a=rI(dI(r));return t=new s(s===RegExp?r.source:r,a),n=!!~vI(a,"g"),i=!!~vI(a,"u"),t.lastIndex=iI(r.lastIndex),new bI(t,o,n,i)};qb({target:"String",proto:!0,forced:CI},{matchAll:function(e){var t,n,i,r,o=nI(this);if(sI(e)){if(CI)return yI(o,e)}else{if(cI(e)&&(t=rI(nI(dI(e))),!~vI(t,"g")))throw RI("`.matchAll` does not allow non-global regexes");if(CI)return yI(o,e);if(void 0===(i=lI(e,mI))&&"RegExp"==aI(e)&&(i=II),i)return Qb(i,e,o)}return n=rI(o),r=new RegExp(e,"g"),Qb(II,r,n)}});var AI=qn("String").matchAll,wI=l,OI=AI,NI=String.prototype,DI=function(e){var t=e.matchAll;return"string"==typeof e||e===NI||wI(NI,e)&&t===NI.matchAll?OI:t},PI=n(DI);function LI(e){function t(e,n,i,r){let o=e[r++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=r>=e.length;if(o=!o&&NR.isArray(i)?i.length:o,a)return NR.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!s;i[o]&&NR.isObject(i[o])||(i[o]=[]);return t(e,n,i[o],r)&&NR.isArray(i[o])&&(i[o]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let o;for(i=0;i<r;i++)o=n[i],t[o]=e[o];return t}(i[o])),!s}if(NR.isFormData(e)&&NR.isFunction(e.entries)){const n={};return NR.forEachEntry(e,((e,i)=>{t(function(e){return PI(NR).call(NR,/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),i,n,0)})),n}return null}const kI={transitional:KR,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=NR.isObject(e);r&&NR.isHTMLForm(e)&&(e=new FormData(e));if(NR.isFormData(e))return i?JSON.stringify(LI(e)):e;if(NR.isArrayBuffer(e)||NR.isBuffer(e)||NR.isStream(e)||NR.isFile(e)||NR.isBlob(e)||NR.isReadableStream(e))return e;if(NR.isArrayBufferView(e))return e.buffer;if(NR.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Wb(e,this.formSerializer).toString();if((o=NR.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return VR(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(NR.isString(e))try{return(t||JSON.parse)(e),dS(NR).call(NR,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||kI.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(NR.isResponse(e)||NR.isReadableStream(e))return e;if(e&&NR.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n){if("SyntaxError"===e.name)throw PR.from(e,PR.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:Gb.classes.FormData,Blob:Gb.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};NR.forEach(["delete","get","head","post","put","patch"],(e=>{kI.headers[e]={}}));var MI=kI;const UI=NR.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 VI=Symbol("internals");function xI(e){var t;return e&&dS(t=String(e)).call(t).toLowerCase()}function FI(e){return!1===e||null==e?e:NR.isArray(e)?e.map(FI):String(e)}function BI(e,t,n,i,r){return NR.isFunction(i)?i.call(this,t,n):(r&&(t=n),NR.isString(t)?NR.isString(i)?-1!==t.indexOf(i):NR.isRegExp(i)?i.test(t):void 0:void 0)}class GI{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=xI(t);if(!r)throw new Error("header name must be a non-empty string");const o=NR.findKey(i,r);(!o||void 0===i[o]||!0===n||void 0===n&&!1!==i[o])&&(i[o||t]=FI(e))}const o=(e,t)=>NR.forEach(e,((e,n)=>r(e,n,t)));if(NR.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(NR.isString(e)&&(e=dS(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(dS(s=e).call(s)))o((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach((function(e){var o,s;r=e.indexOf(":"),n=dS(o=e.substring(0,r)).call(o).toLowerCase(),i=dS(s=e.substring(r+1)).call(s),!n||t[n]&&UI[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)})),t})(e),t);else if(NR.isObject(e)&&NR.isIterable(e)){let n,i,r={};for(const t of e){if(!NR.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?NR.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}o(r,t)}else null!=e&&r(t,e,n);var s;return this}get(e,t){if(e=xI(e)){const n=NR.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(NR.isFunction(t))return t.call(this,e,n);if(NR.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=xI(e)){const n=NR.findKey(this,e);return!(!n||void 0===this[n]||t&&!BI(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=xI(e)){const r=NR.findKey(n,e);!r||t&&!BI(0,n[r],r,t)||(delete n[r],i=!0)}}return NR.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!BI(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return NR.forEach(this,((i,r)=>{var o;const s=NR.findKey(n,r);if(s)return t[s]=FI(i),void delete t[r];const a=e?function(e){return dS(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(r):dS(o=String(r)).call(o);a!==r&&delete t[r],t[a]=FI(i),n[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.constructor.concat(this,...t)}toJSON(e){const t=Object.create(null);return NR.forEach(this,((n,i)=>{null!=n&&!1!==n&&(t[i]=e&&NR.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let[t,n]=e;return t+": "+n})).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 n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.forEach((e=>t.set(e))),t}static accessor(e){const t=(this[VI]=this[VI]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=xI(e);t[i]||(!function(e,t){const n=NR.toCamelCase(" "+t);["get","set","has"].forEach((i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})}))}(n,e),t[i]=!0)}return NR.isArray(e)?e.forEach(i):i(e),this}}GI.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),NR.reduceDescriptors(GI.prototype,((e,t)=>{let{value:n}=e,i=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(e){this[i]=e}}})),NR.freezeMethods(GI);var jI=GI;function WI(e,t){const n=this||MI,i=t||n,r=jI.from(i.headers);let o=i.data;return NR.forEach(e,(function(e){o=e.call(n,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function KI(e){return!(!e||!e.__CANCEL__)}var YI=class extends PR{constructor(e,t,n){super(null==e?"canceled":e,PR.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function HI(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new PR("Request failed with status code "+n.status,[PR.ERR_BAD_REQUEST,PR.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}const XI=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[s];r||(r=c),n[o]=a,i[o]=c;let l=s,u=0;for(;l!==o;)u+=n[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 n,i,r=0,o=1e3/t;const s=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,n=null,i&&(clearTimeout(i),i=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):(n=c,i||(i=setTimeout((()=>{i=null,s(n)}),o-t)))},()=>n&&s(n)]}((n=>{const o=n.loaded,s=n.lengthComputable?n.total:void 0,a=o-i,c=r(a);i=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:n,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),n)},JI=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},zI=e=>function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return NR.asap((()=>e(...n)))};var ZI=Gb.hasStandardBrowserEnv?((e,t)=>n=>(n=new Qf(n,Gb.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new Qf(Gb.origin),Gb.navigator&&/(msie|trident)/i.test(Gb.navigator.userAgent)):()=>!0,qI=Gb.hasStandardBrowserEnv?{write(e,t,n,i,r,o,s){if("undefined"==typeof document)return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];NR.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),NR.isString(i)&&a.push("path=".concat(i)),NR.isString(r)&&a.push("domain=".concat(r)),!0===o&&a.push("secure"),NR.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 QI(e,t,n){let i=!function(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}function $I(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function eA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?$I(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$I(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const tA=e=>e instanceof jI?eA({},e):e;function nA(e,t){t=t||{};const n={};function i(e,t,n,i){return NR.isPlainObject(e)&&NR.isPlainObject(t)?NR.merge.call({caseless:i},e,t):NR.isPlainObject(t)?NR.merge({},t):NR.isArray(t)?t.slice():t}function r(e,t,n,r){return NR.isUndefined(t)?NR.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function o(e,t){if(!NR.isUndefined(t))return i(void 0,t)}function s(e,t){return NR.isUndefined(t)?NR.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(n,r,o){return o in t?i(n,r):o in e?i(void 0,n):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,n)=>r(tA(e),tA(t),0,!0)};return NR.forEach(Object.keys(eA(eA({},e),t)),(function(i){if("__proto__"===i||"constructor"===i||"prototype"===i)return;const o=NR.hasOwnProp(c,i)?c[i]:r,s=o(e[i],t[i],i);NR.isUndefined(s)&&o!==a||(n[i]=s)})),n}var iA=e=>{const t=nA({},e);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:o,headers:s,auth:a}=t;if(t.headers=s=jI.from(s),t.url=jR(QI(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),NR.isFormData(n))if(Gb.hasStandardBrowserEnv||Gb.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(NR.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach((e=>{let[n,i]=e;Di(t).call(t,n.toLowerCase())&&s.set(n,i)}))}if(Gb.hasStandardBrowserEnv&&(i&&NR.isFunction(i)&&(i=i(t)),i||!1!==i&&ZI(t.url))){const e=r&&o&&qI.read(o);e&&s.set(r,e)}return t};var rA="undefined"!=typeof XMLHttpRequest&&function(e){return new Wh((function(t,n){const i=iA(e);let r=i.data;const o=jI.from(i.headers).normalize();let s,a,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=i;function _(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let E=new XMLHttpRequest;function m(){if(!E)return;const i=jI.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders());HI((function(e){t(e),_()}),(function(e){n(e),_()}),{data:u&&"text"!==u&&"json"!==u?E.response:E.responseText,status:E.status,statusText:E.statusText,headers:i,config:e,request:E}),E=null}E.open(i.method.toUpperCase(),i.url,!0),E.timeout=i.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&&(n(new PR("Request aborted",PR.ECONNABORTED,e,E)),E=null)},E.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new PR(i,PR.ERR_NETWORK,e,E);r.event=t||null,n(r),E=null},E.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||KR;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new PR(t,r.clarifyTimeoutError?PR.ETIMEDOUT:PR.ECONNABORTED,e,E)),E=null},void 0===r&&o.setContentType(null),"setRequestHeader"in E&&NR.forEach(o.toJSON(),(function(e,t){E.setRequestHeader(t,e)})),NR.isUndefined(i.withCredentials)||(E.withCredentials=!!i.withCredentials),u&&"json"!==u&&(E.responseType=i.responseType),p&&([c,l]=XI(p,!0),E.addEventListener("progress",c)),h&&E.upload&&([a,d]=XI(h),E.upload.addEventListener("progress",a),E.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(s=t=>{E&&(n(!t||t.type?new YI(null,e,E):t),E.abort(),E=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const f=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);f&&-1===Gb.protocols.indexOf(f)?n(new PR("Unsupported protocol "+f+":",PR.ERR_BAD_REQUEST,e)):E.send(r||null)}))};var oA=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof PR?t:new YI(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>{o=null,r(new PR("timeout of ".concat(t,"ms exceeded"),PR.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}=i;return a.unsubscribe=()=>NR.asap(s),a}},sA=jh,aA=Tl;On({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=aA.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var cA=Tl,dA=tl;On({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=cA.f(this),n=dA(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}});var lA=n(sA),uA=Nv.f("asyncIterator"),hA=n(uA);function pA(e,t){this.v=e,this.k=t}function _A(e){var t,n;function i(t,n){try{var o=e[t](n),s=o.value,a=s instanceof pA;lA.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t?"return":"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}r(o.done?"return":"normal",n)}),(function(e){i("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)?i(t.key,t.arg):n=null}this._invoke=function(e,r){return new lA((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function EA(e){return function(){return new _A(e.apply(this,arguments))}}function mA(e){return new pA(e,0)}function fA(e){var t={},n=!1;function i(t,i){return n=!0,{done:!1,value:new pA(i=new lA((function(n){n(e[t](i))})),1)}}return t[void 0!==Ib&&Ab||"@@iterator"]=function(){return this},t.next=function(e){return n?(n=!1,e):i("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(n)throw n=!1,e;return i("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return n?(n=!1,e):i("return",e)}),t}_A.prototype["function"==typeof Ib&&hA||"@@asyncIterator"]=function(){return this},_A.prototype.next=function(e){return this._invoke("next",e)},_A.prototype.throw=function(e){return this._invoke("throw",e)},_A.prototype.return=function(e){return this._invoke("return",e)};var gA=n(uA);function SA(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=gA,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new TA(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function TA(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 TA=function(e){this.s=e,this.n=e.next},TA.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Wh.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Wh.reject(e):t(n.apply(this.s,arguments))}},new TA(e)}const RA=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},vA=function(){var e=EA((function*(e,t){var n,i=!1,r=!1;try{for(var o,s=SA(yA(e));i=!(o=yield mA(s.next())).done;i=!1){const e=o.value;yield*fA(SA(RA(e,t)))}}catch(e){r=!0,n=e}finally{try{i&&null!=s.return&&(yield mA(s.return()))}finally{if(r)throw n}}}));return function(t,n){return e.apply(this,arguments)}}(),yA=function(){var e=EA((function*(e){if(e[gA])return void(yield*fA(SA(e)));const t=e.getReader();try{for(;;){const{done:e,value:n}=yield mA(t.read());if(e)break;yield n}}finally{yield mA(t.cancel())}}));return function(t){return e.apply(this,arguments)}}(),CA=(e,t,n,i)=>{const r=vA(e,t);let o,s=0,a=e=>{o||(o=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return a(),void e.close();let o=i.byteLength;if(n){let e=s+=o;n(e)}e.enqueue(new Uint8Array(i))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})};function bA(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function IA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?bA(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const{isFunction:AA}=NR,wA=(e=>{let{Request:t,Response:n}=e;return{Request:t,Response:n}})(NR.global),{ReadableStream:OA,TextEncoder:NA}=NR.global,DA=function(e){try{for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return!!e(...n)}catch(e){return!1}},PA=e=>{e=NR.merge.call({skipUndefined:!0},wA,e);const{fetch:t,Request:n,Response:i}=e,r=t?AA(t):"function"==typeof fetch,o=AA(n),s=AA(i);if(!r)return!1;const a=r&&AA(OA),c=r&&("function"==typeof NA?(d=new NA,e=>d.encode(e)):async e=>new Uint8Array(await new n(e).arrayBuffer()));var d;const l=o&&a&&DA((()=>{let e=!1;const t=new n(Gb.origin,{body:new OA,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),u=s&&a&&DA((()=>NR.isReadableStream(new i("").body))),h={stream:u&&(e=>e.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!h[e]&&(h[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new PR("Response type '".concat(e,"' is not supported"),PR.ERR_NOT_SUPPORT,n)})}));const p=async(e,t)=>{const i=NR.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(NR.isBlob(e))return e.size;if(NR.isSpecCompliantForm(e)){const t=new n(Gb.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return NR.isArrayBufferView(e)||NR.isArrayBuffer(e)?e.byteLength:(NR.isURLSearchParams(e)&&(e+=""),NR.isString(e)?(await c(e)).byteLength:void 0)})(t):i};return async e=>{let{url:r,method:s,data:a,signal:c,cancelToken:d,timeout:_,onDownloadProgress:E,onUploadProgress:m,responseType:f,headers:g,withCredentials:S="same-origin",fetchOptions:T}=iA(e),R=t||fetch;f=f?(f+"").toLowerCase():"text";let v=oA([c,d&&d.toAbortSignal()],_),y=null;const C=v&&v.unsubscribe&&(()=>{v.unsubscribe()});let b;try{if(m&&l&&"get"!==s&&"head"!==s&&0!==(b=await p(g,a))){let e,t=new n(r,{method:"POST",body:a,duplex:"half"});if(NR.isFormData(a)&&(e=t.headers.get("content-type"))&&g.setContentType(e),t.body){const[e,n]=JI(b,XI(zI(m)));a=CA(t.body,65536,e,n)}}NR.isString(S)||(S=S?"include":"omit");const t=o&&"credentials"in n.prototype,c=IA(IA({},T),{},{signal:v,method:s.toUpperCase(),headers:g.normalize().toJSON(),body:a,duplex:"half",credentials:t?S:void 0});y=o&&new n(r,c);let d=await(o?R(y,T):R(r,c));const _=u&&("stream"===f||"response"===f);if(u&&(E||_&&C)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=d[t]}));const t=NR.toFiniteNumber(d.headers.get("content-length")),[n,r]=E&&JI(t,XI(zI(E),!0))||[];d=new i(CA(d.body,65536,n,(()=>{r&&r(),C&&C()})),e)}f=f||"text";let I=await h[NR.findKey(h,f)||"text"](d,e);return!_&&C&&C(),await new Wh(((t,n)=>{HI(t,n,{data:I,headers:jI.from(d.headers),status:d.status,statusText:d.statusText,config:e,request:y})}))}catch(t){if(C&&C(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new PR("Network Error",PR.ERR_NETWORK,e,y,t&&t.response),{cause:t.cause||t});throw PR.from(t,t&&t.code,e,y,t&&t.response)}}},LA=new Map,kA=e=>{let t=e&&e.env||{};const{fetch:n,Request:i,Response:r}=t,o=[i,r,n];let s,a,c=o.length,d=LA;for(;c--;)s=o[c],a=d.get(s),void 0===a&&d.set(s,a=c?new Map:PA(t)),d=a;return a};kA();const MA={http:null,xhr:rA,fetch:{get:kA}};NR.forEach(MA,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const UA=e=>"- ".concat(e),VA=e=>NR.isFunction(e)||null===e||!1===e;var xA={getAdapter:function(e,t){e=NR.isArray(e)?e:[e];const{length:n}=e;let i,r;const o={};for(let s=0;s<n;s++){let n;if(i=e[s],r=i,!VA(i)&&(r=MA[(n=String(i)).toLowerCase()],void 0===r))throw new PR("Unknown adapter '".concat(n,"'"));if(r&&(NR.isFunction(r)||(r=r.get(t))))break;o[n||"#"+s]=r}if(!r){const e=Object.entries(o).map((e=>{let[t,n]=e;return"adapter ".concat(t," ")+(!1===n?"is not supported by the environment":"is not available in the build")}));let t=n?e.length>1?"since :\n"+e.map(UA).join("\n"):" "+UA(e[0]):"as no adapter specified";throw new PR("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r},adapters:MA};function FA(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new YI(null,e)}function BA(e){FA(e),e.headers=jI.from(e.headers),e.data=WI.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return xA.getAdapter(e.adapter||MI.adapter,e)(e).then((function(t){return FA(e),t.data=WI.call(e,e.transformResponse,t),t.headers=jI.from(t.headers),t}),(function(t){return KI(t)||(FA(e),t&&t.response&&(t.response.data=WI.call(e,e.transformResponse,t.response),t.response.headers=jI.from(t.response.headers))),Wh.reject(t)}))}const GA="1.13.6",jA={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{jA[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const WA={};jA.transitional=function(e,t,n){function i(e,t){return"[Axios v"+GA+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,o)=>{if(!1===e)throw new PR(i(r," has been removed"+(t?" in "+t:"")),PR.ERR_DEPRECATED);return t&&!WA[r]&&(WA[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,o)}},jA.spelling=function(e){return(t,n)=>(console.warn("".concat(n," is likely a misspelling of ").concat(e)),!0)};var KA={assertOptions:function(e,t,n){if("object"!=typeof e)throw new PR("options must be an object",PR.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const o=i[r],s=t[o];if(s){const t=e[o],n=void 0===t||s(t,o,e);if(!0!==n)throw new PR("option "+o+" must be "+n,PR.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new PR("Unknown option "+o,PR.ERR_BAD_OPTION)}},validators:jA};const YA=KA.validators;let HA=class{constructor(e){this.defaults=e||{},this.interceptors={request:new WR,response:new WR}}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 n=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+n):e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=nA(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&KA.assertOptions(n,{silentJSONParsing:YA.transitional(YA.boolean),forcedJSONParsing:YA.transitional(YA.boolean),clarifyTimeoutError:YA.transitional(YA.boolean),legacyInterceptorReqResOrdering:YA.transitional(YA.boolean)},!1),null!=i&&(NR.isFunction(i)?t.paramsSerializer={serialize:i}:KA.assertOptions(i,{encode:YA.function,serialize:YA.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),KA.assertOptions(t,{baseUrl:YA.spelling("baseURL"),withXsrfToken:YA.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&NR.merge(r.common,r[t.method]);r&&NR.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete r[e]})),t.headers=jI.concat(o,r);const s=[];let a=!0;this.interceptors.request.forEach((function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;a=a&&e.synchronous;const n=t.transitional||KR;n&&n.legacyInterceptorReqResOrdering?s.unshift(e.fulfilled,e.rejected):s.push(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=[BA.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=BA.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 jR(QI((e=nA(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};NR.forEach(["delete","get","head","options"],(function(e){HA.prototype[e]=function(t,n){return this.request(nA(n||{},{method:e,url:t,data:(n||{}).data}))}})),NR.forEach(["post","put","patch"],(function(e){function t(t){return function(n,i,r){return this.request(nA(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}HA.prototype[e]=t(),HA.prototype[e+"Form"]=t(!0)}));var XA=HA;class JA{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 n=this;this.promise.then((e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const i=new Wh((e=>{n.subscribe(e),t=e})).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e((function(e,i,r){n.reason||(n.reason=new YI(e,i,r),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}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 JA((function(t){e=t}));return{token:t,cancel:e}}}var zA=JA;const ZA={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(ZA).forEach((e=>{let[t,n]=e;ZA[n]=t}));var qA=ZA;const QA=function e(t){const n=new XA(t),i=xT(XA.prototype.request,n);return NR.extend(i,XA.prototype,n,{allOwnKeys:!0}),NR.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(nA(t,n))},i}(MI);QA.Axios=XA,QA.CanceledError=YI,QA.CancelToken=zA,QA.isCancel=KI,QA.VERSION=GA,QA.toFormData=VR,QA.AxiosError=PR,QA.Cancel=QA.CanceledError,QA.all=function(e){return Wh.all(e)},QA.spread=function(e){return function(t){return e.apply(null,t)}},QA.isAxiosError=function(e){return NR.isObject(e)&&!0===e.isAxiosError},QA.mergeConfig=nA,QA.AxiosHeaders=jI,QA.formToJSON=e=>LI(NR.isHTMLForm(e)?new FormData(e):e),QA.getAdapter=xA.getAdapter,QA.HttpStatusCode=qA,QA.default=QA;var $A=QA;const ew=()=>{};function tw(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:ew};return e.promise=new Wh(((t,n)=>{e.resolve=n=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(n),e.value=n)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,n(t))}})),e}const nw=new Map,iw=new Map,rw=new Map;let ow=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}({}),sw=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 aw=new pT;let cw=aw.getResult(),dw=null;function lw(e){if(!dw){e&&aw.setUA(e),cw=aw.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return sw.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return sw.CHROME;case"Safari":case"Mobile Safari":return sw.SAFARI;case"Edge":return sw.EDGE;case"Firefox":return sw.FIREFOX;case"QQ":case"QQBrowser":return sw.QQ;case"Opera":return sw.OPERA;case"WeChat":return sw.WECHAT;default:return e.browser.name||""}}(cw),n=uw(cw),i=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(cw),r=cw.os.version,o=uw(cw,!1),s=cw.device.type;if(!(t&&n&&i&&r))return{name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s};dw={name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s}}return dw}function uw(e){let t,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",n?t.split(".")[0]:t}function hw(){return lw().os}function pw(){const e=lw();return"".concat(e.os," ").concat(e.osVersion)}function _w(){const e=lw();return!!("WebKit"===cw.engine.name&&e.os===ow.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==sw.SAFARI||Rw()&&e.name!==sw.SAFARI)}function Ew(){return lw().name===sw.CHROME}function mw(){return lw().name===sw.SAFARI}function fw(){const e=lw();if(e.name!==sw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}function gw(){const e=lw();if(e.name!==sw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}function Sw(){return lw().name===sw.EDGE}function Tw(){return lw().name===sw.FIREFOX}function Rw(){return lw().os===ow.IOS}function vw(e){const t=lw();return!(t.name!==sw.CHROME||!t.osVersion)&&Number(t.version)>=e}function yw(e){const t=lw();return!(t.name!==sw.CHROME||!t.osVersion)&&Number(t.version)<e}function Cw(e,t,n){const i=lw();return!(i.name!==e||!i.osVersion)&&(n?Number(i.version)>=t&&Number(i.version)<=n:Number(i.version)===t)}function bw(e){const t=lw();return!(t.name!==sw.EDGE||!t.osVersion)&&Number(t.version)>=e}function Iw(e){const t=lw();return!(t.name!==sw.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function Aw(e){const t=lw();return!(t.name!==sw.SAFARI||!t.osVersion)&&Number(t.version)>=e}function ww(e,t,n){const i=lw();if(i.os!==ow.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?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 Ow(e,t,n){const i=lw();if(i.os!==ow.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?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 Nw(e,t,n){const i=lw();if(i.name!==sw.SAFARI||!i.osVersion||!i.browserVersion)return!1;const r=i.browserVersion.split(".");return n?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 Dw(e){const t=lw();return!(t.name!==sw.OPERA||!t.osVersion)&&Number(t.version)>=e}function Pw(){const e=lw();if(e.os!==ow.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function Lw(){const e=lw();if(e.os!==ow.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function kw(){const e=lw();if(e.os!==ow.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function Mw(){const e=lw();if(e.os!==ow.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function Uw(){return mw()&&navigator.maxTouchPoints>0}function Vw(){return lw().name===sw.WECHAT}function xw(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function Fw(){const e=hw();return function(){const{deviceType:e}=lw();return"mobile"===e||"tablet"===e}()||e===ow.ANDROID||e===ow.IOS||e===ow.HARMONY_OS}function Bw(){const e=lw();return e.name!==sw.EDGE&&e.name!==sw.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function Gw(){return hw()===ow.ANDROID}function jw(){const e=lw();return Gw()&&(e.name===sw.CHROME||e.name===sw.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function Ww(){var e;return!!Di(e=window.navigator.userAgent).call(e,"AgoraWebView")}function Kw(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Hw(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Yw(Object(n),!0).forEach((function(t){Kw(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Yw(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Xw=function(e){return e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.PB_ERROR="PB_ERROR",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_ERROR="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}({}),Jw=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0;super(t),Kw(this,"code",void 0),Kw(this,"message",void 0),Kw(this,"data",void 0),Kw(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=n}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 zw(e,t){if("boolean"!=typeof e)throw new Jw(Xw.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Zw(e,t,n){if(!Di(n).call(n,e))throw new Jw(Xw.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(n)))}function qw(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<n||e>i||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new Jw(Xw.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(n,", ").concat(i,"]. integer only"))}function Qw(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new Jw(Xw.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&qw(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&qw(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&qw(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&qw(e.ideal,"".concat(t,".ideal"),1,1/0)}else qw(e,t,1,1/0)}function $w(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=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(Xw.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!nO(e,n,i,r))throw new Jw(Xw.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(n,",").concat(i,"].").concat(r?" ASCII characters only.":""))}function eO(e,t){if(!Array.isArray(e))throw new Jw(Xw.INVALID_PARAMS,"".concat(t," should be an array"))}function tO(e){return null==e}function nO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=n&&e.length>=t&&(!i||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n<0||n>255)return!1}return!0}(e))}function iO(e,t,n){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,n);const i=e.getUint32(t,n),r=e.getUint32(t+4,n),o=Number(!!n),s=Number(!n);return BigInt(i*s+r*o)<<BigInt(32)|BigInt(i*o+r*s)}function rO(e,t,n,i){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,n,i);const r=Number(n>>BigInt(32)),o=Number(n&BigInt(4294967295));i?(e.setUint32(t+4,r,i),e.setUint32(t,o,i)):(e.setUint32(t,r,i),e.setUint32(t+4,o,i))}var oO=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(oO||{}),sO=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(sO||{});const aO=new class{constructor(){Kw(this,"_clientSize",null),Kw(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),Kw(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),Kw(this,"getStyle",(e=>window.getComputedStyle(e,null))),Kw(this,"checkCssVisibleProperty",(e=>{var t;let n=!0;const i=this.getStyle(e),{display:r,visibility:o,opacity:s,filter:a}=i;return("none"===r||Di(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(n=!1),!!n&&(a&&a.split(" ").filter((e=>{var t;const n=e.split("(")[0];return Di(t=["brightness","blur","opacity"]).call(t,n)})).map((e=>{const[t,n]=e.split(/\(|\)/);return[t,Number(n.match(/^[0-9\.]+/))]})).forEach((e=>{const[t,i]=e;switch(t){case"brightness":(i<.1||i>3)&&(n=!1);break;case"blur":i>3&&(n=!1);break;case"opacity":i<.1&&(n=!1)}})),n)})),Kw(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let n=!0,i=!0;const r=e=>t(e);let o=e;for(;o&&i;)r(o)||(n=!1,i=!1),o=o.parentElement,o||(i=!1);return n})),Kw(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),Kw(this,"getSizeAboutClient",(e=>{const{width:t,height:n,left:i,right:r,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:n,left:i,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),Kw(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:n}=this._clientSize;return this.checkSizeIsVisible(e,t,n)})),Kw(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),Kw(this,"checkCoverForAPoint",((e,t,n)=>{const i=this.elementFromPoint(e,t);return null!==i&&i!==n})),Kw(this,"getPointPositionList",(()=>{const{width:e,height:t,left:n,top:i}=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=(n*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(i*a+(0===t?.1:4===t?(o*t*a-1e5)/a:o*t)*a)/a;s.push({x:c,y:d})}return[...s]})),Kw(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),Kw(this,"checkSizeIsVisible",((e,t,n)=>(e>50||n/e<=10)&&(t>50||n/t<=10))),Kw(this,"checkSizeOfPartInClient",(()=>{const{left:e,right:t,top:n,bottom:i,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,n<0)d=0;else{if(!(n<r))return!1;d=n}if(i<0)return!1;l=i<r?i:r;const u=c-a,h=l-d;return this.checkSizeIsVisible(u,h,s)})),Kw(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),Kw(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(oO.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(oO.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(oO.SIZE)}}return this.returnHiddenResult(oO.STYLE)}return this.returnHiddenResult(sO.UNMOUNTED)}return this.returnHiddenResult(sO.INVALID_HTML_ELEMENT)})),Kw(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function cO(e){return(new TextEncoder).encode(e)}const dO=function(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n};const lO=async e=>function(e,t){let n="";return new Uint8Array(e).forEach((e=>{n+=e.toString(t).padStart(2,"0")})),n}(await crypto.subtle.digest("SHA-256",cO(e)),16);let uO=class{constructor(){Kw(this,"_events",{}),Kw(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 n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const n=this._events[e],i=this._indexOfListener(n,t);-1!==i&&n.splice(i,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 n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(let n=0;n<t.length;n+=1){const r=t[n];r.once&&this.off(e,r.listener),r.listener.apply(this,i||[])}}safeEmit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,n)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let n=e.length;for(;n--;)if(e[n].listener===t)return n;return-1}};let hO=null;function pO(){if(hO)return hO;if(window.electron)return hO=window.electron;if(!window.require)return null;try{return hO=window.require("electron"),hO}catch(e){return null}}let _O=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.MISMATCH_ICE_PARAMETERS="mismatchIceParameters",e.VOS_FALLBACK_CN="vosFallbackCN",e.DATACHANNEL_FAILBACK="datachannelFailback",e}({}),EO=function(e){return e.TRACER="tracer",e}({});function mO(e){return qw(e.timeout,"config.timeout",0,1e5),qw(e.timeoutFactor,"config.timeoutFactor",0,100,!1),qw(e.maxRetryCount,"config.maxRetryConfig",0,1/0),qw(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let fO=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}({}),gO=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 SO(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 TO(e){return $w(e.turnServerURL,"turnServerURL"),$w(e.username,"username"),$w(e.password,"password"),e.udpport&&qw(e.udpport,"udpport",1,99999,!0),e.forceturn&&zw(e.forceturn,"forceturn"),e.security&&zw(e.security,"security"),e.tcpport&&qw(e.tcpport,"tcpport",1,99999,!0),!0}let RO=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 vO(e){return void 0!==e.level&&Zw(e.level,"level",[1,2,3]),void 0!==e.delay&&qw(e.delay,"delay",0,3e3,!0),!0}let yO=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.USER_LIST="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}({}),CO=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}),bO=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}({}),IO=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),AO=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function wO(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return 0===e.getListeners(t).length?Wh.reject(new Jw(Xw.UNEXPECTED_ERROR,"can not emit promise")):new Wh(((n,r)=>{e.emit(t,...i,n,r)}))}function OO(e,t){if(0===e.getListeners(t).length)return Wh.resolve();for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return wO(e,t,...i)}function NO(e,t){if(0===e.getListeners(t).length)return null;for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return DO(e,t,...i)}function DO(e,t){let n=null,i=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=>{n=e}),(e=>{i=e})),null!==i)throw i;if(null===n)throw new Jw(Xw.UNEXPECTED_ERROR,"handler is not sync");return n}const PO=new class extends uO{set networkState(e){this.emit(AO.NETWORK_STATE_CHANGE,e,this._networkState),e===IO.ONLINE?this.emit(AO.ONLINE):e===IO.OFFLINE&&(this.onlineWaiter=new Wh((e=>{this.once(AO.ONLINE,(()=>{this.onlineWaiter=void 0,e(IO.ONLINE)}))})),this.emit(AO.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===IO.ONLINE}constructor(){super(),Kw(this,"_moduleName","network-indicator"),Kw(this,"_networkState",IO.ONLINE),Kw(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=IO.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=IO.OFFLINE}))}},LO=[];for(let e=0;e<256;++e)LO.push((e+256).toString(16).slice(1));const kO="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let MO;const UO=new Uint8Array(16);function VO(){return kO?kO():function(e,t,n){var i,r,o,s;const a=null!==(i=null!==(r=(e=e||{}).random)&&void 0!==r?r:null===(o=(s=e).rng)||void 0===o?void 0:o.call(s))&&void 0!==i?i:function(){if(!MO){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");MO=crypto.getRandomValues.bind(crypto)}return MO(UO)}();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((n=n||0)<0||n+16>t.length)throw new RangeError("UUID byte range ".concat(n,":").concat(n+15," is out of buffer bounds"));for(let e=0;e<16;++e)t[n+e]=a[e];return t}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(LO[e[t+0]]+LO[e[t+1]]+LO[e[t+2]]+LO[e[t+3]]+"-"+LO[e[t+4]]+LO[e[t+5]]+"-"+LO[e[t+6]]+LO[e[t+7]]+"-"+LO[e[t+8]]+LO[e[t+9]]+"-"+LO[e[t+10]]+LO[e[t+11]]+LO[e[t+12]]+LO[e[t+13]]+LO[e[t+14]]+LO[e[t+15]]).toLowerCase()}(a)}(e,t,undefined);var e,t}function xO(e,t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}function FO(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function BO(e){void 0!==Wh?Wh.resolve().then(e):setTimeout(e,0)}function GO(e){return JSON.parse(JSON.stringify(e))}function jO(e){try{return GO(e)}catch(t){return e}}const WO={};function KO(e,t){WO[t]||(WO[t]=!0,e())}function YO(e){const t=window.atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function HO(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}function XO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=(new TextEncoder).encode(e);if(n.length>t)n=n.slice(0,t);else if(n.length<t){const e=new Uint8Array(t);e.set(n),n=e}return n}function JO(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=zi(t).call(t,((e,t)=>e+t.length),0),r=new Uint8Array(new ArrayBuffer(i));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function zO(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function ZO(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?zO(e):e.size})),t+138}function qO(e){const t=new Jw(Xw.TIMEOUT,"timeout");return new Wh(((n,i)=>{window.setTimeout((()=>i(t)),e)}))}function QO(e){return new Wh((t=>{window.setTimeout(t,e)}))}function $O(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const n=Math.random().toString(16).substr(2,e).toLowerCase();return n.length===e?"".concat(t).concat(n):"".concat(t).concat(n)+$O(e-n.length,"")}function eN(){let e,t=!1;try{var n;e=aT(n=VO()).call(n,"-","")}catch(e){t=!0}return!t&&e&&32===e.length||(e=$O(32,"")),e.toUpperCase()}const tN=()=>{},nN=new class{constructor(){Kw(this,"fnMap",new Map)}throttleByKey(e,t,n,i){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!==n){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)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:s,args:o,skipFn:i})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,Hw(Hw({},r),{},{fn:e,args:o,skipFn:i}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:r,args:o,skipFn:i})}}},iN=nN.throttleByKey.bind(nN);function rN(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function oN(e,t){if(!rN(e)||!rN(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 n=[...e];for(let i=0;i<t.length;i++)n[i]=oN(e[i],t[i]);return n}{const n=Hw({},e);for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)?n[i]=oN(e[i],t[i]):n[i]=t[i]);return n}}function sN(e,t){let n=[0];if(t&&(n=new Array(t).fill(0)),0===e)return n;let i=0;for(;e>0&&(n[i]=255&e,e>>=8,i++,!t||i!==t););return n}function aN(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function cN(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function dN(e){return zi(e).call(e,((e,t)=>e+t),0)}function lN(e){const t="0123456789abcdef";function n(e){let n,i="";for(n=0;n<=3;n++)i+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return i}function i(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,n,r,o,s){return i(function(e,t){return e<<t|e>>>32-t}(i(i(t,e),i(r,s)),o),n)}function o(e,t,n,i,o,s,a){return r(t&n|~t&i,e,t,o,s,a)}function s(e,t,n,i,o,s,a){return r(t&i|n&~i,e,t,o,s,a)}function a(e,t,n,i,o,s,a){return r(t^n^i,e,t,o,s,a)}function c(e,t,n,i,o,s,a){return r(n^(t|~i),e,t,o,s,a)}const d=function(e){let t;const n=1+(e.length+8>>6),i=new Array(16*n);for(t=0;t<16*n;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[16*n-2]=8*e.length,i}(e);let l,u,h,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)u=E,h=m,p=f,_=g,E=o(E,m,f,g,d[l+0],7,-680876936),g=o(g,E,m,f,d[l+1],12,-389564586),f=o(f,g,E,m,d[l+2],17,606105819),m=o(m,f,g,E,d[l+3],22,-1044525330),E=o(E,m,f,g,d[l+4],7,-176418897),g=o(g,E,m,f,d[l+5],12,1200080426),f=o(f,g,E,m,d[l+6],17,-1473231341),m=o(m,f,g,E,d[l+7],22,-45705983),E=o(E,m,f,g,d[l+8],7,1770035416),g=o(g,E,m,f,d[l+9],12,-1958414417),f=o(f,g,E,m,d[l+10],17,-42063),m=o(m,f,g,E,d[l+11],22,-1990404162),E=o(E,m,f,g,d[l+12],7,1804603682),g=o(g,E,m,f,d[l+13],12,-40341101),f=o(f,g,E,m,d[l+14],17,-1502002290),m=o(m,f,g,E,d[l+15],22,1236535329),E=s(E,m,f,g,d[l+1],5,-165796510),g=s(g,E,m,f,d[l+6],9,-1069501632),f=s(f,g,E,m,d[l+11],14,643717713),m=s(m,f,g,E,d[l+0],20,-373897302),E=s(E,m,f,g,d[l+5],5,-701558691),g=s(g,E,m,f,d[l+10],9,38016083),f=s(f,g,E,m,d[l+15],14,-660478335),m=s(m,f,g,E,d[l+4],20,-405537848),E=s(E,m,f,g,d[l+9],5,568446438),g=s(g,E,m,f,d[l+14],9,-1019803690),f=s(f,g,E,m,d[l+3],14,-187363961),m=s(m,f,g,E,d[l+8],20,1163531501),E=s(E,m,f,g,d[l+13],5,-1444681467),g=s(g,E,m,f,d[l+2],9,-51403784),f=s(f,g,E,m,d[l+7],14,1735328473),m=s(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=i(E,u),m=i(m,h),f=i(f,p),g=i(g,_);return n(E)+n(m)+n(f)+n(g)}let uN=1,hN=console,pN=class{static setLogger(e){hN=e}constructor(e,t){Kw(this,"id",void 0),Kw(this,"lockingPromise",Wh.resolve()),Kw(this,"locks",0),Kw(this,"name",""),Kw(this,"lockId",void 0),this.lockId=uN++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const n=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),i="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");hN.debug("".concat(n," ").concat(i))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const n=new Wh((n=>{t=()=>{this.locks-=1,this.logger("unlocked",e),n()}})),i=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>n)),i}};function _N(e,t){return function(n,i,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const n=this[t];if(!n)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await n.lock("From ".concat(e,".").concat(i));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 EN={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function mN(e,t){const n=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,n)}function fN(e,t,n,i){const r=Object.assign({},EN,i);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(i,o)=>{t=t||(()=>!1),n=n||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new Jw(Xw.OPERATION_ABORTED));try{const n=await e();if(!t(n,c))return i(n);if(c+1===r.maxRetryCount)return i(n);await s()}catch(e){if(!n(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}}));return c.cancel=()=>a=!0,c}let gN,SN=class{constructor(e){Kw(this,"input",[]),Kw(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:zi(e=this.input).call(e,((e,t)=>e+t))/this.input.length}},TN=0,RN=0;function vN(e,t,n,i){return new Wh(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),TN+=zO(t.data)):n&&(t.data.size?TN+=t.data.size:t.data instanceof FormData?TN+=ZO(t.data):TN+=zO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,$A.request(t).then((e=>{"string"==typeof e.data?RN+=zO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?RN+=e.data.byteLength:RN+=zO(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{$A.isCancel(e)?o(new Jw(Xw.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new Jw(Xw.NETWORK_TIMEOUT,e.message)):e.response?o(new Jw(Xw.NETWORK_RESPONSE_ERROR,e.response.status)):o(new Jw(Xw.NETWORK_ERROR,e.message))}))}))}async function yN(e,t){const n=new Blob([t.data],{type:"buffer"});return await vN(e,Hw(Hw({},t),{},{data:n,headers:{"Content-Type":"application/octet-stream"}}),!0)}const CN=()=>void 0!==window.isSecureContext;function bN(e){if(Array.isArray(e))return e.map((e=>e));if(!IN(e))return e;const t={};for(const n in e){const i=e[n];IN(i)||Array.isArray(i)?t[n]=bN(i):t[n]=i}return t}function IN(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let AN=class{constructor(e){Kw(this,"input",[]),Kw(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 wN={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},ON={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:wN,remoteCandidate:wN},updateInterval:0},NN={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},DN={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},PN={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},LN={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 kN=class{constructor(e,t){Kw(this,"onFirstVideoReceived",void 0),Kw(this,"onFirstVideoDecoded",void 0),Kw(this,"onFirstAudioReceived",void 0),Kw(this,"onFirstVideoDecodedTimeout",void 0),Kw(this,"onFirstAudioDecoded",void 0),Kw(this,"onSelectedLocalCandidateChanged",void 0),Kw(this,"onSelectedRemoteCandidateChanged",void 0),Kw(this,"videoIsReady",!1),Kw(this,"videoIsReady2",{}),Kw(this,"pc",void 0),Kw(this,"options",void 0),Kw(this,"intervalTimer",void 0),Kw(this,"stats",bN(ON)),Kw(this,"isFirstVideoReceived",{}),Kw(this,"isFirstVideoDecoded",{}),Kw(this,"isFirstAudioReceived",{}),Kw(this,"isFirstAudioDecoded",{}),Kw(this,"isFirstVideoDecodedTimeout",{}),Kw(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:Hw({},wN),remote:Hw({},wN)})}))}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,n=["videoSend","audioSend","videoRecv","audioRecv"];let i=0,r=0,o=0,s=0;for(const a of n)e[a].forEach(((e,n)=>{if(!this.lossRateWindowStats[t-1][a][n]||!this.lossRateWindowStats[0][a][n])return;const c=this.lossRateWindowStats[t-1][a][n].packets-this.lossRateWindowStats[0][a][n].packets,d=this.lossRateWindowStats[t-1][a][n].packetsLost-this.lossRateWindowStats[0][a][n].packetsLost;"videoSend"===a||"audioSend"===a?(i+=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=i<=0||o<=0?0:o/(i+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},MN=class extends kN{constructor(){super(...arguments),Kw(this,"_stats",ON),Kw(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=bN(ON);const n=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(n);const i=t.find((e=>"VideoBwe"===e.type));i&&this.processBandwidthStats(i),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 n=Di(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(n?"send":"recv")){case"video_send":{const t=bN(DN);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=bN(NN),n=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),n){const i=n.stats,r=Date.now()-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.framesDecodeInterval,t.framesDecodeCount>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.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<n.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:Hw({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=bN(LN);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=bN(PN);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 n={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t.push(n)})),t}},UN=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),VN=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}({}),xN=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}({}),FN=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 BN=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(BN||{});function GN(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:BN.kNone;if(!t)return;const o=Number(t[n]);if("number"!=typeof o)return;const s=Number(t[i]);if("number"!=typeof s)return;if(!e)return s?o/s*r:void 0;const a=Number(e[n]);if("number"!=typeof a)return;const c=Number(e[i]);if("number"!=typeof c)return;const d=s-c;return d?(o-a)/d*r:void 0}let jN=class extends kN{constructor(){super(...arguments),Kw(this,"_stats",ON),Kw(this,"report",void 0),Kw(this,"lastDecodeVideoReceiverStats",new Map),Kw(this,"lastVideoFramesRecv",new Map),Kw(this,"lastVideoFramesSent",new Map),Kw(this,"lastVideoFramesDecode",new Map),Kw(this,"lastVideoFramesOutput",new Map),Kw(this,"lastVideoJBDelay",new Map),Kw(this,"lastAudioJBDelay",new Map),Kw(this,"mediaBytesSent",new Map),Kw(this,"mediaBytesRetransmit",new Map),Kw(this,"mediaBytesTargetEncode",new Map),Kw(this,"lastDecodeAudioReceiverStats",new Map),Kw(this,"lastAudioConcealment",new Map),Kw(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=bN(ON),this.report.forEach((e=>{switch(e.type){case FN.OUTBOUND:case FN.INBOUND:{const t=e.mediaType||e.kind,n=!t&&"frameWidth"in e,i=!t&&!("frameWidth"in e);e.type===FN.OUTBOUND?"audio"===t||i?this.processAudioOutboundStats(e):("video"===t||n)&&this.processVideoOutboundStats(e):e.type===FN.INBOUND&&("audio"===t||i?this.processAudioInboundStats(e):("video"===t||n)&&this.processVideoInboundStats(e));break}case FN.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case FN.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:Hw({},wN),remote:Hw({},wN)};return e.forEach((n=>{let i;if(n.type===FN.TRANSPORT&&(i=e.get(n.selectedCandidatePairId)),n.type===FN.CANDIDATE_PAIR&&n.selected&&(i=n),i){const n=(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(i.localCandidateId){const r=e.get(i.localCandidateId);r&&n(t.local,r)}if(i.remoteCandidateId){const r=e.get(i.remoteCandidateId);r&&n(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===FN.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===FN.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===FN.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(Hw({},t),Hw({},this.stats.selectedCandidatePair.localCandidate)),e.type===FN.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(Hw({},t),Hw({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=bN(LN),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 n=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=GN(n,t,"totalProcessingDelay","jitterBufferEmittedCount",BN.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,n,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,Hw({},t))}calculateAudioFreeze(e,t,n){const i=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=i){const r=i.lts,o=n.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=i.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&&(i.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*h)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*h)),p=i.plc80+1);let _=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>u&&(i.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*h)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*h)),_=i.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:n.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=bN(NN),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 n=this.lastDecodeVideoReceiverStats.get(t.ssrc),i=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,n=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,n),this.isFirstVideoDecoded[t.ssrc]=!0}if(n){const i=n.stats,r=o-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.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>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.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<i.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(n.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-n.qpSum)/(e.framesDecoded-n.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=GN(null==n?void 0:n.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=GN(null==n?void 0:n.stats,t,"totalProcessingDelay","framesDecodeCount",BN.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=GN(null==n?void 0:n.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",BN.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=GN(null==n?void 0:n.stats,t,"totalInterFrameDelay","framesDecodeCount",BN.kMillisecondsFromSeconds),i&&o-i.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-i.count)/((o-i.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):i?t.decodeFrameRate=i.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)),"boolean"==typeof e.powerEfficientDecoder&&(t.powerEfficientDecoder=e.powerEfficientDecoder?1:0),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:Hw({},t),lts:n?n.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=bN(DN),this._stats.videoSend.push(t));const n=this.mediaBytesSent.get(e.ssrc);if(n)n.add(e.bytesSent);else{const t=new AN(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 AN(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 AN(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 n=this.lastEncoderMs.get(e.ssrc);if(!n||n.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const i=e.framesEncoded-n.lastFrameCount,r=e.totalEncodeTime-n.lastEncoderTime;t.avgEncodeMs=1e3*r/i}}if(e.framesEncoded&&e.qpSum){const n=this.lastEncoderMs.get(e.ssrc);!n||n.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-n.lastQpSum)/(e.framesEncoded-n.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)),"boolean"==typeof e.powerEfficientEncoder&&(t.powerEfficientEncoder=e.powerEfficientEncoder?1:0),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,FN.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=bN(PN),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 n=this.findRemoteStatsId(e.ssrc,FN.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,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 n;const i=Array.from(Qh(n=this.report).call(n)).find((n=>n.type===t&&n.ssrc===e));return i?i.id:null}processVideoMediaSource(e,t){const n=this.report.get(e);n&&n.width&&n.height&&n.framesPerSecond&&(t.inputFrame={width:n.width,height:n.height,frameRate:n.framesPerSecond})}processAudioMediaSource(e,t){const n=this.report.get(e);n&&(t.inputLevel=n.audioLevel)}processVideoTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null==a?void 0:a.framesSent)&&void 0!==i?i: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(n.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:0})}n.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,n){var i,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(i=null==c?void 0:c.framesReceived)&&void 0!==i?i: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(n.ssrc),t=Date.now();n.framesReceivedCount=d;let i=0;e&&t-e.lts>=800?(i=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:i})):e?i=e.rate:this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:0}),n.receivedFrame={width:l||0,height:u||0,frameRate:i||0},n.decodedFrame={width:l||0,height:u||0,frameRate:n.decodeFrameRate||0},n.outputFrame={width:l||0,height:u||0,frameRate:n.outputFrameRate||n.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=p-e.jitterBufferEmittedCount;i>0&&(t=1e3*(h-e.jitterBufferDelay)/i),n.jitterBufferMs=t,n.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(n.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:n.currentDelayMs})}}processAudioTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==i?i:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;n.aecReturnLoss=c,n.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,n){var i,r,o,s,a,c,d,l,u;const h=t?this.report.get(t):void 0,p=null!==(i=null==h?void 0:h.removedSamplesForAcceleration)&&void 0!==i?i: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,g=null!==(c=null==h?void 0:h.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,S=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 _&&(n.totalSamplesReceived=_),"number"==typeof T&&(n.silentConcealedSamples=T),"number"==typeof R&&(n.concealmentEvents=R),"number"==typeof S&&(n.concealedSamples=S),p&&_&&(n.accelerateRate=p/_),E&&m){const e=this.lastAudioJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=m-e.jitterBufferEmittedCount;i>0&&(t=1e3*(E-e.jitterBufferDelay)/i),n.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(n.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:m,jitterBufferMs:n.jitterBufferMs})}n.outputLevel=f;let v=1920;g&&_&&(v=_/g/50,n.receivedFrames=Math.round(_/v)),S&&(n.droppedFrames=Math.round(S/v))}processRemoteInboundStats(e,t){const n=this.report.get(e);n&&(t.packetsLost=n.packetsLost,n.roundTripTime&&(t.rttMs=1e3*n.roundTripTime),n.jitter&&(t.jitterMs=1e3*n.jitter),n.timestamp&&(t.timestamp=n.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const n=t.mimeType.match(/\/(.*)$/);return n&&n[1]?n[1]:""}updateSendBitrate(){let e=0,t=null,n=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{n=null===n?e.diffMean():n+e.diffMean()}));const i=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*i/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==n&&(this._stats.bitrate.targetEncoded=8*n/(this.options.updateInterval/1e3))}},WN=class extends kN{updateStats(){return Wh.resolve()}};function KN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,i=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 MN(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new jN(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,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 jN(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new WN(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r})}const YN="websdk_ng_install_id";function HN(){try{if(iD("INSTALL_ID"))return iD("INSTALL_ID");let e=window.localStorage.getItem(YN);return e||(e=eN(),window.localStorage.setItem(YN,e)),nD("INSTALL_ID",e),e}catch(e){return}}const XN=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],n=t[2];return"".concat(e,".").concat(n)}return"4.0.0.999"}("4.24.3"),JN=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let zN=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const ZN=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const i=n.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=i,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=ZN;const qN={ENABLE_PUBLISHED_USER_LIST:!0,ENABLE_USER_LIST:!1,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,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"],ENABLE_JOIN_V4:!1,ENABLE_AP_COMPRESS:!0},QN={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},$N="v4.24.3-0-g6cc16b0bb-dirty(3/16/2026, 4:35:55 PM)",eD={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,MAX_CONFIG_RETRY:10,ENABLE_CONFIG_RESTORE:!1,CONFIG_RESTORE_ERROR_API:["createClient","Client.join"],CONFIG_ERROR_MONITOR:["INVALID_OPERATION","UNEXPECTED_ERROR"],BLOCKED_CONFIG_MAX_TIME:864e5,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:!0,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:!0,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,ENABLE_SDP_ENDPOINT_LOG:!1,REMOTE_VIDEO_FREEZE_TIME_VERSION:2},tD=Hw(Hw(Hw(Hw({},eD),{},{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"],SDP_ENDPOINT_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],SDP_ENDPOINT_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:QN,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},qN),{},{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,PRE_SUB_NUM:1,DC_IN_ESM:!0,PRE_PLAYOUT_DELAY_HINT:void 0});function nD(e,t,n){var i,r,o;Di(i=Object.keys(tD)).call(i,e)&&(!n&&Di(r=Object.keys(oD)).call(r,e)||(tD[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(tD.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,tD.USE_NEW_NETWORK_CONFIG=o,o&&(tD.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],tD.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],tD.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],tD.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],tD.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",tD.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",tD.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(tD.ENABLE_INSTANT_VIDEO=!0,tD.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(tD.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(tD.NEW_TURN_MODE||(tD.NEW_TURN_MODE=4))))}function iD(e){if("TURN_DOMAINS"===e){const e=tD.TURN_DOMAINS;return Di(e).call(e,iD("TURN_DOMAIN"))?e:[iD("TURN_DOMAIN")].concat(e)}return tD[e]}JN||(tD.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],tD.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],tD.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],tD.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],tD.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],tD.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],tD.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",tD.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",tD.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",tD.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",tD.AREAS=["NORTH_AMERICA","OVERSEA"]);let rD=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const oD={};var sD=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}(sD||{});let aD=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 cD=128,dD=96,lD=1e3,uD=10;let hD=0;var pD=(()=>{var e={8:(e,t,n)=>{n.r(t),n.d(t,{Parser:()=>v,Printer:()=>A,parse:()=>D,print:()=>P});const i="\n",r="".concat("\r").concat(i),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 g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function S(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?g(Object(n),!0).forEach((function(t){T(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,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 n=t;for(;n<e.length;){const t=e[n];if("\0"===t||"\r"===t||t===i)break;n+=1}if(n-t==0)throw new Error("Invalid text, at ".concat(e));return n}consumeUnicastAddress(e,t,n){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,n){let i=t;for(;n(e[i]);)i++;if(i-t==0)throw new Error("Invalid rule at ".concat(t,"."));return i}consumeSpace(e,t){if(e[t]===o)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let n=t;for(let t=0;t<4;t++)if(n=this.consumeDecimalUChar(e,n),3!==t){if("."!==e[n])throw new Error("Invalid IP4 address.");n++}return n}consumeDecimalUChar(e,t){let n=t;for(let t=0;t<3&&a(e[n]);t++,n++);if(n-t==0)throw new Error("Invalid decimal uchar.");const i=parseInt(e.slice(t,n));if(i>=0&&i<=255)return n;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let n=this.consumeHexpart(e,t);return":"===e[n]?(n+=1,n=this.consumeIP4Address(e,n),n):n}consumeHexpart(e,t){let n=t;if(":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}if(n=this.consumeHexseq(e,n),":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}return n}consumeHexseq(e,t){let n=t;for(;n=this.consumeHex4(e,n),":"===e[n]&&":"!==e[n+1];)n+=1;return n}consumeHex4(e,t){let n=0;for(;n<4;n++)if(!((i=e[t+n])>="0"&&i<="9"||i>="a"&&i<="f"||i>="A"&&i<="F")){if(0===n)throw new Error("Invalid hex 4");break}var i;return t+n}consumeFQDN(e,t){let n=t;for(;a(e[n])||h(e[n])||"-"===e[n]||"."===e[n];)n+=1;if(n-t<4)throw new Error("Invalid FQDN");return n}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,n){switch(n){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(n){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const n=this.consumeHexpart(e,t);return"/"===e[n]?this.consumeInteger(e,n+1):n}consumeIP4MulticastAddress(e,t){let n=t+3;const i=e.slice(t,n),r=parseInt(i);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[n])throw new Error("Invalid IP4 multicast address.");n+=1,n=this.consumeDecimalUChar(e,n)}return"/"===e[n]&&(n+=1),n=this.consumeTTL(e,n),"/"===e[n]&&(n=this.consumeInteger(e,n)),n}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 n=0;n<2&&a(e[t]);n++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let n=t;if("0"===e[n])return n+1;for(u(e[n])&&(n+=1);a(e[n]);)n++;if(n-t<10)throw new Error("Invalid time");return n}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let n=t;return n=this.consumeOneOrMore(e,n,a),p(e[n])?n+1:n}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,n){for(let i=0;i<n.length;i++){if(t+i>=e.length)throw new Error("consume exceeding value length");if(e[t+i]!==n[i])throw new Error("consume ".concat(n," failed at ").concat(i))}return t+n.length}consumeTill(e,t,n){let i=t;for(;i<e.length&&("string"!=typeof n||e[i]!==n)&&("function"!=typeof n||!n(e[i]));)i++;return i}}class v 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=>!!dS(e).call(e))).map(this.parseLine),this.currentLine=0;const n=this.parseVersion(),i=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:n,origin:i,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]===i)return"\r"===e[t-1]?r:i;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 n=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:n,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new C;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(t,(e=>l(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,n.attValue=this.extractOneOrMore(t,_)),e.parse(n),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new b(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(e,(e=>l(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,n.attValue=this.extractOneOrMore(e,_)),t.parse(n),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 n=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let i=!1;"-"===e.value[e.cur]&&(i=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:n,typedTime:r,back:i})}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 n=this.extract(t,this.consumeRepeatInterval),i=this.parseTypedTime(t);e.push({repeatInterval:n,typedTimes:i}),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 n=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:n}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const n=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const i=this.extractOneOrMore(t,a);e.push({bwtype:n,bandwidth:i}),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 n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const i=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:n,sessVersion:i,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 n=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:n,address:i}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let n=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,n+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const i=[];for(i.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,i.push(this.extract(e,this.consumeToken));if(0===i.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:n,protos:i,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),n=this.parseRepeat(),i=this.parseZone();e.push({time:t,repeats:n,zones:i})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),n=this.parseInformation(),i=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:n,connections:i,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 n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.value,e.cur,...i),s=e.value.slice(e.cur,o);return e.cur=o,s}extractOneOrMore(e,t){const n=this.consumeOneOrMore(e.value,e.cur,t),i=e.value.slice(e.cur,n);return e.cur=n,i}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class y extends R{constructor(){super(...arguments),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,n){const i=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,i),[o,s]=n||[];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=i,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 n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.attValue,e._cur,...i),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 n=0;n<t.length;n++)if(t[n]!==e.attValue[e._cur+n])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 n=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:n})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let n;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),n=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o),r=S(S({entry:parseInt(t,10)},n&&{direction:n}),{},{extensionName:i});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 C extends y{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),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),n.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:n})}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),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const i=this.extractOneOrMore(e,(e=>e!==o&&_(e)));n.push({name:t,value:i})}this.attributes.identities.push({assertionValue:t,extensions:n})}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 n=this.extract(e,this.consumeTill,o);t.identifierList.push(n)}}this.attributes.msidSemantic=t}}class b extends y{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 n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=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:n,transport:i,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 n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:n,connectionAddress:i,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 n=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const i={encodingName:n,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),i.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=i:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:i,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 n=this.extract(e,this.consumeTill,":");let i;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),i=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[n]=i:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[n]:i}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill),i={};n.split(";").forEach((e=>{let[t,n]=e.split("=");t=dS(t).call(t);const r="string"==typeof n?dS(n).call(n):null;"string"==typeof t&&t.length>0&&(i[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:i}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:i}})}parseFmtParameters(e){const t={},n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");for(t[n]=i;";"===e.attValue[e._cur];){const n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");t[n]=i}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 n=this.extract(e,this.consumeTill,o);let i;if("trr-int"===n)i={type:n,interval:this.extract(e,this.consumeTill)};else{const t={type:n};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))),i=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(i);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(i):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[i]})}}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 n={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 n=this.extract(e,this.consumeToken);t.push(n);try{this.extract(e,this.consume,",")}catch(e){break}}n.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 i={type:t,rids:this.extract(e,this.consume,"=").split(",")};n.params.push(i);break}default:{const i={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),i.val=this.extract(e,this.consumeTill,";")),n.params.push(i)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(n)}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),n=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);n.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:n})}}function I(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class A{constructor(){I(this,"eol",r)}print(e,t){let n="";return t&&(this.eol=t),n+=this.printVersion(e.version),n+=this.printOrigin(e.origin),n+=this.printSessionName(e.sessionName),n+=this.printInformation(e.information),n+=this.printUri(e.uri),n+=this.printEmail(e.emails),n+=this.printPhone(e.phones),n+=this.printConnection(e.connection),n+=this.printBandwidth(e.bandwidths),n+=this.printTimeFields(e.timeFields),n+=this.printKey(e.key),n+=this.printSessionAttributes(e.attributes),n+=this.printMediaDescription(e.mediaDescriptions),n}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 n of e)t+="e=".concat(n).concat(this.eol);return t}printPhone(e){let t="";for(const n of e)t+="e=".concat(n).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 n of e)t+="b=".concat(n.bwtype,":").concat(n.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const n of e){t+="t=".concat(n.time.startTime," ").concat(n.time.startTime).concat(this.eol);for(const e of n.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);n.zoneAdjustments&&(t+="z=",t+="z=".concat(n.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 n of e)t+="a=".concat(n.attField).concat(n.attValue?":".concat(n.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const n of e)t+=this.printMedia(n.media),t+=this.printInformation(n.information),t+=this.printConnections(n.connections),t+=this.printBandwidth(n.bandwidths),t+=this.printKey(n.key),t+=this.printMediaAttributes(n);return t}printConnections(e){let t="";for(const n of e)t+=this.printConnection(n);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){I(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 n="";return n+=this.printRTCP(t.rtcp),n+=this.printIceUfrag(t.iceUfrag),n+=this.printIcePwd(t.icePwd),n+=this.printIceOptions(t.iceOptions),n+=this.printCandidates(t.candidates),n+=this.printRemoteCandidatesList(t.remoteCandidatesList),n+=this.printEndOfCandidates(t.endOfCandidates),n+=this.printFingerprints(t.fingerprints),n+=this.printSetup(t.setup),n+=this.printMid(t.mid),n+=this.printExtmap(t.extmaps),n+=this.printRTPRelated(t),n+=this.printPtime(t.ptime),n+=this.printMaxPtime(t.maxPtime),n+=this.printDirection(t.direction),n+=this.printSSRCGroups(t.ssrcGroups),n+=this.printSSRC(t.ssrcs),n+=this.printRTCPMux(t.rtcpMux),n+=this.printRTCPMuxOnly(t.rtcpMuxOnly),n+=this.printRTCPRsize(t.rtcpRsize),n+=this.printMSId(t.msids),n+=this.printImageattr(t.imageattr),n+=this.printRid(t.rids),n+=this.printSimulcast(t.simulcast),n+=this.printSCTPPort(t.sctpPort),n+=this.printMaxMessageSize(t.maxMessageSize),n+=this.printUnrecognized(t.unrecognized),n}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 n="";n+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)n+=this.printRtpMap(e.payloadType,e.rtpMap),n+=this.printFmtp(e.payloadType,e.fmtp),n+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return n}printFmtp(e,t){if(!t)return"";const n=Object.keys(t.parameters);return 1===n.length&&null===t.parameters[n[0]]?"a=fmtp:".concat(e).concat(o).concat(n[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 n="a=rtcp-fb:".concat(e).concat(o),i=t;return"trr-int"===i.type?n+="ttr-int".concat(o).concat(i.interval):(n+="".concat(i.type),i.parameter&&(n+="".concat(o).concat(i.parameter),i.additional&&(n+="".concat(o).concat(i.additional)))),n+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 v).parse(e)}function P(e,t){return(new A).print(e,t)}}},t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={exports:{}};return e[i](r,r.exports,n),r.exports}return n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(8)})();function _D(e){return pD.parse(e)}function ED(e,t){return pD.print(e,t)}var mD=qn("Array").keys,fD=pi,gD=Qe,SD=l,TD=mD,RD=Array.prototype,vD={DOMTokenList:!0,NodeList:!0},yD=function(e){var t=e.keys;return e===RD||SD(RD,e)&&t===RD.keys||gD(vD,fD(e))?TD:t},CD=n(yD);function bD(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ID(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function AD(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ID(Object(n),!0).forEach((function(t){bD(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ID(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function wD(e,t){return wD=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},wD(e,t)}function OD(){OD=function(e,t){return new n(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function n(e,i,r){var o=RegExp(e,i);return t.set(o,r||t.get(e)),wD(o,n.prototype)}function i(e,n){var i,r=t.get(n);return zi(i=Object.keys(r)).call(i,(function(t,n){var i=r[n];if("number"==typeof i)t[n]=e[i];else{for(var o=0;void 0===e[i[o]]&&o+1<i.length;)o++;t[n]=e[i[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&&wD(e,t)}(n,RegExp),n.prototype.exec=function(t){var n=e.exec.call(this,t);if(n){n.groups=i(n,this);var r=n.indices;r&&(r.groups=i(r,this))}return n},n.prototype[Symbol.replace]=function(n,r){if("string"==typeof r){var o=t.get(this);return e[Symbol.replace].call(this,n,r.replace(/\$<([^>]+)(>|$)/g,(function(e,t,n){if(""===n)return e;var i=o[t];return Array.isArray(i)?"$"+i.join("$"):"number"==typeof i?"$"+i:""})))}if("function"==typeof r){var s=this;return e[Symbol.replace].call(this,n,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(i(e,s)),r.apply(this,e)}))}return e[Symbol.replace].call(this,n,r)},OD.apply(this,arguments)}const ND=new class extends uO{constructor(){super(...arguments),bD(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))}};function DD(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function PD(){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 LD={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},kD=Date.now(),MD=e=>{for(const t in LD)if(Object.prototype.hasOwnProperty.call(LD,t)&&LD[t]===e)return t;return"DEFAULT"};const UD=new class{constructor(){bD(this,"proxyServerURL",void 0),bD(this,"logLevel",LD.DEBUG),bD(this,"uploadState","collecting"),bD(this,"uploadLogWaitingList",[]),bD(this,"uploadLogUploadingList",[]),bD(this,"uploadErrorCount",0),bD(this,"currentLogID",0),bD(this,"url",void 0),bD(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[LD.DEBUG].concat(t);this.log.apply(this,i)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[LD.INFO].concat(t);this.log.apply(this,i)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[LD.WARNING].concat(t);this.log.apply(this,i)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[LD.ERROR].concat(t);this.log.apply(this,i)}upload(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[LD.DEBUG].concat(t);this.uploadLog.apply(this,i)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){nD("UPLOAD_LOG",!0)}disableLogUpload(){nD("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new class{constructor(e){bD(this,"logger",void 0),bD(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-kD<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-kD);const i=Math.max(0,Math.min(4,t[0]));if(t[0]=DD()+" Agora-SDK [".concat(MD(i),"]:"),this.appendLogToWaitingList(i,...t),i<this.logLevel)return;const r=DD()+" %cAgora-SDK [".concat(MD(i),"]:");let o=[];if(!iD("USE_NEW_LOG"))switch(i){case LD.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case LD.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case LD.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case LD.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),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-kD<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-kD);const i=Math.max(0,Math.min(4,t[0]));t[0]=DD()+" Agora-SDK [".concat(MD(i),"]:"),this.appendLogToWaitingList(i,...t)}appendLogToWaitingList(e){if(!iD("UPLOAD_LOG"))return;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];Array.isArray(n[0])?n[0][0]=PD()+" Agora-SDK [".concat(MD(e),"]:"):n[0]=PD()+" Agora-SDK [".concat(MD(e),"]:");let r="";n.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:XN,process_id:iD("PROCESS_ID"),payload:JSON.stringify(e)};return fN((async()=>{const e=await $A.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(iD("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(iD("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 n={status:-1,message:t.message,errorRange:e.map((e=>e.log_item_id))};return t.response?(n.status=t.response.status,n.data=t.response.data,n.headers=t.response.headers):t.request&&(n.status=t.request.status),ND.reportLogUploadError(n),!0}),{timeout:iD("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:iD("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,iD("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),iD("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),iD("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),iD("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var VD;function xD(e){return $w(e.reportId,"params.reportId",0,100,!1),$w(e.category,"params.category",0,100,!1),$w(e.event,"params.event",0,100,!1),$w(e.label,"params.label",0,100,!1),qw(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(VD={}).FREE="free",VD.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}({});let FD=function(e){return e[e.RECOVER=0]="RECOVER",e[e.WARNING=1]="WARNING",e[e.ERROR=2]="ERROR",e}({}),BD=function(e){return e.CONFIG_DISTRIBUTE="config-distribute-error",e}({});const GD={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let jD=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.ALARM_STATUS_NOTIFY="alarm_status_notify",e}({}),WD=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.ALARM_STATUS_NOTIFY="io.agora.pb.Wrtc.AlarmStatusNotify",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let KD=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}({});const YD="[config-restore]",HD="websdk_ng_",XD=HD+"blocked_config_hashes",JD=HD+"api_failure_records",zD=HD+"global_parameter",ZD=HD+"config_restore_state";function qD(e){var t;return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map((e=>qD(e))).join(",")+"]":"{"+Jp(t=Object.keys(e)).call(t).map((t=>JSON.stringify(t)+":"+qD(e[t]))).join(",")+"}"}function QD(e){return function(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}(qD(e))}function $D(){try{const e=window.localStorage.getItem(ZD);if(e)return JSON.parse(e)}catch(e){}return{currentConfigHash:"",configVerified:!1}}function eP(e){try{window.localStorage.setItem(ZD,JSON.stringify(e))}catch(e){}}function tP(){try{const e=window.localStorage.getItem(JD);return e?JSON.parse(e):[]}catch(e){return UD.debug("[error] ".concat(YD," error getting API failure records:"),e),[]}}function nP(){var e;return zi(e=tP()).call(e,((e,t)=>e+t.count),0)}function iP(){try{window.localStorage.removeItem(JD)}catch(e){UD.debug("[error] ".concat(YD," error clearing API failure records:"),e)}}function rP(){try{const e=nP(),t=iD("MAX_CONFIG_RETRY");if(e<t)return;const{currentConfigHash:n}=$D();UD.debug("[warning] ".concat(YD," restoring config due to ").concat(e," API failures")),n&&function(e){try{const t=window.localStorage.getItem(XD);let n=[];t&&(n=JSON.parse(t).configHashes);const i=[...new Set([...n,e])];window.localStorage.setItem(XD,JSON.stringify({configHashes:i,timestamp:Date.now()})),UD.debug("[warning] ".concat(YD," blocked config hash: ").concat(e))}catch(e){UD.debug("[error] ".concat(YD," error blocking config hash:"),e)}}(n),window.localStorage.removeItem(zD);const i=tP().slice(-5);(function(e,t){cP.reportAlarm(e,t)})(null,{status:FD.ERROR,type:BD.CONFIG_DISTRIBUTE,message:"Config cache cleared due to API failures",extend:{failureCount:e,maxRetry:t,blockedConfigHash:n,recentFailures:i.map((e=>({api:e.apiName,error:e.errorCode||e.errorMessage,count:e.count,lastTime:e.lastTimestamp})))}}),iP()}catch(e){UD.debug("[error] ".concat(YD," error restoring config:"),e)}}function oP(e,t){try{if(!iD("ENABLE_CONFIG_RESTORE"))return;if(t&&"AgoraRTCException"===t.name){const e=iD("CONFIG_ERROR_MONITOR");if(!Array.isArray(e)||!Di(e).call(e,t.code))return}const n=window.localStorage.getItem(zD);if(!n||n.length<20)return;const{configVerified:i}=$D();if(i)return;const r=iD("CONFIG_RESTORE_ERROR_API");if(!Array.isArray(r)||!Di(r).call(r,e))return;let o,s;t&&(t.code&&(o=t.code),s=t.message?t.message:"string"==typeof t?t:t.toString()),function(e,t,n){try{const i=tP(),r="".concat(e,":").concat(t||""),o=i.find((e=>"".concat(e.apiName,":").concat(e.errorCode||"")===r)),{currentConfigHash:s}=$D();if(o)o.count++,o.lastTimestamp=Date.now(),n&&(o.errorMessage=n),s&&(o.configHash=s);else{const r=Date.now();i.push({apiName:e,errorCode:t,errorMessage:n,count:1,firstTimestamp:r,lastTimestamp:r,configHash:s||void 0})}const a=i.length>20?i.slice(-20):i;window.localStorage.setItem(JD,JSON.stringify(a))}catch(e){UD.debug("[error] ".concat(YD," error saving API failure record:"),e)}}(e,o,s);const a=nP(),c=iD("MAX_CONFIG_RETRY");UD.debug("".concat(YD," API failure count: ").concat(a,"/").concat(c,", API: ").concat(e,", Error: ").concat(o||s)),a>=c&&rP()}catch(e){}}function sP(){try{window.localStorage.removeItem(XD)}catch(e){UD.debug("[error] ".concat(YD," error resetting blocked config:"),e)}}function aP(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,n,i){const r=i.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);i.value=function(){for(var t,i=arguments.length,s=new Array(i),a=0;a<i;a++)s[a]=arguments[a];let c=s;if(e.argsMap)try{c=e.argsMap(this,...s)}catch(e){UD.warning(e),c=[]}try{JSON.stringify(c)}catch(e){UD.warning("arguments for method ".concat(o,".").concat(String(n)," not serializable for apiInvoke.")),c=[]}const d=(e.report||cP).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(n)),options:c,tag:EO.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 i}}const cP=new class{constructor(){bD(this,"baseInfoMap",new Map),bD(this,"proxyServer",void 0),bD(this,"eventUploadTimer",void 0),bD(this,"setSessionIdTimer",void 0),bD(this,"url",void 0),bD(this,"sids",new Set),bD(this,"backupUrl",void 0),bD(this,"_appId",void 0),bD(this,"_aid",0),bD(this,"keyEventUploadPendingItems",[]),bD(this,"normalEventUploadPendingItems",[]),bD(this,"apiInvokeUploadPendingItems",[]),bD(this,"apiInvokeCount",0),bD(this,"apiInvokeLoggedCount",0),bD(this,"ltsList",[]),bD(this,"lastSendNormalEventTime",Date.now()),bD(this,"customReportCounterTimer",void 0),bD(this,"customReportCount",0),bD(this,"extApiInvoke",(async e=>{for(const t of e){const e=AD(AD({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:EO.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),iD("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),iD("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,n]=e;return t+n})),16)||0}reportApiInvoke(e,t,n){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const i=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!iD("SHOW_REPORT_INVOKER_LOG"),s=!!iD("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(e,n){if(a){let i="[apiInvoke-".concat(c,"]");if(t.id&&(i+="[".concat(t.id,"]")),t.name&&(i+="[".concat(t.name,"]"),t.name===_O.JOIN))return UD.info("".concat(i," ").concat(e));UD.info("".concat(i," ").concat(e),"start"===e?t.options:n||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:i,options:t.options,states:t.states||null});d("start");let u=!1;QO(t.timeout).then((()=>{u||(this.sendApiInvoke(AD(AD({},l()),{},{error:Xw.API_INVOKE_TIMEOUT,success:!1})),d("timeout"),oP(t.name,new Jw(Xw.API_INVOKE_TIMEOUT)))}));const h=new Jw(Xw.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const i=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(AD(AD({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return n?iN(i,t.name+"Success",n,(()=>u=!0)):i()},onError:e=>{const i=()=>{if(u)throw e;u=!0,this.sendApiInvoke(AD(AD({},l()),{},{success:!1,error:e})),oP(t.name,e),d("onFailure",e.toString())};return n?iN(i,t.name+"Error",n,(()=>u=!0)):i()}}}_send(e,t,n){this.send({type:e,data:t},n)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const n=Date.now(),i=this.createBaseInfo(e,n);i.cname=t.cname,i.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:iD("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:JN?"global":"oversea",areas:iD("AREAS")&&iD("AREAS").join(",")},t.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=AD(AD({},i),{},{eventType:jD.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:$N,lts:u,elapse:u-n,extend:JSON.stringify(r),mode:t.mode,process:iD("PROCESS_ID"),appType:iD("APP_TYPE"),success:!0,version:XN,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:Ww()?42:20,clientRole:l,serviceId:iD("PROCESS_ID"),extensionID:iD("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid,installId:HN()});this.send({type:WD.SESSION,data:h},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const n=t.info,i=Date.now(),r=AD(AD({},n),{},{eventType:jD.RTE_DETAIL,lts:i,success:!0,elapse:i-t.startTime,vid:void 0===n.vid?0:Number(n.vid),ua:navigator.userAgent});this.send({type:WD.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid);const r=Date.now(),o=AD(AD({},i),{},{role:t.role,eventType:jD.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-n.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:WD.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{eventType:jD.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-n.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:WD.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid),i.uid=t.uid,i.cid=t.cid;const r=Date.now(),{firstSuccess:o,addr:s,isProxy:a}=t,c=r-n.startTime,d=AD(AD({},i),{},{eventType:jD.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:HN(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:a?1:0}),l=d.success?1:0;if(t.succ&&(n.lastJoinSuccessTime=r),s)if("1"===d.signalChannel){const e=OD(/(\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:WD.JOIN_GATEWAY,data:d},!0);else{const 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:jD.REJOIN_GATEWAY});this.send({type:WD.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=Date.now(),r=AD(AD({},n.info),{},{lts:i,timeout:t,elapse:i-n.startTime});this.send({type:WD.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{eventType:jD.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-n.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:WD.PUBLISH,data:o},!0)}subscribe(e,t,n){const i=this.baseInfoMap.get(e);if(!i)return;const r=i.info,o=Date.now(),s=AD(AD({},r),{},{eventType:jD.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-i.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},n&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:WD.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const n=[...CD(t=this.baseInfoMap).call(t)],i=n.length?n[0]:"UnableToGetSid",r=this.baseInfoMap.get(i);if(!r)return;const o=r.info,s=Date.now(),a=AD(AD({},o),{},{eventType:jD.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:WD.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=t.peerPubStatusMs-(n.lastJoinSuccessTime||r),s=AD(AD({},i),{},{elapse:r-n.startTime,eventType:jD.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||"",sdpEndPoint:t.sdpEndPoint?1:0});this.send({type:WD.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=AD(AD(AD({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((i.firstFrame||s)-r.startTime,0),apEnd:Math.max(i.apEnd-r.startTime,0),apStart:Math.max(i.apStart-r.startTime,0),joinGwEnd:Math.max(i.joinGwEnd-r.startTime,0),joinGwStart:Math.max(i.joinGwStart-r.startTime,0),pcEnd:Math.max(i.pcEnd-r.startTime,0),pcStart:Math.max(i.pcStart-r.startTime,0),subscriberEnd:Math.max(i.subscriberEnd-r.startTime,0),subscriberStart:Math.max(i.subscriberStart-r.startTime,0),videoAddNotify:Math.max(i.videoAddNotify-r.startTime,0)});this.send({type:n,data:a},!0)}firstRemoteFrame(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=AD(AD(AD({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:n,data:a},!0)}abTest(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:jD.AB_TEST,lts:r});this.send({type:WD.AB_TEST,data:o},!0)}pcStats(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:jD.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:WD.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),eventType:jD.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:WD.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=AD(AD(AD({},o),i),{},{eventType:t,lts:s});this.send({type:n,data:a},!0)}streamSwitch(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{eventType:jD.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-n.startTime,success:t.succ});this.send({type:WD.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{eventType:jD.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:WD.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{eventType:jD.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:WD.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?UD.debug("reportProxyServerurl: ".concat(e)):UD.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD({},i),{},{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-n.startTime,joinChannelSuccessElapse:r-(n.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:WD.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now();(function(e,t,n){const i=e[t];if(!i||"string"!=typeof i)return[e];e[t]="";const r=zO(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<i.length;c++)a+=i.charCodeAt(c)<=127?1:3,a<=n-r||(s[s.length]=Hw(Hw({},e),{},{[t]:i.substring(o,c)}),o=c,a=i.charCodeAt(c)<=127?1:3);return o!==i.length-1&&(s[s.length]=Hw(Hw({},e),{},{[t]:i.substring(o)})),s})(AD(AD(AD({},i),t),{},{elapse:r-n.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach((e=>this.send({type:WD.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:WD.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{elapse:r-n.startTime,lts:r,extend:t.extend||void 0});this.send({type:WD.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:WD.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>iD("CUSTOM_REPORT_LIMIT"))throw new Jw(Xw.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const n=Date.now(),i=t.map((t=>({type:WD.USER_ANALYTICS,data:AD(AD({sid:e},t),{},{lts:n})})));try{iD("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(i):await this.postDataToStatsCollector(i)}catch(e){throw UD.error("send custom report message failed",e.toString()),new Jw(Xw.CUSTOM_REPORT_SEND_FAILED,e.message)}}reportAlarm(e,t){const n=e?this.baseInfoMap.get(e):void 0,i=null==n?void 0:n.info,r=Date.now(),o=AD(AD(AD({},i),t),{},{vid:void 0===(null==i?void 0:i.vid)?0:Number(i.vid),elapse:n?r-n.startTime:0,eventType:jD.ALARM_STATUS_NOTIFY,lts:r,installId:HN(),processId:iD("PROCESS_ID")});this.send({type:WD.ALARM_STATUS_NOTIFY,data:o},!0)}sendApiInvoke(e){const t=iD("NOT_REPORT_EVENT");if(e.tag&&Di(t)&&Di(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const n=this.baseInfoMap.get(e.sid);if(!n)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:i,uid:r,cid:o}=n.info;let s;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Jw){const{code:t,message:n}=e.error;s=t||n||e.error.toString()}else s=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:i,cid:o,uid:r,lts:e.lts,success:e.success,elapse:e.lts-n.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:WD.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>iD("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 n=[],i=[];for(;e.length;){const t=e.shift();n.length<20?n.push(t):i.push(t)}e.push(...i);for(const e of[...n]){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),Jp(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),iD("ENABLE_EVENT_REPORT")?(n.length&&(iD("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(n):this.postDataToStatsCollector(n)).catch((e=>n=>{iD("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>iD("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-iD("NORMAL_EVENT_QUEUE_CAPACITY")),UD.warning("report: drop normal events"))))})(n)),e):e}async postDataToStatsCollector2(e){PO.networkState===IO.OFFLINE&&await Wh.race([PO.onlineWaiter,QO(2*EN.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const n=cO(JSON.stringify(e.data)),i=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(WD).forEach((n=>{let[i,r]=n;r===e.type&&(t=KD[i])})),t})(e),o=new DataView(i);o.setUint16(0,n.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=dO(t,new Uint8Array(i)),t=dO(t,n)})),t},n="event";let i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(iD("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(n):"https://".concat(iD("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(n);for(let r=0;r<2;r+=1){1===r&&(i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(iD("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(n):"https://".concat(iD("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(n));try{await vN(i,{timeout:1e4,data:t(e),headers:AD(AD({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 n=(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),i=n?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:n,aid:i};PO.networkState===IO.OFFLINE&&await Wh.race([PO.onlineWaiter,QO(2*EN.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(iD("EVENT_REPORT_DOMAIN"),"&p=").concat(iD("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(iD("EVENT_REPORT_DOMAIN"),":").concat(iD("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(iD("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(iD("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(iD("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(iD("STATS_COLLECTOR_PORT")).concat(o)));try{t?await yN(s,{timeout:1e4,data:r}):await vN(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const n=Object.assign({},GD);return n.sid=e,this.baseInfoMap.set(e,{info:n,startTime:t}),n}reportResourceTiming(e,t){const n=performance.getEntriesByName(e),i=n[n.length-1];i&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:i,tag:EO.TRACER}).onSuccess()}};ND.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=PO.networkState,cP.reportApiInvoke(null,{name:"logUploadError",options:e,tag:EO.TRACER}).onSuccess("logUploadError")}));let dP=class extends Jw{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),bD(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,UD)}throw(){super.throw(UD)}};const lP={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 uP(){return lP}function hP(){return"setSinkId"in HTMLAudioElement.prototype&&(!iD("RESTRICTION_SET_PLAYBACK_DEVICE")||(Ew()||Sw())&&!Fw())}function pP(){return!lP.supportUnifiedPlan||iD("CHROME_FORCE_PLAN_B")&&Bw()}function _P(){return iD("ENABLE_JOIN_V4")}function EP(e){return!(Tw()||yw(87)||pP()||!iD("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||iD("FORCE_DISABLE_AUTO_SUB")))}function mP(e){return iD("ENABLE_INSTANT_VIDEO")?iD("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||iD("FORCE_DISABLE_AUTO_SUB"))}function fP(){return!!iD("FORCE_ENABLE_AUT_CC")||!pP()&&(!!iD("ENABLE_AUT_CC")||void 0)}function gP(){return!!iD("FORCE_ENABLE_AUT_CC")||!pP()&&(!!iD("ENABLE_AUT_FEEDBACK")||void 0)}function SP(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function TP(){if(SP()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return vw(141)||bw(141)||Dw(141)}function RP(){if(SP()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return vw(141)||bw(141)||Dw(125)}let vP=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 yP(e,t,n){return{sampleRate:e,stereo:t,bitrate:n}}function CP(e,t,n,i,r){return{width:e,height:t,frameRate:n,bitrateMin:i,bitrateMax:r}}function bP(e,t,n,i,r){return{width:{max:e},height:{max:t},frameRate:n,bitrateMin:i,bitrateMax:r}}function IP(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const AP={"90p":CP(160,90),"90p_1":CP(160,90),"120p":CP(160,120,15,30,65),"120p_1":CP(160,120,15,30,65),"120p_3":CP(120,120,15,30,50),"120p_4":CP(212,120),"180p":CP(320,180,15,30,140),"180p_1":CP(320,180,15,30,140),"180p_3":CP(180,180,15,30,100),"180p_4":CP(240,180,15,30,120),"240p":CP(320,240,15,40,200),"240p_1":CP(320,240,15,40,200),"240p_3":CP(240,240,15,40,140),"240p_4":CP(424,240,15,40,220),"360p":CP(640,360,15,80,400),"360p_1":CP(640,360,15,80,400),"360p_3":CP(360,360,15,80,260),"360p_4":CP(640,360,30,80,600),"360p_6":CP(360,360,30,80,400),"360p_7":CP(480,360,15,80,320),"360p_8":CP(480,360,30,80,490),"360p_9":CP(640,360,15,80,800),"360p_10":CP(640,360,24,80,800),"360p_11":CP(640,360,24,80,1e3),"480p":CP(640,480,15,100,500),"480p_1":CP(640,480,15,100,500),"480p_2":CP(640,480,30,100,1e3),"480p_3":CP(480,480,15,100,400),"480p_4":CP(640,480,30,100,750),"480p_6":CP(480,480,30,100,600),"480p_8":CP(848,480,15,100,610),"480p_9":CP(848,480,30,100,930),"480p_10":CP(640,480,10,100,400),"720p":CP(1280,720,15,120,1130),"720p_auto":CP(1280,720,30,900,3e3),"720p_1":CP(1280,720,15,120,1130),"720p_2":CP(1280,720,30,120,2e3),"720p_3":CP(1280,720,30,120,1710),"720p_5":CP(960,720,15,120,910),"720p_6":CP(960,720,30,120,1380),"1080p":CP(1920,1080,15,120,2080),"1080p_1":CP(1920,1080,15,120,2080),"1080p_2":CP(1920,1080,30,120,3e3),"1080p_3":CP(1920,1080,30,120,3150),"1080p_5":CP(1920,1080,60,120,4780),"1440p":CP(2560,1440,30,120,4850),"1440p_1":CP(2560,1440,30,120,4850),"1440p_2":CP(2560,1440,60,120,7350),"4k":CP(3840,2160,30,120,8910),"4k_1":CP(3840,2160,30,120,8910),"4k_3":CP(3840,2160,60,120,13500)},wP={"480p":bP(640,480,5),"480p_1":bP(640,480,5),"480p_2":bP(640,480,30),"480p_3":bP(640,480,15),"720p":bP(1280,720,5),"720p_auto":CP(1280,720,30,900,3e3),"720p_1":bP(1280,720,5),"720p_2":bP(1280,720,30),"720p_3":bP(1280,720,15),"1080p":bP(1920,1080,5),"1080p_1":bP(1920,1080,5),"1080p_2":bP(1920,1080,30),"1080p_3":bP(1920,1080,15)},OP={"1SL1TL":IP(1,1),"3SL3TL":IP(3,3),"2SL3TL":IP(2,3)};function NP(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},AP[e]):e}function DP(e){return"string"==typeof e?Object.assign({},wP[e]):e}function PP(e){return"string"==typeof e?Object.assign({},OP[e]):e}const LP={speech_low_quality:yP(16e3,!1),speech_standard:yP(32e3,!1,18),music_standard:yP(48e3,!1),standard_stereo:yP(48e3,!0,56),high_quality:yP(48e3,!1,128),high_quality_stereo:yP(48e3,!0,192)};function kP(e){return"string"==typeof e?Object.assign({},LP[e]):e}const MP=[];function UP(e){return Zw(e,"mediaSource",["screen","window","application"]),!0}let VP=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}({}),xP=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 FP=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),BP=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}({}),GP=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}({}),jP=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}({}),WP=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}({}),KP=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}({}),YP=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),HP=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 XP={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},JP={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},zP={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},ZP={uplinkNetworkQuality:0,downlinkNetworkQuality:0},qP={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 QP=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),$P=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),eL=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),tL=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),nL=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}({}),iL=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 rL={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 oL=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function sL(e,t,n,i,r){var o,s,a={};return Object.keys(i).forEach((function(e){a[e]=i[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=zi(o=cr(s=n.slice()).call(s)).call(o,(function(n,i){return i(e,t,n)||n}),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),null):a}function aL(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function dL(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?cL(Object(n),!0).forEach((function(t){aL(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cL(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let lL=class extends uO{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(jP.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),aL(this,"trackMediaType",void 0),aL(this,"_ID",void 0),aL(this,"_rtpTransceiver",void 0),aL(this,"_lowRtpTransceiver",void 0),aL(this,"_hints",[]),aL(this,"_isClosed",!1),aL(this,"_originMediaStreamTrack",void 0),aL(this,"mediaStreamTrack",void 0),aL(this,"_external",{}),this._ID=t||$O(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){Di(MP).call(MP,e)||MP.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||KO((()=>{var e;cP.reportApiInvoke(null,{name:_O.GET_MEDIA_STREAM_TRACK,options:[],tag:EO.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===FP.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=MP.indexOf(e);-1!==t&&MP.splice(t,1)}(this),this.emit(WP.CLOSED),this.removeAllListeners(jP.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===FP.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(jP.TRANSCEIVER_UPDATED,e,t)}},uL=class extends lL{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),aL(this,"_enabled",!0),aL(this,"_muted",!1),aL(this,"_isExternalTrack",!1),aL(this,"_isClosed",!1),aL(this,"_enabledMutex",void 0),aL(this,"processor",void 0),aL(this,"_processorContext",void 0),aL(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new pN("".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,UD.debug("[".concat(this.getTrackId(),"] close")),this.emit(VP.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=n,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 OO(this,VP.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){UD.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(WP.TRACK_ENDED)}stateCheck(e,t){if(UD.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),zw(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Jw(Xw.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",UD);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Jw(Xw.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",UD)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Wh.resolve([])}};const hL=window.AudioContext||window.webkitAudioContext;let pL,_L=null;const EL=new class extends uO{constructor(){super(...arguments),aL(this,"prevState",void 0),aL(this,"curState",void 0),aL(this,"currentTime",void 0),aL(this,"currentTimeStuckAt",void 0),aL(this,"interruptDetectorTrack",void 0),aL(this,"onLocalAudioTrackMute",(()=>{UD.info("ios15-interruption-start"),this.emit(vP.IOS_15_16_INTERRUPTION_START)})),aL(this,"onLocalAudioTrackUnmute",(async()=>{UD.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?UD.info("ios15-interruption-end-canceled"):(_L&&await _L.suspend(),this.emit(vP.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){UD.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){UD.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 mL(){if(!_L){if(function(){if(!hL)return void UD.error("your browser is not support web audio");UD.info("create audio context");const e=dL({},iD("WEBAUDIO_INIT_OPTIONS"));UD.debug("audio context init option:",JSON.stringify(e)),_L=new hL(e),EL.curState=_L.state,_L.onstatechange=()=>{EL.prevState=EL.curState,EL.curState=_L?_L.state:void 0;const{prevState:e,curState:t}=EL,n="running"===t,i="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=lw().osVersion;(Rw()||Uw())&&r&&i&&(UD.info("ios".concat(a,"-interruption-start")),EL.emit(vP.IOS_INTERRUPTION_START)),(Rw()||Uw())&&(o||s)&&n&&(UD.info("ios".concat(a,"-interruption-end")),EL.emit(vP.IOS_INTERRUPTION_END)),e!==t&&EL.emit(vP.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=_L)||void 0===e?void 0:e.currentTime;EL.currentTime!==t?(EL.currentTimeStuckAt&&(UD.debug("AudioContext current time resume at ".concat(t)),EL.currentTimeStuckAt=void 0),EL.currentTime=t):(t!==EL.currentTimeStuckAt&&(cP.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:EO.TRACER}).onSuccess(),UD.warning("AudioContext current time stuck at ".concat(t))),EL.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let n,i,r=!1,o=!1,s=!1;function a(t){"running"===e.state?c(!1):Rw()||Uw()?"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 n=0,i=t;n<i.length;n+=1){const t=i[n];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=n.play(),e?e.then(_,_):(n.addEventListener("playing",_),n.addEventListener("abort",_),n.addEventListener("error",_))}catch(e){_()}}function h(e){s||(n.paused?e?(p(!1),s=!0,u()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let n=0,i=t;n<i.length;n++){const t=i[n];e?window.addEventListener(t,E,{capture:!0,passive:!0}):window.removeEventListener(t,E,{capture:!0,passive:!0})}}}function _(){n.removeEventListener("playing",_),n.removeEventListener("abort",_),n.removeEventListener("error",_),s=!1,h(!1)}function E(){h(!0)}if(Rw()&&iD("IOS_BG_TAG")){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",n=r.children.item(0),n.controls=!1,n.disableRemotePlayback=!0,n.preload="auto",n.srcObject=t.stream,i=()=>{if(iD("IOS_AUTO_RESTART_BG_TAG")&&n&&n.srcObject&&!s&&(!n.paused||!0!==o)){n.paused||n.pause();try{s=!0,u()}catch(e){s=!1}return!0}},h(!0)}return EL.on(vP.STATE_CHANGE,(function(){a(!0)})),a(!1),i}(_L).then((e=>{pL=e}))}(),!_L)throw new Jw(Xw.NOT_SUPPORTED,"can not create audio context");return _L}return _L}function fL(e){if(function(){if(null!==gL)return gL;const e=mL(),t=e.createBufferSource(),n=e.createGain(),i=e.createGain();t.connect(n),t.connect(i),t.disconnect(n);let r=!1;try{t.disconnect(n)}catch(e){r=!0}return t.disconnect(),gL=r,r}())return;const t=e.connect,n=e.disconnect;e.connect=(n,i,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Di(o=e._inputNodes).call(o,n)||(n instanceof AudioNode?(e._inputNodes.push(n),t.call(e,n,i,r)):t.call(e,n,i)),e},e.disconnect=(i,r,o)=>{n.call(e),i?xO(e._inputNodes,i):e._inputNodes=[];for(const n of e._inputNodes)t.call(e,n)}}let gL=null;function SL(e,t){let n=!1;const i=1/t;if(iD("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{n?window.clearInterval(t):e(performance.now()/1e3)}),1e3*i)}else{const t=mL();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(n)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+i),e(t.currentTime)};o()}return()=>{n=!0}}let TL=class{constructor(){aL(this,"context",void 0),aL(this,"analyserNode",void 0),aL(this,"sourceNode",void 0),this.context=mL(),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||Rw()||Uw()||"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 n=0;n<e.length;++n)e[n]=t[n]/128-1}const t=zi(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){UD.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}},RL=class extends uO{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var n;null===(n=this.sourceNode)||void 0===n||n.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(),aL(this,"outputNode",void 0),aL(this,"outputTrack",void 0),aL(this,"isPlayed",!1),aL(this,"sourceNode",void 0),aL(this,"context",void 0),aL(this,"audioBufferNode",void 0),aL(this,"destNode",void 0),aL(this,"audioOutputLevel",0),aL(this,"volumeLevelAnalyser",void 0),aL(this,"_processedNode",void 0),aL(this,"playNode",void 0),aL(this,"isDestroyed",!1),aL(this,"onNoAudioInput",void 0),aL(this,"isNoAudioInput",!1),aL(this,"_noAudioInputCount",0),this.context=mL(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),fL(this.outputNode),this.volumeLevelAnalyser=new TL}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(HP.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const n=e.outputBuffer.getChannelData(t);for(let e=0;e<n.length;e+=1)n[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!uP().webAudioMediaStreamDest)throw new Jw(Xw.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&&BO((()=>{EL.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;Rw()||Uw()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let n;t.getFloatTimeDomainData?(n=new Float32Array(t.fftSize),t.getFloatTimeDomainData(n)):(n=new Uint8Array(t.fftSize),t.getByteTimeDomainData(n));let i=!1;for(let e=0;e<n.length;e++)0!==n[e]&&(i=!0);return i?(this.isNoAudioInput=!1,!0):(await QO(200),await this.checkHasAudioInput(e?e+1:1)&&i)}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)}},vL=class extends RL{get isFreeze(){return!1}constructor(e,t,n){var i;if(super(),aL(this,"sourceNode",void 0),aL(this,"track",void 0),aL(this,"clonedTrack",void 0),aL(this,"audioElement",void 0),aL(this,"isCurrentTrackCloned",!1),aL(this,"isRemoteTrack",!1),aL(this,"originVolumeLevelAnalyser",void 0),aL(this,"rebuildWebAudio",(async()=>{if(UD.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 UD.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>UD.info("resume success"))),UD.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),fL(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const n=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(n,this.context.currentTime),fL(this.outputNode),this.emit(HP.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new Jw(Xw.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),fL(this.sourceNode),n){const e=n.clone();e.enabled=!0,this.clonedTrack=e,UD.debug("create an unmuted track ".concat(e.id," from the original track ").concat(n.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));fL(t),this.originVolumeLevelAnalyser=new TL,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=lw();t&&o.os===ow.IOS&&Number(null===(i=o.osVersion)||void 0===i?void 0:i.split(".")[0])<15&&(EL.on(vP.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),fL(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(HP.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),EL.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),UD.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const n=this.context.createMediaStreamSource(new MediaStream([t]));fL(n),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(n)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}};async function yL(e,t,n){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!n&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(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 CL(e,t){const n=await bL(e.mediaSource),{sourceId:i,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Wh(((n,i)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border:  solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(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 i=e.thumbnail;try{const{width:e}=i.getSize();e>1920&&(i=i.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='+i.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),n({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(n,t);return await yL(i,e,r)}async function bL(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const n=pO();if(!n)throw console.error("failed to fetch electron, please mount it to window"),new Jw(Xw.ELECTRON_IS_NULL);let i=null;try{var r;i=(null===(r=n.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||n.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){i=null}i&&i.then||(i=new Wh(((e,i)=>{n.desktopCapturer.getSources({types:t},((t,n)=>{t?i(t):e(n)}))})));try{return await i}catch(e){throw new Jw(Xw.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const IL=new pN("safari");let AL=!1,wL=!1;async function OL(e,t){let n=0,i=null;for(;n<2;)try{i=await NL(e,t,n>0);break}catch(e){if(e instanceof Jw)throw UD.error("[".concat(t,"] ").concat(e.toString())),e;const i=DL(e.name||e.code||e,e.message);if(i.code===Xw.MEDIA_OPTION_INVALID){UD.debug("[".concat(t,"] detect media option invalid, retry")),n+=1,await QO(500);continue}throw UD.error("[".concat(t,"] ").concat(i.toString())),i}if(!i)throw new Jw(Xw.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return i}async function NL(e,t,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Jw(Xw.NOT_SUPPORTED,"can not find getUserMedia");n&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const i=uP(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return UD.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(pO())e.screen.sourceId?PL(r,await yL(e.screen.sourceId,e.screen,!!e.screenAudio)):PL(r,await CL(e.screen,!!e.screenAudio));else if(Ew()&&e.screen.extensionId&&e.screen.mandatory){if(!i.getStreamFromExtension)throw new Jw(Xw.NOT_SUPPORTED,"This browser does not support screen sharing");UD.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const n=await(s=e.screen.extensionId,a=t,new Wh(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(n=>{if(!n||!n.streamId)return UD.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),n),void t(new Jw(Xw.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(n.streamId)}))}catch(e){UD.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new Jw(Xw.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=n,PL(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(i.getDisplayMedia){var o;e.screen.mediaSource&&UP(e.screen.mediaSource);const n={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:i,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l}=e.screen,u={selfBrowserSurface:i,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l};!i&&delete u.selfBrowserSurface,!s&&delete u.surfaceSwitching,!a&&delete u.systemAudio,!c&&delete u.preferCurrentTab,!d&&delete u.windowAudio,!l&&delete u.monitorTypeSurfaces,UD.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:n,audio:e.screenAudio,controls:u})),PL(r,await navigator.mediaDevices.getDisplayMedia(dL({video:n,audio:e.screenAudio},u)))}else{if(!Tw())throw UD.error("[".concat(t,"] This browser does not support screenSharing")),new Jw(Xw.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&UP(e.screen.mediaSource);const n={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};UD.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(n))),PL(r,await navigator.mediaDevices.getUserMedia(n))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=iD("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=oN(c,d)}catch(e){}UD.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),lw();let l,u=null;(mw()||Rw()||_w())&&(u=await IL.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(AL=!0),c.video&&(wL=!0),PL(r,l),u&&u(),r}function DL(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new Jw(Xw.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new Jw(Xw.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new Jw(Xw.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new Jw(Xw.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new Jw(Xw.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new Jw(Xw.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return UD.error("getUserMedia unexpected error",e),new Jw(Xw.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function PL(e,t){const n=e.getVideoTracks()[0],i=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(i&&e.removeTrack(i),e.addTrack(o)),r&&(n&&e.removeTrack(n),e.addTrack(r))}const LL=new class extends uO{get state(){return this._state}set state(e){e!==this._state&&(this.emit(tL.STATE_CHANGE,e),this._state=e)}constructor(){super(),aL(this,"_state",eL.IDLE),aL(this,"isAccessMicrophonePermission",!1),aL(this,"isAccessCameraPermission",!1),aL(this,"lastAccessMicrophonePermission",!1),aL(this,"lastAccessCameraPermission",!1),aL(this,"checkdeviceMatched",!1),aL(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(iD("ENUMERATE_DEVICES_INTERVAL")||(Gw()||hw()===ow.HARMONY_OS)&&Bw())&&this.updateDevicesInfo()}),iD("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>UD.error(e.toString())))}async enumerateDevices(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new Jw(Xw.NOT_SUPPORTED,"enumerateDevices() not supported.");const i=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(i);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(!n&&(o||s)){if(IL.isLocked&&(UD.debug("[device manager] wait GUM lock"),(await IL.lock())(),UD.debug("[device manager] GUM unlock")),AL&&(o=!1,this.isAccessMicrophonePermission=!0),wL&&(s=!1,this.isAccessCameraPermission=!0),UD.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=DL(e.name||e.code||e,e.message);if(t.code===Xw.PERMISSION_DENIED)throw t;UD.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=DL(e.name||e.code||e,e.message);if(t.code===Xw.PERMISSION_DENIED)throw t;UD.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=DL(e.name||e.code||e,e.message);if(t.code===Xw.PERMISSION_DENIED)throw t;UD.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}UD.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(Xw.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((n=>{n.device.label===e&&(t=n.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new Jw(Xw.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=eL.INITING;try{await this.updateDevicesInfo(),this.state=eL.INITEND}catch(e){if(this.state=eL.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(Xw.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw UD.warning("Device Detection functionality cannot start properly.",e.toString()),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),n=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),n=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&n?n.groupId===t.groupId?UD.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is the same group")):UD.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is not the same group")):UD.debug("[device-check] default input or output not found")}const i=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const i=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(i?i.state:"INACTIVE")){const i={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),i),n.push(i)}i&&(i.updateAt=t)})),this.deviceInfoMap.forEach(((e,i)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",n.push(e))})),this.state!==eL.INITEND)return i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));n.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(tL.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(tL.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(tL.PLAYOUT_DEVICE_CHANGED,e)}})),i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),n=e.filter((e=>"videoinput"===e.kind)),i={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){i.audio=!0;break}for(const e of n)if(e.label&&e.deviceId){i.video=!0;break}return i}};let kL=!1;const ML=new class extends uO{constructor(){super(...arguments),aL(this,"onAutoplayFailed",void 0),aL(this,"onAudioAutoplayFailed",void 0)}};function UL(){if(kL)return iD("FLS_AUTOPLAY_EMITS")?(ML.onAutoplayFailed&&ML.onAutoplayFailed(),ML.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),kL=!1,jw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};kL=!0,jw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),UD.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),ML.onAutoplayFailed?ML.onAutoplayFailed():ML.onAudioAutoplayFailed?UD.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 ."):UD.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 ."),ML.emit("autoplay-failed")}}function VL(e,t,n,i){if(!e)return;const r=cP.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=dL(dL({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:ML.onAutoplayFailed||ML.onAudioAutoplayFailed?1:-1,errorMsg:n,mediaType:t,trackId:i,extend:void 0});cP.send({type:WD.AUTOPLAY_FAILED,data:a},!0)}const xL=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],FL=new class{constructor(){aL(this,"onAutoplayFailed",void 0),aL(this,"elementMap",new Map),aL(this,"elementStateMap",new Map),aL(this,"elementsNeedToResume",[]),aL(this,"sinkIdMap",new Map),aL(this,"autoResumeAfterInterruption",(e=>Wh.all(Array.from(this.elementMap.entries()).map((async t=>{let[n,i]=t;const r=this.elementStateMap.get(n),o=i.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(UD.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(e)),"live"===s){if(e)return i.pause(),i.play();if("running"===EL.curState)return Lw()?(i.pause(),i.play()):r&&"paused"===r?i.play():void 0}}))))),aL(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,n]=e;const i=n.srcObject.getAudioTracks()[0];i&&"live"===i.readyState&&(UD.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),n.pause(),n.play())}))})),this.autoResumeAudioElement(),EL.on(vP.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),EL.on(vP.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),EL.on(vP.STATE_CHANGE,(()=>{Rw()&&"suspended"===EL.prevState&&"running"===EL.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const n=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),n)try{await n.setSinkId(t)}catch(e){throw new Jw(Xw.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,n,i){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,nL.INIT),this.setVolume(t,n);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{UD.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){UD.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{i&&VL(i,"audio",e.message,t),UD.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(UD.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),BO((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),UL()})))}))}updateTrack(e,t){const n=this.elementMap.get(e);n&&(n.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const n=this.elementMap.get(e);n&&(t=Math.max(0,Math.min(100,t)),n.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 n=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(n,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){xL.forEach((n=>{t.addEventListener(n,(n=>{const i=this.elementStateMap.get(e),r="pause"===n.type?"paused":n.type;if(UD.debug("[".concat(e,"] audio-element-status change ").concat(i," => ").concat(r)),"error"===n.type){const n=null==t?void 0:t.error;n&&UD.error("[".concat(e,"] media error, code: ").concat(n.code,", message: ").concat(n.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=>{UD.debug("Auto resume audio element success")})).catch((e=>{UD.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new Wh((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{jw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function BL(){return function(e,t,n){const i=n.value;return"function"==typeof i&&(n.value=function(){this._isClosed&&new Jw(Xw.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",UD);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const r=i.apply(this,t);return r instanceof Wh?new Wh(((e,t)=>{r.then(e).catch(t)})):r}),n}}let GL=class extends uO{constructor(e){super(),aL(this,"name","VideoProcessorDestination"),aL(this,"ID","0"),aL(this,"_source",void 0),aL(this,"videoContext",void 0),aL(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new Jw(Xw.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new Jw(Xw.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(QP.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(QP.ON_TRACK,void 0)}},jL=class extends uO{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),aL(this,"constraintsMap",new Map),aL(this,"statsRegistry",[]),aL(this,"usageRegistry",[]),aL(this,"trackId",void 0),aL(this,"direction",void 0),aL(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await wO(this,$P.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var n;return UD.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),OO(this,$P.REQUEST_UPDATE_CONSTRAINTS,Array.from(Qh(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return UD.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),OO(this,$P.REQUEST_UPDATE_CONSTRAINTS,Array.from(Qh(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:n,type:i,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:n,type:i,stats:o})}catch(e){UD.error(new Jw(Xw.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 n=t();n instanceof Wh&&(n=await n),e.push(dL(dL({},n),{},{direction:this.direction}))}catch(e){UD.error("gather extension usage error",e)}return e}getDirection(){return this.direction}},WL=class extends uO{constructor(e){super(),aL(this,"name","AudioProcessorDestination"),aL(this,"ID","0"),aL(this,"inputTrack",void 0),aL(this,"inputNode",void 0),aL(this,"audioProcessorContext",void 0),aL(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new Jw(Xw.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new Jw(Xw.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(QP.ON_TRACK,void 0),this.emit(QP.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(QP.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(QP.ON_NODE,this.inputNode))}},KL=class extends uO{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,n){super(),aL(this,"constraintsMap",new Map),aL(this,"statsRegistry",[]),aL(this,"audioContext",void 0),aL(this,"trackId",void 0),aL(this,"direction",void 0),aL(this,"usageRegistry",[]),aL(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=n}async getConstraints(){return wO(this,$P.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var n;return UD.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),OO(this,$P.REQUEST_UPDATE_CONSTRAINTS,Array.from(Qh(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),OO(this,$P.REQUEST_UPDATE_CONSTRAINTS,Array.from(Qh(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:n,type:i,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:n,type:i,stats:o})}catch(e){UD.error(new Jw(Xw.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 n=t();n instanceof Wh&&(n=await n),e.push(dL(dL({},n),{},{direction:this.direction}))}catch(e){UD.error("gather extension usage error",e)}return e}getDirection(){return this.direction}},YL=class extends uO{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),aL(this,"context",void 0),aL(this,"processSourceNode",void 0),aL(this,"outputTrack",void 0),aL(this,"processedNode",void 0),aL(this,"clonedTrack",void 0),aL(this,"outputNode",void 0),this.outputNode=new HL}setVolume(){}createOutputTrack(){throw new Jw(Xw.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}},HL=class{disconnect(){}connect(){}};function XL(e){return new Wh(((t,n)=>{let i=!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=Rw()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,n=r.videoHeight;!e&&Tw()||(i=!0,r.srcObject=null,r.remove(),t([e,n]))})),r.srcObject=new MediaStream([e]),r.play().catch(tN),setTimeout((()=>{i||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function JL(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const n=NP(e.encoderConfig);return null!=n.width&&(t.width=n.width),null!=n.height&&(t.height=n.height),!xw()&&n.frameRate&&(t.frameRate=n.frameRate),Sw()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Tw()&&(t.frameRate={ideal:30,max:30}),t}function zL(e){const t={};return xw()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Ew()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function ZL(e){const t=zL(e);if(e.encoderConfig){const n=kP(e.encoderConfig);t.channelCount=n.stereo?2:1,t.sampleRate=n.sampleRate,t.sampleSize=n.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Gw()&&(t.sampleRate=void 0),t}const qL=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:n,width:i,height:r}=e.getMediaStreamTrackSettings();let{frameRate:o=n,width:s=i,height:a=r}=t;if(!o||!s||!a)return;s=aN(s),a=aN(a),o=aN(o);const{max:c,min:d}=function(e,t,n){const i=200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(i),max:Math.floor(4*i)}}(s,a,o),{bitrateMax:l,bitrateMin:u}=t||{};l||UD.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(u,"]"));const{maxFramerate:h}=iD("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}},QL=async(e,t,n)=>await(async(e,t,n)=>{const i=function(e){const t=[];for(let n=0;n<e.length;n+=2)t.push(parseInt(e.slice(n,n+2),16));return Uint8Array.from(t)}(lN(""+t+n)).slice(0,16),r=i.slice(0,12),o=await window.crypto.subtle.importKey("raw",i,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},o,e))})(e.buffer,t,n),$L=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Wh(((n,i)=>{t.toBlob((async e=>{if(t.remove(),e){const i=await ek(e);n({buffer:i,width:t.width,height:t.height})}else i(new Jw(Xw.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},ek=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var tk,nk,ik,rk,ok,sk,ak,ck,dk,lk,uk,hk,pk,_k,Ek,mk,fk,gk,Sk,Tk,Rk,vk,yk,Ck,bk,Ik,Ak,wk,Ok,Nk,Dk,Pk,Lk,kk,Mk,Uk,Vk,xk,Fk,Bk;let Gk=(tk=aP({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),nk=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),ik=BL(),rk=_N("LocalAudioTrack","_enabledMutex"),ok=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),sk=BL(),ak=_N("LocalAudioTrack","_enabledMutex"),ck=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),dk=BL(),lk=BL(),uk=BL(),hk=aP({argsMap:e=>[e.getTrackId()]}),pk=BL(),_k=aP({argsMap:e=>[e.getTrackId()]}),Ek=BL(),mk=aP({argsMap:e=>[e.getTrackId()]}),fk=aP({argsMap:(e,t)=>[e.getTrackId(),t.name]}),gk=aP({argsMap:e=>[e.getTrackId()]}),sL((Sk=class extends uL{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?FL.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,n,i){super(e,n),aL(this,"trackMediaType",YP.AUDIO),aL(this,"_encoderConfig",void 0),aL(this,"_trackSource",void 0),aL(this,"metadata",[]),aL(this,"_enabled",!0),aL(this,"_volume",100),aL(this,"_useAudioElement",!0),aL(this,"_bypassWebAudio",!1),aL(this,"processor",void 0),aL(this,"_processorContext",void 0),aL(this,"_processorDestination",void 0),aL(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!i,this._trackSource=new YL,iD("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),iD("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),mw()&&!_L?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){qw(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&FL.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void UD.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,OO(this,VP.NEED_REPLACE_TRACK,this).then((()=>{UD.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{UD.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||!hP())throw new Jw(Xw.NOT_SUPPORTED,"your browser does not support setting the audio output device");await FL.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,n){return this._setEnabled(e,t,n)}async _setEnabled(e,t,n){if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(UD.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await OO(this,VP.NEED_ENABLE_TRACK,this),UD.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw n||(this._enabled=!1),UD.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await OO(this,VP.NEED_DISABLE_TRACK,this)}catch(e){throw n||(this._enabled=!0),UD.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,UD.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await OO(this,VP.NEED_MUTE_TRACK,this):await OO(this,VP.NEED_UNMUTE_TRACK,this))}getStats(){KO((()=>{UD.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return NO(this,VP.GET_STATS)||dL({},XP)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(HP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(HP.ON_AUDIO_BUFFER),this._source.on(HP.ON_AUDIO_BUFFER,(t=>e(t)))}play(){UD.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(UD.debug("[".concat(this.getTrackId(),"] start audio playback in element")),FL.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){UD.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?FL.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];UD.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&FL.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 OO(this,VP.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(Xw.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Jw(Xw.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(QP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await OO(this,VP.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await OO(this,VP.NEED_REPLACE_TRACK,this))})),e.on(QP.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(QP.ON_TRACK),e.removeAllListeners(QP.ON_NODE)}bindProcessorContextEvents(e){e.on($P.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners($P.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof YL&&(this._trackSource=new vL(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new KL(this._source.context,this.getTrackId(),"local"),t=new WL(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(HP.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(FL.stop(this.getTrackId()),this._source.play()),OO(this,VP.NEED_REPLACE_MIXING_TRACK,this).then((()=>{UD.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{UD.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[tk],Object.getOwnPropertyDescriptor(Sk.prototype,"setVolume"),Sk.prototype),sL(Sk.prototype,"setPlaybackDevice",[nk,ik],Object.getOwnPropertyDescriptor(Sk.prototype,"setPlaybackDevice"),Sk.prototype),sL(Sk.prototype,"setEnabled",[rk,ok,sk],Object.getOwnPropertyDescriptor(Sk.prototype,"setEnabled"),Sk.prototype),sL(Sk.prototype,"setMuted",[ak,ck,dk],Object.getOwnPropertyDescriptor(Sk.prototype,"setMuted"),Sk.prototype),sL(Sk.prototype,"getStats",[lk],Object.getOwnPropertyDescriptor(Sk.prototype,"getStats"),Sk.prototype),sL(Sk.prototype,"setAudioFrameCallback",[uk],Object.getOwnPropertyDescriptor(Sk.prototype,"setAudioFrameCallback"),Sk.prototype),sL(Sk.prototype,"play",[hk,pk],Object.getOwnPropertyDescriptor(Sk.prototype,"play"),Sk.prototype),sL(Sk.prototype,"stop",[_k,Ek],Object.getOwnPropertyDescriptor(Sk.prototype,"stop"),Sk.prototype),sL(Sk.prototype,"close",[mk],Object.getOwnPropertyDescriptor(Sk.prototype,"close"),Sk.prototype),sL(Sk.prototype,"pipe",[fk],Object.getOwnPropertyDescriptor(Sk.prototype,"pipe"),Sk.prototype),sL(Sk.prototype,"unpipe",[gk],Object.getOwnPropertyDescriptor(Sk.prototype,"unpipe"),Sk.prototype),Sk),jk=(Tk=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),Rk=BL(),vk=_N("MicrophoneAudioTrack","_enabledMutex"),yk=aP({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),Ck=BL(),bk=aP({argsMap:e=>[e.getTrackId()]}),sL((Ik=class extends Gk{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,n,i){super(e,t.encoderConfig?kP(t.encoderConfig):{},i,iD("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),aL(this,"_config",void 0),aL(this,"_deviceName","default"),aL(this,"_constraints",void 0),aL(this,"_originalConstraints",void 0),aL(this,"_enabled",!0),this._config=t,this._constraints=n,this._originalConstraints=n,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Lw()||kw())&&EL.bindInterruptDetectorTrack(this)}async setDevice(e){if(UD.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await LL.getDeviceById(e),n={};n.audio=dL({},this._constraints),n.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let i=null;try{i=await OL(n,this.getTrackId())}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await OL({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await LL.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}UD.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,n){if(t)return UD.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(UD.info("[".concat(this.getTrackId(),"] start setEnabled"),e),iD("AUTO_RESET_AUDIO_ROUTE")&&(Rw()||Uw())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var i;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(i=this._source.clonedTrack)||void 0===i||i.stop(),n||(this._enabled=!1);try{await OO(this,VP.NEED_DISABLE_TRACK,this)}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=dL({},this._constraints),o=LL.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{n||(this._enabled=!0);const e=await OL({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await OO(this,VP.NEED_ENABLE_TRACK,this)}catch(e){throw n||(this._enabled=!1),UD.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}UD.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(Lw()||kw())&&EL.unbindInterruptDetectorTrack(this),MP.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))||pL&&pL()&&(cP.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:EO.TRACER}).onSuccess(),UD.debug("restart background audio tag success"))}onTrackEnded(){if((Rw()||Uw())&&this._enabled&&!this._isClosed&&EL.duringInterruption){const e=async()=>{EL.off(vP.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(UD.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};EL.on(vP.IOS_INTERRUPTION_END,e)}else UD.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(WP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=LL.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId=n),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await OL({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on($P.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners($P.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[Tk,Rk],Object.getOwnPropertyDescriptor(Ik.prototype,"setDevice"),Ik.prototype),sL(Ik.prototype,"setEnabled",[vk,yk,Ck],Object.getOwnPropertyDescriptor(Ik.prototype,"setEnabled"),Ik.prototype),sL(Ik.prototype,"close",[bk],Object.getOwnPropertyDescriptor(Ik.prototype,"close"),Ik.prototype),Ik),Wk=(Ak=aP({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),wk=BL(),Ok=aP({argsMap:e=>[e.getTrackId()]}),Nk=BL(),Dk=aP({argsMap:e=>[e.getTrackId()]}),Pk=BL(),Lk=aP({argsMap:e=>[e.getTrackId()]}),kk=BL(),Mk=aP({argsMap:e=>[e.getTrackId()]}),Uk=BL(),Vk=aP({argsMap:e=>[e.getTrackId()]}),xk=aP({argsMap:e=>[e.getTrackId()]}),Fk=BL(),sL((Bk=class extends Gk{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,n,i){super(t.createOutputTrack(),n,i),aL(this,"source",void 0),aL(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(HP.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(WP.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){qw(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[Ak,wk],Object.getOwnPropertyDescriptor(Bk.prototype,"startProcessAudioBuffer"),Bk.prototype),sL(Bk.prototype,"pauseProcessAudioBuffer",[Ok,Nk],Object.getOwnPropertyDescriptor(Bk.prototype,"pauseProcessAudioBuffer"),Bk.prototype),sL(Bk.prototype,"seekAudioBuffer",[Dk,Pk],Object.getOwnPropertyDescriptor(Bk.prototype,"seekAudioBuffer"),Bk.prototype),sL(Bk.prototype,"resumeProcessAudioBuffer",[Lk,kk],Object.getOwnPropertyDescriptor(Bk.prototype,"resumeProcessAudioBuffer"),Bk.prototype),sL(Bk.prototype,"stopProcessAudioBuffer",[Mk,Uk],Object.getOwnPropertyDescriptor(Bk.prototype,"stopProcessAudioBuffer"),Bk.prototype),sL(Bk.prototype,"close",[Vk],Object.getOwnPropertyDescriptor(Bk.prototype,"close"),Bk.prototype),sL(Bk.prototype,"setAudioBufferPlaybackSpeed",[xk,Fk],Object.getOwnPropertyDescriptor(Bk.prototype,"setAudioBufferPlaybackSpeed"),Bk.prototype),Bk),Kk=class e extends Gk{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=mL().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,$O(8,"track-mix-")),aL(this,"trackList",void 0),aL(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)?(UD.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):UD.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){UD.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}xO(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(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach((n=>{n instanceof e?n.emit(jP.TRANSCEIVER_UPDATED,t):n._updateRtpTransceiver(t)})))}},Yk=class extends RL{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(HP.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(),aL(this,"audioBuffer",void 0),aL(this,"sourceNode",void 0),aL(this,"startPlayTime",0),aL(this,"startPlayOffset",0),aL(this,"pausePlayTime",0),aL(this,"options",void 0),aL(this,"currentLoopCount",0),aL(this,"currentPlaybackSpeed",100),aL(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):UD.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 Hk=new Map;function Xk(e,t){if(0===e.length||0===t.length)return 1/0;const n=dN(e),i=dN(t);return Math.floor(i/n)}let Jk=class{get rendFrameRate(){const e=Math.max(1,Xk(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:nL.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(UD.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){aL(this,"trackId",void 0),aL(this,"config",void 0),aL(this,"onFirstVideoFrameDecoded",void 0),aL(this,"onFirstVideoFrameRender",void 0),aL(this,"onVideoBufferReady",void 0),aL(this,"onVideoStateChanged",void 0),aL(this,"freezeTimeCounterList",[]),aL(this,"renderFreezeAccTime",0),aL(this,"renderFreezeAccTime2",0),aL(this,"totalFreezeTime",0),aL(this,"isKeepLastFrame",!1),aL(this,"isDestroyed",!1),aL(this,"timeUpdatedCount",0),aL(this,"freezeTime",0),aL(this,"playbackTime",0),aL(this,"lastTimeUpdatedTime",0),aL(this,"autoplayFailed",!1),aL(this,"videoTrack",void 0),aL(this,"videoElement",void 0),aL(this,"cacheVideoElement",void 0),aL(this,"cancelRVFId",void 0),aL(this,"internal",!1),aL(this,"_render_interframe_delays",[]),aL(this,"_render_interframe_delays_sizes",[]),aL(this,"_videoState",iL.VideoStateStopped),aL(this,"videoElementCheckInterval",void 0),aL(this,"videoElementFreezeTimeout",void 0),aL(this,"_videoElementStatus",nL.NONE),aL(this,"_isInPage",!0),aL(this,"isGettingVideoDimensions",!1),aL(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return UD.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),aL(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===EL.curState&&(UD.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(pw())),Mw()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),aL(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&UD.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=nL.PLAYING;break;case"loadeddata":if(this.videoState=iL.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=nL.CANPLAY;break;case"stalled":this.videoElementStatus=nL.STALLED;break;case"suspend":this.videoElementStatus=nL.SUSPEND;break;case"pause":this.videoElementStatus=nL.PAUSED,Rw()||Uw()||mw()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(UD.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=nL.WAITING;break;case"abort":this.videoElementStatus=nL.ABORT;break;case"ended":this.videoElementStatus=nL.ENDED;break;case"emptied":this.videoElementStatus=nL.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=nL.ERROR,UD.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>iD("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,n=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,tU.lastVisibleTime<tU.lastHiddenTime||n<tU.lastHiddenTime||n<tU.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())return;for(t>iD("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}}})),aL(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(UD.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(pw())),Mw()?(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"),EL.on(vP.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),EL.on(vP.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&&VL(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(UD.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):UD.warning("[".concat(this.trackId,"] play warning: "),t)}));const n=lw();if(("Safari"===n.name&&15===Number(n.version)||Lw())&&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 UD.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const n=t.getImageData(0,0,e.width,e.height);return e.remove(),n}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const n=document.createElement("canvas");n.width=this.videoElement.videoWidth,n.height=this.videoElement.videoHeight;const i=n.getContext("2d");return i?(i.drawImage(this.videoElement,0,0,n.width,n.height),new Wh(((i,r)=>{n.toBlob((async e=>{if(n.remove(),e){const t=await ek(e);i({buffer:t,width:n.width,height:n.height})}else r(new Jw(Xw.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await $L(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,EL.off(vP.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),EL.off(vP.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=iL.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==nL.NONE&&this._videoElementStatus!==nL.DESTROYED||(this.videoElementStatus=nL.INIT),!this.videoElementCheckInterval&&(zk.forEach((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),iD("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let n;const i=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",i),this.videoElementFreezeTimeout=window.setTimeout(r,iD("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===iL.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=iL.VideoStateFrozen:document.addEventListener("visibilitychange",i))},o=(e,t)=>{if(this.videoElementStatus===nL.PLAYING){if(n){const e=t.presentationTime-n.presentationTime,i=t.presentedFrames-n.presentedFrames;this._render_interframe_delays_sizes.push(i),this._render_interframe_delays.push(e);const o=dN(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===iL.VideoStateStarting&&(this.videoState=iL.VideoStateDecoding),this.videoState===iL.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,iD("VIDEO_FREEZE_DURATION"))),e<iD("VIDEO_FREEZE_DURATION")&&this.videoState===iL.VideoStateFrozen&&(this.videoState=iL.VideoStateDecoding),e>iD("VIDEO_FREEZE_DURATION")&&tU.lastVisibleTime>=tU.lastHiddenTime&&n.timestamp>tU.lastVisibleTime&&n.timestamp>tU.lastHiddenTime){const t=Math.min(66,Xk(this._render_interframe_delays_sizes,this._render_interframe_delays)),n=Math.max(0,e-(i-1)*t),r=n>t?n:0;this.renderFreezeAccTime2+=r,this.totalFreezeTime+=r,this.renderFreezeAccTime+=e}}n=dL(dL({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(n=dL(dL({},t),{},{timestamp:e}));var i,s;iD("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(i=(s=this.videoElement).requestVideoFrameCallback)||void 0===i?void 0:i.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",""),Gw()&&!iD("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const n=lw();this.config.noStyle||("Safari"===n.name&&15===Number(n.version)||Lw()||!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,Tw()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Tw()&&this.videoElement.load());const i=this.videoElement.play();void 0!==i&&i.catch((e=>{UD.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;zk.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=nL.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===nL.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{UD.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{UD.error(e)})),this.autoplayFailed=!1,jw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};jw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),UL()}};const zk=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];let Zk=class extends Jk{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),aL(this,"container",void 0),aL(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 n;!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===(n=this.slot)||void 0===n||n.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 n=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,n):await $L(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",iD("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 qk,Qk,$k,eM,tM,nM,iM,rM,oM,sM,aM,cM,dM,lM,uM,hM,pM,_M,EM,mM,fM,gM,SM,TM,RM,vM,yM,CM,bM,IM,AM,wM,OM,NM,DM,PM,LM,kM;let MM=(qk=aP({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),Qk=BL(),$k=aP({argsMap:e=>[e.getTrackId()]}),eM=_N("LocalVideoTrack","_enabledMutex"),tM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),nM=BL(),iM=_N("LocalVideoTrack","_enabledMutex"),rM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),oM=BL(),sM=aP({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),aM=BL(),cM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),dM=BL(),lM=BL(),uM=aP({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),hM=BL(),pM=BL(),_M=BL(),EM=aP({argsMap:e=>[e.getTrackId()]}),mM=BL(),fM=BL(),gM=BL(),SM=BL(),TM=BL(),RM=aP({argsMap:(e,t)=>[e.getTrackId(),t.name]}),vM=aP({argsMap:e=>[e.getTrackId()]}),yM=aP({argsMap:e=>[e.getTrackId()]}),CM=aP({argsMap:(e,t,n)=>[e.getTrackId(),t.label,n]}),bM=class e extends uL{get videoHeight(){if(mw()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(mw()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==nL.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,n,i,r,o){if(super(e,r),aL(this,"trackMediaType",YP.VIDEO),aL(this,"_player",void 0),aL(this,"isUseScaleResolutionDownBy",!1),aL(this,"_videoVisibleTimer",null),aL(this,"_previousVideoVisibleStatus",void 0),aL(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),aL(this,"_encoderConfig",void 0),aL(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),aL(this,"_optimizationMode",void 0),aL(this,"_saveEncodeBitrateRatio",1),aL(this,"_videoHeight",void 0),aL(this,"_videoWidth",void 0),aL(this,"_forceBitrateLimit",void 0),aL(this,"_enabled",!0),aL(this,"_processorDestination",void 0),aL(this,"_processorContext",void 0),mw()){const{width:t,height:n}=e.getSettings();this._videoWidth=t,this._videoHeight=n}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=n,this._optimizationMode=i,this._hints=o||[],t&&-1!==this._hints.indexOf(xP.CUSTOM_TRACK)?this._encoderConfig=GO(t):this._encoderConfig=t,-1===this._hints.indexOf(xP.SCREEN_TRACK))this.updateBitrateFromProfile();else if(Cw(sw.CHROME,115)&&-1!==hw().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&uP().supportWebRTCInsertableStream){const n=new MediaStreamTrackProcessor(e),i=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,i.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{"live"===i.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return i.addEventListener("ended",a),n.readable.pipeThrough(d).pipeTo(i.writable),i}}(e);t&&(UD.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(xP.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new jL(this.getTrackId(),"local"),this._processorDestination=new GL(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:(UD.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}UD.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=dL(dL(dL({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(n):(e instanceof HTMLVideoElement?this._player=new Jk(n):this._player=new Zk(n),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(WP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),iD("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,UD.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(UD.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await OO(this,VP.NEED_DISABLE_TRACK,this)}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void UD.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await OO(this,VP.NEED_ENABLE_TRACK,this)}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}UD.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,UD.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await OO(this,VP.NEED_MUTE_TRACK,this):await OO(this,VP.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),UD.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await OO(this,VP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(UD)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Jw(Xw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=NP(e),iD("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=JL({encoderConfig:e});(mw()||Rw()||Uw())&&(t.deviceId=void 0),UD.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(Xw.UNEXPECTED_ERROR,e.toString());throw UD.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(xP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await OO(this,VP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(UD)}}getStats(){KO((()=>{UD.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return NO(this,VP.GET_STATS)||dL({},JP)}async setBeautyEffect(e){UD.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 $L(e)}async findClosestProfile(){const{width:e,height:t,frameRate:n}=this.getMediaStreamTrackSettings(),{width:i,height:r,frameRate:o}=this._encoderConfig||{},s=aN(this._videoWidth||e||i||0),a=aN(this._videoHeight||t||r||0),c=function(e,t,n){if(!Array.isArray(iD("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===iD("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const i=Math.min(e,t);return!(i>=480)&&dL(dL({},iD("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>i))),{},{frameRate:n})}(s,a,aN(n||o||15));if(c)return UD.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(s,"x").concat(a," => ").concat(JSON.stringify(c))),this.setEncoderConfiguration(c)}async setBitrateLimit(e){UD.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 UD.error(Xw.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await OO(this,VP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,UD.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}UD.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return UD.error(Xw.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,UD.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){XL(this._originMediaStreamTrack).then((e=>{let[t,n]=e;this._videoHeight=n,this._videoWidth=t})).catch(tN)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new Jw(Xw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");UD.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=NP(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(xP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await OO(this,VP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(UD)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:n}=this.getMediaStreamTrackSettings();if(!e||!t||!n)return;const{bitrateMax:i,bitrateMin:r}=this._encoderConfig;if(null==r||null==i){const{max:o,min:s}=function(e,t,n,i,r){const o=iD("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:i,max:r};if(void 0===r){var s;const a=Math.floor(200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*a:2*a,i=null!==(s=i)&&void 0!==s?s:a}else{var a;i=null!==(a=i)&&void 0!==a?a:Math.floor(r/10)}return{min:i,max:r}}(e,t,n,r,i);if(this._encoderConfig.bitrateMin=s,this._encoderConfig.bitrateMax=o,iD("VIDEO_STANDARD_BITRATE_VERSION")&&null==r&&null==i){const[i,r]=function(e,t,n){const i=4*Math.floor(2e5*Math.pow(n/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=Qh(o).call(o).next().value,c=1;if(o.has(r))a=o.get(r);else{var d;const e=Jp(d=Array.from(o.entries())).call(d,((e,t)=>{let[n]=e,[i]=t;return n-i})),t=e.find((e=>{let[t]=e;return t>r}));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);a=i[1]+o*(t[1]-i[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=Jp(l=Array.from(s.entries())).call(l,((e,t)=>{let[n]=e,[i]=t;return n-i})),t=e.find((e=>{let[t]=e;return t>r}));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);c=i[1]+o*(t[1]-i[1])}else c=t[1]}else c=e[e.length-1][1]}const u=iD("VIDEO_NEW_BITRATE_RATIO");u&&u>0&&(a=u/100);const h=Math.floor(i*a),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(n/15,.69));let _=h;const E=iD("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=i:2===E?_=h:3===E&&(_=p)),[Math.floor(_/1e3),c]}(e,t,n);this._encoderConfig.bitrateMax=i,this._encoderConfig.bitrateMin=s?Math.min(s,i):i,this._saveEncodeBitrateRatio=r,UD.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(n,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else UD.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(n,"] => [brMax: ").concat(o,", brMin: ").concat(s,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},{element:r,slot:o}=i;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=aO.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=cP.reportApiInvoke(null,{tag:EO.TRACER,name:_O.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(Xw.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Jw(Xw.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 n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=dL(dL({},i),NP(t))),i=jO(i);const r=$O(8,"track-video-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,jO(this._scalabilityMode),this._optimizationMode,r,jO(this._hints));return t&&i&&o.setEncoderConfiguration(i),UD.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Jw(Xw.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Jw(Xw.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(KO((()=>{cP.reportApiInvoke(null,{name:_O.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:EO.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!iD("ENABLE_VIDEO_SEI")||!iD("ENABLE_ENCODED_TRANSFORM"))return void UD.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new Jw(Xw.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void UD.warning("Video track is not published, SEI can not be send");const n=t.sender.getParameters();if(0===n.codecs.length)return;const i=n.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===i||"video/h265"===i?this.safeEmit("sei-to-send",e):UD.warning("SEI is not supported by ".concat(i))}bindProcessorDestinationEvents(){this.processorDestination.on(QP.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await OO(this,VP.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await OO(this,VP.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(QP.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners($P.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners($P.REQUEST_CONSTRAINTS)}},sL(bM.prototype,"play",[qk,Qk],Object.getOwnPropertyDescriptor(bM.prototype,"play"),bM.prototype),sL(bM.prototype,"stop",[$k],Object.getOwnPropertyDescriptor(bM.prototype,"stop"),bM.prototype),sL(bM.prototype,"setEnabled",[eM,tM,nM],Object.getOwnPropertyDescriptor(bM.prototype,"setEnabled"),bM.prototype),sL(bM.prototype,"setMuted",[iM,rM,oM],Object.getOwnPropertyDescriptor(bM.prototype,"setMuted"),bM.prototype),sL(bM.prototype,"setSaveEncodeBitrateRatio",[sM,aM],Object.getOwnPropertyDescriptor(bM.prototype,"setSaveEncodeBitrateRatio"),bM.prototype),sL(bM.prototype,"setEncoderConfiguration",[cM,dM],Object.getOwnPropertyDescriptor(bM.prototype,"setEncoderConfiguration"),bM.prototype),sL(bM.prototype,"getStats",[lM],Object.getOwnPropertyDescriptor(bM.prototype,"getStats"),bM.prototype),sL(bM.prototype,"setBeautyEffect",[uM,hM],Object.getOwnPropertyDescriptor(bM.prototype,"setBeautyEffect"),bM.prototype),sL(bM.prototype,"getCurrentFrameData",[pM],Object.getOwnPropertyDescriptor(bM.prototype,"getCurrentFrameData"),bM.prototype),sL(bM.prototype,"getCurrentFrameImage",[_M],Object.getOwnPropertyDescriptor(bM.prototype,"getCurrentFrameImage"),bM.prototype),sL(bM.prototype,"findClosestProfile",[EM,mM],Object.getOwnPropertyDescriptor(bM.prototype,"findClosestProfile"),bM.prototype),sL(bM.prototype,"setBitrateLimit",[fM],Object.getOwnPropertyDescriptor(bM.prototype,"setBitrateLimit"),bM.prototype),sL(bM.prototype,"setOptimizationMode",[gM],Object.getOwnPropertyDescriptor(bM.prototype,"setOptimizationMode"),bM.prototype),sL(bM.prototype,"setScalabiltyMode",[SM],Object.getOwnPropertyDescriptor(bM.prototype,"setScalabiltyMode"),bM.prototype),sL(bM.prototype,"updateMediaStreamTrackResolution",[TM],Object.getOwnPropertyDescriptor(bM.prototype,"updateMediaStreamTrackResolution"),bM.prototype),sL(bM.prototype,"pipe",[RM],Object.getOwnPropertyDescriptor(bM.prototype,"pipe"),bM.prototype),sL(bM.prototype,"unpipe",[vM],Object.getOwnPropertyDescriptor(bM.prototype,"unpipe"),bM.prototype),sL(bM.prototype,"close",[yM],Object.getOwnPropertyDescriptor(bM.prototype,"close"),bM.prototype),sL(bM.prototype,"replaceTrack",[CM],Object.getOwnPropertyDescriptor(bM.prototype,"replaceTrack"),bM.prototype),bM),UM=(IM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),AM=BL(),wM=_N("CameraVideoTrack","_enabledMutex"),OM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),NM=BL(),DM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),PM=BL(),LM=aP({argsMap:e=>[e.getTrackId()]}),kM=class e extends MM{get __className__(){return"CameraVideoTrack"}constructor(e,t,n,i,r,o){super(e,NP(t.encoderConfig),i,r,o),aL(this,"_config",void 0),aL(this,"_originalConstraints",void 0),aL(this,"_constraints",void 0),aL(this,"_enabled",!0),aL(this,"_deviceName","default"),aL(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(Lw()||kw())&&!function(){const e=lw();if(e.os!==ow.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&Vw()&&this._enabled&&!this._isClosed&&(UD.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=n,this._constraints=n,this._deviceName=e.label,this._encoderConfig=NP(this._config.encoderConfig),EL.on(vP.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),EL.on(vP.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(UD.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await LL.getDeviceById(e),n={};n.video=dL({},this._constraints),n.video.deviceId={exact:e},n.video.facingMode=void 0,this._originMediaStreamTrack.stop();let i=null;try{i=await OL(n,this.getTrackId())}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await OL({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await LL.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}UD.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){UD.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:dL(dL({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await OL(t,this.getTrackId())}catch(t){throw UD.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await OL({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=dL({},t.video),UD.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(UD.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await OL({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await OO(this,VP.NEED_ENABLE_TRACK,this)}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),UD.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 OO(this,VP.NEED_DISABLE_TRACK,this)}catch(e){throw UD.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}UD.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Jw(Xw.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=NP(e),iD("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 n=GO(this._config);n.encoderConfig=e;const i=JL(n);(mw()||Rw()||Uw())&&(i.deviceId=void 0),UD.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(i));try{await this._originMediaStreamTrack.applyConstraints(i),this.updateMediaStreamTrackResolution()}catch(e){const t=new Jw(Xw.UNEXPECTED_ERROR,e.toString());throw UD.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=n,this._constraints=i,this._originalConstraints=i,this._encoderConfig=e,-1===this._hints.indexOf(xP.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await OO(this,VP.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(UD)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Rw()||Uw())&&this._enabled&&!this._isClosed&&EL.duringInterruption){const e=async()=>{EL.off(vP.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(UD.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};EL.on(vP.IOS_INTERRUPTION_END,e)}else UD.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(WP.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=LL.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId={exact:n}),this._enabled){const e=await OL({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),EL.off(vP.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),EL.off(vP.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=dL(dL({},i),NP(t))),i=jO(i);const r=$O(8,"track-cam-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,jO(dL(dL({},this._config),{},{encoderConfig:i})),jO(this._constraints),jO(this._scalabilityMode),this._optimizationMode,r);return t&&i&&o.setEncoderConfiguration(i),UD.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}bindProcessorContextEvents(){this.processorContext.on($P.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}})),this.processorContext.on($P.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},sL(kM.prototype,"setDevice",[IM,AM],Object.getOwnPropertyDescriptor(kM.prototype,"setDevice"),kM.prototype),sL(kM.prototype,"setEnabled",[wM,OM,NM],Object.getOwnPropertyDescriptor(kM.prototype,"setEnabled"),kM.prototype),sL(kM.prototype,"setEncoderConfiguration",[DM,PM],Object.getOwnPropertyDescriptor(kM.prototype,"setEncoderConfiguration"),kM.prototype),sL(kM.prototype,"close",[LM],Object.getOwnPropertyDescriptor(kM.prototype,"close"),kM.prototype),kM);function VM(e){const t=$O(8,"track-cus-"),n=cP.reportApiInvoke(null,{id:t,tag:EO.TRACER,name:_O.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new Gk(e.mediaStreamTrack,e.encoderConfig?kP(e.encoderConfig):{},t,!1);return UD.info("create custom audio track success with config",e,"trackId",i.getTrackId()),n.onSuccess(i.getTrackId()),i}function xM(e,t,n,i){n.optimizationMode&&(i&&i.width&&i.height?(n.encoderConfig=dL(dL({},i),{},{bitrateMin:i.bitrateMin,bitrateMax:i.bitrateMax}),"motion"!==n.optimizationMode&&"detail"!==n.optimizationMode||(t.contentHint=n.optimizationMode,t.contentHint===n.optimizationMode?UD.debug("[".concat(e,"] set content hint to"),n.optimizationMode):UD.debug("[".concat(e,"] set content hint failed")))):UD.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var FM,BM,GM,jM,WM,KM,YM,HM,XM,JM,zM,ZM,qM;let QM=class extends lL{getUserId(){return this._userId}constructor(e,t,n,i){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(i.clientId,"_").concat($O(5,""))),aL(this,"_userId",void 0),aL(this,"_uintId",void 0),aL(this,"_isDestroyed",!1),aL(this,"store",void 0),aL(this,"processor",void 0),aL(this,"processorContext",void 0),this._userId=t,this._uintId=n,this.store=i}_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,UD.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}},$M=(FM=aP({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),BM=aP({argsMap:e=>[e.getTrackId()]}),GM=aP({argsMap:(e,t)=>[e.getTrackId(),t.name]}),jM=aP({argsMap:e=>[e.getTrackId()]}),sL((WM=class extends QM{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==nL.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,n,i,r){super(e,t,n,i),aL(this,"_videoVisibleTimer",null),aL(this,"_previousVideoVisibleStatus",void 0),aL(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),aL(this,"trackMediaType",YP.VIDEO),aL(this,"_videoWidth",void 0),aL(this,"_videoHeight",void 0),aL(this,"_player",void 0),aL(this,"_prePlayer",void 0),aL(this,"processorDestination",void 0),aL(this,"processorContext",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new jL(this.getTrackId(),"remote"),this.processorDestination=new GL(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return KO((()=>{UD.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),NO(this,VP.GET_STATS)||dL({},qP)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(KP.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(UD.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}UD.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=dL(dL({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(n);else{let t=!1,i=!1;const r=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!r&&(this._prePlayer.destroy(),i=!0),r?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(n)):this._player=e instanceof HTMLVideoElement?new Jk(n):new Zk(n),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(KP.FIRST_FRAME_DECODED),i&&this.safeEmit(KP.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(KP.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(KP.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),iD("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(KP.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,UD.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){XL(this._originMediaStreamTrack).then((e=>{let[t,n]=e;this._videoHeight=n,this._videoWidth=t})).catch(tN)}_updatePlayerSource(){UD.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},{element:r,slot:o}=i;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=aO.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=cP.reportApiInvoke(null,{tag:EO.TRACER,name:_O.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(Xw.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Jw(Xw.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(QP.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(QP.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(jP.SEI_RECEIVED,e)}}).prototype,"play",[FM],Object.getOwnPropertyDescriptor(WM.prototype,"play"),WM.prototype),sL(WM.prototype,"stop",[BM],Object.getOwnPropertyDescriptor(WM.prototype,"stop"),WM.prototype),sL(WM.prototype,"pipe",[GM],Object.getOwnPropertyDescriptor(WM.prototype,"pipe"),WM.prototype),sL(WM.prototype,"unpipe",[jM],Object.getOwnPropertyDescriptor(WM.prototype,"unpipe"),WM.prototype),WM),eU=(KM=aP({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),YM=aP({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),HM=aP({argsMap:(e,t)=>[e.getTrackId(),t]}),XM=aP({argsMap:e=>[e.getTrackId()]}),JM=aP({argsMap:e=>[e.getTrackId()]}),zM=aP({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ZM=aP({argsMap:e=>[e.getTrackId()]}),sL((qM=class extends QM{get isPlaying(){return this._useAudioElement?FL.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,n,i){super(e,t,n,i),aL(this,"trackMediaType",YP.AUDIO),aL(this,"_source",void 0),aL(this,"_useAudioElement",!0),aL(this,"_volume",100),aL(this,"processorContext",void 0),aL(this,"processorDestination",void 0),aL(this,"_played",!1),aL(this,"_bypassWebAudio",!1),iD("DISABLE_WEBAUDIO")?(this._source=new YL,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new vL(e,!0),iD("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(HP.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(KP.FIRST_FRAME_DECODED)})),this.processorContext=new KL(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new WL(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(HP.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(HP.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(HP.ON_AUDIO_BUFFER),this._source.on(HP.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?FL.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(FL.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,iD("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!hP())throw new Jw(Xw.NOT_SUPPORTED,"your browser does not support setting the audio output device");await FL.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?FL.getVolume(this.getTrackId()):this._source instanceof vL?this._source.getAudioVolume():0}getStats(){return KO((()=>{UD.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),NO(this,VP.GET_STATS)||dL({},zP)}play(){UD.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(UD.debug("[".concat(this.getTrackId(),"] use audio element to play")),FL.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):(UD.debug("[".concat(this.getTrackId(),"] use audio context to play")),this._source.play())}stop(){UD.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?FL.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];UD.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&FL.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new Jw(Xw.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Jw(Xw.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(Xw.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(QP.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(QP.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(QP.ON_TRACK),this.processorDestination.removeAllListeners(QP.ON_NODE)}}).prototype,"setVolume",[KM],Object.getOwnPropertyDescriptor(qM.prototype,"setVolume"),qM.prototype),sL(qM.prototype,"setAmplifiedVolume",[YM],Object.getOwnPropertyDescriptor(qM.prototype,"setAmplifiedVolume"),qM.prototype),sL(qM.prototype,"setPlaybackDevice",[HM],Object.getOwnPropertyDescriptor(qM.prototype,"setPlaybackDevice"),qM.prototype),sL(qM.prototype,"play",[XM],Object.getOwnPropertyDescriptor(qM.prototype,"play"),qM.prototype),sL(qM.prototype,"stop",[JM],Object.getOwnPropertyDescriptor(qM.prototype,"stop"),qM.prototype),sL(qM.prototype,"pipe",[zM],Object.getOwnPropertyDescriptor(qM.prototype,"pipe"),qM.prototype),sL(qM.prototype,"unpipe",[ZM],Object.getOwnPropertyDescriptor(qM.prototype,"unpipe"),qM.prototype),qM);const tU=new class extends uO{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),aL(this,"_lastHiddenTime",0),aL(this,"_lastVisibleTime",0),aL(this,"needUploadStats",[]),aL(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),UD.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}};let nU=class extends uO{constructor(e,t){super(),aL(this,"trackMediaType",YP.DATA),aL(this,"_version",1),aL(this,"_type",3),aL(this,"_config",void 0),aL(this,"_originDataChannel",void 0),aL(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),aL(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),aL(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 iD("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 n=setTimeout((()=>{var e;t(new Jw(Xw.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(n),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(n),new Jw(Xw.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new Jw(Xw.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),[oL.OPEN,oL.CLOSE,oL.ERROR].forEach((t=>{const n=()=>{this.emit(t)};this._datachannelEventMap.set(t,n),e.addEventListener(t,n)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[n,i]=t;e.removeEventListener(n,i)})),this._datachannelEventMap.clear()}},iU=class extends nU{constructor(e){super(e),aL(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),n=new DataView(t).getUint8(3);if(n!==this.id)return void(iD("SHOW_DATASTREAM2_LOG")&&UD.debug("invalid datachannel id: ".concat(n," !== ").concat(this.id)));let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(oL.MESSAGE,i)}}_updateDataChannelConfig(e){this._config=e}_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)}},rU=class extends nU{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const n=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);n.set(new Uint8Array(this._dataStreamPacketHeader),0),n.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(n.buffer)}}};function oU(){const e=new Blob([atob("Y29uc3QgdD0idmlkZW8vaDI2NCIsZT0idmlkZW8vaDI2NSI7ZnVuY3Rpb24gbih0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLHI9W10sbz0wO2Zvcig7ci5sZW5ndGg8bjspbyszPG4mJjA9PT1hW29dJiYwPT09YVtvKzFdJiYzPT09YVtvKzJdJiYoMD09PWFbbyszXXx8MT09PWFbbyszXXx8Mj09PWFbbyszXXx8Mz09PWFbbyszXSk/KHIucHVzaChhW29dLGFbbysxXSxhW28rM10pLG8rPTQpOihyLnB1c2goYVtvXSksbysrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocil9ZnVuY3Rpb24gYShhLHIpe3N3aXRjaChyKXtjYXNlIHQ6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IGE9MDtmb3IoO2ErNDx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KGErMCkmJjA9PT1lLmdldFVpbnQ4KGErMSkmJjA9PT1lLmdldFVpbnQ4KGErMikmJjE9PT1lLmdldFVpbnQ4KGErMykmJjY9PT1lLmdldFVpbnQ4KGErNCkpe2xldCByPWErNixvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1uKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1hKyt9cmV0dXJuIG51bGx9KGEpO2Nhc2UgZTpyZXR1cm4gZnVuY3Rpb24odCl7Y29uc3QgZT1uZXcgRGF0YVZpZXcodC5kYXRhKTtsZXQgYT0wO2Zvcig7YSs1PHQuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PWUuZ2V0VWludDgoYSswKSYmMD09PWUuZ2V0VWludDgoYSsxKSYmMD09PWUuZ2V0VWludDgoYSsyKSYmMT09PWUuZ2V0VWludDgoYSszKSYmNzg9PT1lLmdldFVpbnQ4KGErNCkmJjE9PT1lLmdldFVpbnQ4KGErNSkmJjEwMT09PWUuZ2V0VWludDgoYSs2KSl7bGV0IHI9YSs3LG89MCxpPTA7Zm9yKDsyNTU9PT0oaT1lLmdldFVpbnQ4KHIrKykpOylvKz0yNTU7bys9aTtjb25zdCBzPW4odC5kYXRhLHIsbyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KHMpfWErK31yZXR1cm4gbnVsbH0oYSk7ZGVmYXVsdDpyZXR1cm4gbnVsbH19ZnVuY3Rpb24gcih0KXtjb25zdCBlPXQubGVuZ3RoO2xldCBuPVtdLGE9MDtmb3IoO2E8ZTspYSsyPGUmJjA9PT10W2FdJiYwPT09dFthKzFdJiYoMD09PXRbYSsyXXx8MT09PXRbYSsyXXx8Mj09PXRbYSsyXXx8Mz09PXRbYSsyXSk/KG4ucHVzaCh0W2FdLHRbYSsxXSwzLHRbYSsyXSksYSs9Myk6KG4ucHVzaCh0W2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShuKX1mdW5jdGlvbiBvKG4sYSxvKXtzd2l0Y2gobyl7Y2FzZSB0OnJldHVybiBmdW5jdGlvbih0LGUpe2NvbnN0IG49cihlKSxhPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihhLzI1NSksaT1hJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK2ErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09aSxmKysscy5zZXQobiw2K2YpLHMuc2V0KG5ldyBVaW50OEFycmF5KHQpLDYrZithKSxzLmJ1ZmZlcn0obixhKTtjYXNlIGU6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1yKGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxpPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNytvKzErYSsxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09aSxmKysscy5zZXQobiw3K2YpLGYrPWEsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0obixhKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBpKG4pe2lmKG4ubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGE9LTE7Zm9yKGxldCB0PTA7dDxuLmxlbmd0aC0zO3QrKyl7aWYoMD09PW5bdF0mJjA9PT1uW3QrMV0mJjE9PT1uW3QrMl0pe2E9dDticmVha31pZih0PG4ubGVuZ3RoLTQmJjA9PT1uW3RdJiYwPT09blt0KzFdJiYwPT09blt0KzJdJiYxPT09blt0KzNdKXthPXQ7YnJlYWt9fWlmKC0xPT09YSlyZXR1cm4iIjtjb25zdCByPWErKDA9PT1uW2ErMl0/NDozKTtpZihyPj1uLmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPW5bcl07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gZTtpZihyKzE8bi5sZW5ndGgpe2lmKDA9PSgyNDgmbltyKzFdKSlyZXR1cm4gZX1yZXR1cm4oMzEmbyk8PTMxP3Q6IiJ9Y29uc3Qgcz03MSxmPTEsbD0yLHU9MSxnPTI7dmFyIGM7ZnVuY3Rpb24gZCh0LGU9ITEpe2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09cylyZXR1cm47Y29uc3QgYT10LmdldFVpbnQxNigxKSxyPWYrbCthLG89bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLXIpO28uc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHIsdC5ieXRlTGVuZ3RoLXIpKTtjb25zdCBpPXttOm4sdGx2TGVuOmEsdGx2OltdLGZyYW1lOm99O2xldCBkPWYrbDtmb3IoO2Q8cjspe2NvbnN0IG49dC5nZXRVaW50OChkKSxhPXQuZ2V0VWludDE2KGQrdSkscj11K2c7aWYobj09PWMuQVVESU9fTEVWRUwpe2xldCBvPXQuZ2V0VWludDgoZCtyKTtmb3IobGV0IGU9MTtlPGE7ZSsrKW89bzw8OHx0LmdldFVpbnQ4KGQrcitlKTtpLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6YSx2YWx1ZTplPzEyN15vPj4xOjEyNyZvfSl9ZWxzZSBpZihuPT09Yy5NRVRBREFUQXx8bj09PWMuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShhKTtmb3IobGV0IG49MDtuPGE7bisrKWVbbl09dC5nZXRVaW50OChkK3Irbik7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZX0pfWQrPXIrYX1yZXR1cm4gaX0hZnVuY3Rpb24odCl7dFt0LkFVRElPX0xFVkVMPTFdPSJBVURJT19MRVZFTCIsdFt0Lk1FVEFEQVRBPTJdPSJNRVRBREFUQSIsdFt0LkFVRElPXzY0X0JJVF9QVFM9M109IkFVRElPXzY0X0JJVF9QVFMifShjfHwoYz17fSkpLHNlbGYub25ydGN0cmFuc2Zvcm09dD0+e2NvbnN0IGU9dC50cmFuc2Zvcm1lcixuPVtdLHI9W107bGV0IGg9bnVsbDtlLm9wdGlvbnMucG9ydC5vbm1lc3NhZ2U9dD0+e3QuZGF0YS5zZWkmJm4ucHVzaCh0LmRhdGEuc2VpKSx0LmRhdGEubWV0YWRhdGEmJnIucHVzaCh0LmRhdGEubWV0YWRhdGEpfSxzZWxmLnBvc3RNZXNzYWdlKCJzdGFydGVkIik7Y29uc3QgcD1lLnJlYWRhYmxlLmdldFJlYWRlcigpLFU9ZS53cml0YWJsZS5nZXRXcml0ZXIoKTsic2VpLXJ4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KG4udmFsdWUuZGF0YSkpLHI9YShuLnZhbHVlLHQpO2lmKHImJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtzZWk6cn0pLCFoKXtjb25zdCB0PW4udmFsdWUuZ2V0TWV0YWRhdGEoKXx8e307aD17dHlwZTpuLnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOm4udmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOnQucGF5bG9hZFR5cGV8fDAsc3NyYzp0LnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6bi52YWx1ZS5kYXRhLmJ5dGVMZW5ndGgsLi4uIm1pbWVUeXBlImluIHQ/e21pbWVUeXBlOnQubWltZVR5cGV9Ont9fSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7Zmlyc3RGcmFtZUluZm86aH0pfX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToic2VpLXR4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigoYT0+e2lmKCFhLmRvbmUpe2lmKGEudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KGEudmFsdWUuZGF0YSkpLGU9bi5zaGlmdCgpO2lmKGUpe2NvbnN0IG49byhhLnZhbHVlLmRhdGEsZSx0KTtuJiYoYS52YWx1ZS5kYXRhPW4pfX1VLndyaXRlKGEudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtcngiPT09ZS5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXtwLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYobi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PW5ldyBEYXRhVmlldyhuLnZhbHVlLmRhdGEpLGE9dC5nZXRVaW50OCgwKTtsZXQgcjtpZigwIT0oMTI4JmEpJiY3MSE9PWEpe2NvbnN0IGU9ZnVuY3Rpb24odCl7aWYodC5ieXRlTGVuZ3RoPD0wKXJldHVybltdO2NvbnN0IGU9W107bGV0IG49MDtmb3IoO248dC5ieXRlTGVuZ3RoOyl7Y29uc3QgYT0oMTI4JnQuZ2V0VWludDgobikpPj43LHI9MTI3JnQuZ2V0VWludDgobik7aWYoIShhJiZuKzQ8PXQuYnl0ZUxlbmd0aCkpe24rKzticmVha317Y29uc3QgYT10LmdldFVpbnQzMihuLCExKSxvPSgxNjc3NjE5MiZhKT4+MTAsaT0xMDIzJmE7ZS5wdXNoKHtwdDpyLHRzX29mZnNldDpvLGxlbmd0aDppLGRhdGE6bmV3IFVpbnQ4QXJyYXl9KSxuKz00fX1sZXQgYT10LmJ5dGVMZW5ndGgtbjtmb3IoY29uc3QgciBvZiBlKXtpZihyLmxlbmd0aD5hKXJldHVybiBjb25zb2xlLndhcm4oIkJyb2tlbiByZWQgcGF5bG9hZCIpLFtdO3IubGVuZ3RoPjAmJihyLmRhdGE9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sci5sZW5ndGgpLG4rPXIubGVuZ3RoLGEtPXIubGVuZ3RoKX1pZihhPjApe2NvbnN0IHI9e3B0OmUubGVuZ3RoPjA/ZVtlLmxlbmd0aC0xXS5wdDowLHRzX29mZnNldDowLGxlbmd0aDphLGRhdGE6bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sYSl9O2UucHVzaChyKX1yZXR1cm4gZX0odCk7aWYoZS5sZW5ndGg+MCl7Y29uc3QgdD1mdW5jdGlvbih0KXtsZXQgZT0wO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKWUrPW48dC5sZW5ndGgtMT80OjEsZSs9dFtuXS5sZW5ndGg7Y29uc3Qgbj1uZXcgVWludDhBcnJheShlKTtsZXQgYT0wO2ZvcihsZXQgZT0wO2U8dC5sZW5ndGg7ZSsrKWlmKGU8dC5sZW5ndGgtMSl7Y29uc3Qgcj0oMjE0NzQ4MzY0OHwoMTI3JnRbZV0ucHQpPDwyNHwoMjYyMTQzJnRbZV0udHNfb2Zmc2V0KTw8MTB8MTAyMyZ0W2VdLmxlbmd0aCk+Pj4wO25bYSsrXT1yPj4yNCYyNTUsblthKytdPXI+PjE2JjI1NSxuW2ErK109cj4+OCYyNTUsblthKytdPTI1NSZyfWVsc2UgblthKytdPTEyNyZ0W2VdLnB0O2Zvcihjb25zdCBlIG9mIHQpbi5zZXQoZS5kYXRhLGEpLGErPWUubGVuZ3RoO3JldHVybiBufShlLm1hcCgodD0+e2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkodC5sZW5ndGgpO2Uuc2V0KHQuZGF0YSk7Y29uc3Qgbj1kKG5ldyBEYXRhVmlldyhlLmJ1ZmZlcikpO3JldHVybiBuPy5mcmFtZSYmKHQuZGF0YT1uPy5mcmFtZSkscj1uLHR9KSkpO24udmFsdWUuZGF0YT10LmJ1ZmZlcn19ZWxzZSByPWQodCksciYmKG4udmFsdWUuZGF0YT1yLmZyYW1lLmJ1ZmZlcik7aWYocil7bGV0IHQ9ci50bHYuZmluZCgodD0+dC50YWc9PT1jLk1FVEFEQVRBKSk7aWYodCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHttZXRhZGF0YTp0LnZhbHVlfSksdD1yLnRsdi5maW5kKCh0PT50LnRhZz09PWMuQVVESU9fNjRfQklUX1BUUykpLHQmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiY4PT10LnZhbHVlLmxlbmd0aCl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcodC52YWx1ZS5idWZmZXIpLmdldEJpZ1VpbnQ2NCgwLCEwKTt0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3B0czpufSl9fX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtdHgiPT09ZS5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtnZXRNZXRhZGF0YTohMH0pLG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1yLnNoaWZ0KCk7dCYmKG4udmFsdWUuZGF0YT1mdW5jdGlvbih0LGUsbil7Y29uc3QgYT1uLmJ5dGVMZW5ndGgscj1hK3UrZyxvPWYrbCtyLGk9bmV3IEFycmF5QnVmZmVyKHQuYnl0ZUxlbmd0aCtvKSxjPW5ldyBEYXRhVmlldyhpKTtjLnNldFVpbnQ4KDAscyksYy5zZXRVaW50MTYoMSxyKSxjLnNldFVpbnQ4KDMsZSksYy5zZXRVaW50MTYoNCxhKTtmb3IobGV0IHQ9MDt0PGE7dCsrKWMuc2V0VWludDgoNit0LG5bdF0pO2NvbnN0IGQ9bmV3IFVpbnQ4QXJyYXkoYy5idWZmZXIpO3JldHVybiBkLnNldChuZXcgVWludDhBcnJheSh0KSxvKSxkLmJ1ZmZlcn0obi52YWx1ZS5kYXRhLGMuQVVESU9fNjRfQklUX1BUUyx0KSl9VS53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0oZSl9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKTsK")],{type:"text/javascript"});return setTimeout((()=>Qf.revokeObjectURL(e)),0),new Worker(Qf.createObjectURL(e))}const sU=71,aU=1,cU=2,dU=1,lU=2;var uU=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}(uU||{});function hU(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.getUint8(0);if(n!==sU)return;const i=e.getUint16(1),r=aU+cU+i,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:n,tlvLen:i,tlv:[],frame:o};let a=aU+cU;for(;a<r;){const n=e.getUint8(a),i=e.getUint16(a+dU),r=dU+lU;if(n===uU.AUDIO_LEVEL){let o=e.getUint8(a+r);for(let t=1;t<i;t++)o=o<<8|e.getUint8(a+r+t);s.tlv.push({tag:n,length:i,value:t?127^o>>1:127&o})}else if(n===uU.METADATA||n===uU.AUDIO_64_BIT_PTS){const t=new Uint8Array(i);for(let n=0;n<i;n++)t[n]=e.getUint8(a+r+n);s.tlv.push({tag:n,length:i,value:t})}a+=r+i}return s}const pU=new Map;const _U=127,EU=1e-10,mU=139/13,fU=new Map;function gU(e,t,n){const i="".concat(e,"-").concat(t,"-").concat(n);let r=0;if(fU.has(i))r=fU.get(i);else{const o=.5;r=Math.log(function(e,t){const n=e-t;t<n&&(t=n);let i=1;for(let n=e,r=1;n>t;n--,r++)i=i*n/r;return i}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(n)+n*e,fU.set(i,r)}return r<EU&&(r=EU),r}function SU(e,t,n){const i=t.length,r=e.length/i;let o=!1;for(let s=0,a=0;s<i;s++){let i=0;for(let t=a+r;a<t;a++)e[a]>n&&i++;t[s]!==i&&(t[s]=i,o=!0)}return o}window.cache=fU;let TU=0,RU=class{constructor(e){aL(this,"id",void 0),aL(this,"immediates",[]),aL(this,"lastNonSilence",-1),aL(this,"immediateSpeechActivityScore",EU),aL(this,"lastLevelChangedTime",Date.now()),aL(this,"levels",[]),aL(this,"longs",[]),aL(this,"longSpeechActivityScore",EU),aL(this,"mediums",[]),aL(this,"mediumSpeechActivityScore",EU),aL(this,"minLevel",0),aL(this,"nextMinLevel",0),aL(this,"nextMinLevelWindowLength",0),aL(this,"energyScore",0),this.id=e||"".concat(TU++),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,n=this.minLevel+mU;let i=!1;for(let r=0;r<e.length;++r){let o=t[r];o<n&&(o=0);const s=Math.floor(o/mU);e[r]!==s&&(e[r]=s,i=!0)}return i}computeLongs(){return SU(this.mediums,this.longs,4)}computeMediums(){return SU(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=gU(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=gU(this.longs[0],10,47),this.longSpeechActivityScore>EU&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=gU(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 n=e;return e<0&&(n=0),e>_U&&(n=_U),this.levels.unshift(n),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(n),n>=this.minLevel+mU?n:n/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>_U&&(e=_U),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}},vU=class{constructor(e,t,n){aL(this,"isDominant",void 0),aL(this,"energyRanking",void 0),aL(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=n}},yU=class extends uO{constructor(e){super(),aL(this,"dominantId",null),aL(this,"lastDecisionTime",0),aL(this,"lastLevelChangedTime",0),aL(this,"lastLevelIdleTime",0),aL(this,"relativeSpeechActivities",[]),aL(this,"speakers",new Map),aL(this,"enableSilence",!1),aL(this,"timeoutToSilenceInterval",0),aL(this,"decisionMaker",null),aL(this,"loudest",[]),aL(this,"numLoudestToTrack",3),aL(this,"energyExpireTimeMs",250),aL(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,n=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=n&&(this.energyAlphaPct=n),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 n=Date.now(),i=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<n&&(this.lastLevelChangedTime=n,this.maybeStartDecisionMaker());const r=i.levelChanged(t,n);return this.updateLoudestList(i,r,n)}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 RU(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,n){const i=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new vU(i,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new vU(i,0,e.energyScore);const r=n-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 vU(i,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new class{constructor(e){aL(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)}}(this),this.decisionMaker.execute())}makeDecision(e){let t=null,n=null;const i=this.speakers.size;let r=null;if(0===i)r=null;else if(1===i){var o;const t=Qh(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 n=this.relativeSpeechActivities;let i=2;for(const o of this.speakers.entries()){const[s,a]=o;if(a===t)continue;a.evaluateSpeechActivityScores(e);for(let e=0;e<n.length;++e){const i=null==t?EU:t.getSpeechActivityScore(e);n[e]=Math.log(a.getSpeechActivityScore(e)/i)}const c=n[0],d=n[1],l=n[2];c>3&&d>2&&l>0&&d>i&&(i=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,n=this.dominantId),null==n&&!this.enableSilence||n===t||this.emit("ActiveSpeakerChanged",n)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let n=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):n=t;let i=300-(e-this.lastDecisionTime);return i<=0&&(this.lastDecisionTime=e,this.makeDecision(e),i=300-(Date.now()-e)),i>0&&n>i&&(n=i),n}timeoutIdleLevels(e){const t=[];for(const i of Qh(n=this.speakers).call(n)){var n;const r=e-i.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}};const CU=new Map;let bU=null,IU=null;const AU=3;let wU=[];const OU=new Map,NU=new Map;let DU,PU=class{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){aL(this,"id",void 0),aL(this,"track",void 0),aL(this,"score",0),aL(this,"active",!0),aL(this,"muted",!1),aL(this,"timer",0),aL(this,"actives",0),aL(this,"inactives",0),this.id=e,this.track=t,this.setActive(OU.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:n}=function(){const e=[],t=[];return Array.from(Qh(OU).call(OU)).forEach((n=>{n.active?e.push(n):t.push(n)})),{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&&n.length>0){let t;n.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(Qh(OU).call(OU)).forEach((n=>{!n.active||n.id===e||n.samples<40||(!t||n.score<t.score)&&(t=n)})),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(Qh(OU).call(OU)).forEach((n=>{n.active||n.id===e||n.samples<40||(!t||n.score>t.score)&&(t=n)})),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)}};function LU(e){const t=OU.get(e);t&&(OU.delete(e),t.clearTimer())}const kU=new Map,MU=new Map;const UU="video/h264",VU="video/h265";function xU(e,t,n){let i=new Uint8Array(e,t,n),r=[],o=0;for(;r.length<n;)o+3<n&&0===i[o]&&0===i[o+1]&&3===i[o+2]&&(0===i[o+3]||1===i[o+3]||2===i[o+3]||3===i[o+3])?(r.push(i[o],i[o+1],i[o+3]),o+=4):(r.push(i[o]),o++);return new Uint8Array(r)}function FU(e){const t=e.length;let n=[],i=0;for(;i<t;)i+2<t&&0===e[i]&&0===e[i+1]&&(0===e[i+2]||1===e[i+2]||2===e[i+2]||3===e[i+2])?(n.push(e[i],e[i+1],3,e[i+2]),i+=3):(n.push(e[i]),i++);return new Uint8Array(n)}function BU(e){if(e.length<5)return"";let t=-1;for(let n=0;n<e.length-3;n++){if(0===e[n]&&0===e[n+1]&&1===e[n+2]){t=n;break}if(n<e.length-4&&0===e[n]&&0===e[n+1]&&0===e[n+2]&&1===e[n+3]){t=n;break}}if(-1===t)return"";const n=t+(0===e[t+2]?4:3);if(n>=e.length)return"";const i=e[n];return 128&i?"":(i>>1&63)>=32||n+1<e.length&&0==(248&e[n+1])?VU:(31&i)<=31?UU:""}const GU=new Map;const jU=new Map;!function(){const e=lw();lP.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),lP.getStreamFromExtension=e.name===sw.CHROME&&Number(e.version)>34,lP.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}(),lP.supportMinBitrate=e.name===sw.CHROME||e.name===sw.EDGE,lP.supportSetRtpSenderParameters=function(){const e=lw();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!Bw()||!(!mw()&&!_w())||e.name===sw.FIREFOX&&Number(e.version)>=64)}(),e.name===sw.SAFARI&&(Number(e.version)>=14?lP.supportDualStream=!0:lP.supportDualStream=!1),lP.webAudioMediaStreamDest=function(){const e=lw();return!(e.name===sw.SAFARI&&Number(e.version)<12)}(),lP.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,lP.supportWebGL="undefined"!=typeof WebGLRenderingContext,lP.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,Bw()||(lP.webAudioWithAEC=!0),lP.supportShareAudio=function(){const e=lw();return(e.os===ow.WIN_10||e.os===ow.WIN_81||e.os===ow.WIN_7||e.os===ow.LINUX||e.os===ow.MAC_OS||e.os===ow.CHROMIUM_OS)&&e.name===sw.CHROME&&Number(e.version)>=74}(),lP.supportDataChannel=!!(vw(76)||Iw(68)||Aw(14)),lP.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!Tw()&&!!e&&e.prototype.setConfiguration instanceof Function}(),lP.supportWebRTCEncodedTransform=vw(87)||fw()||Iw(117),lP.supportWebRTCInsertableStream=function(){const e=lw();return(e.name===sw.CHROME||e.name===sw.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),lP.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,lP.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,lP.supportSuppressLocalAudioPlayback=TP(),lP.supportRestrictOwnAudio=RP(),BO((()=>{lP.supportDualStreamEncoding=function(){const e=lw();return!!iD("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&iD("CHROME_DUAL_STREAM_USE_ENCODING")))}(),UD.debug("browser ua: ",navigator.userAgent),UD.info("browser info: ",e),UD.info("browser compatibility: ",lP)}))}();const WU=["CHINA","GLOBAL"];const KU=[[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]],YU=[],HU=[];function XU(e,t){return!!t&&YU.some((n=>n.uid===e&&n.channelName===t))}function JU(){return HU.length>0}var zU=zv.forEach,ZU=Bi("forEach")?[].forEach:function(e){return zU(this,e,arguments.length>1?arguments[1]:void 0)};On({target:"Array",proto:!0,forced:[].forEach!=ZU},{forEach:ZU});var qU=qn("Array").forEach,QU=pi,$U=Qe,eV=l,tV=qU,nV=Array.prototype,iV={DOMTokenList:!0,NodeList:!0},rV=function(e){var t=e.forEach;return e===nV||eV(nV,e)&&t===nV.forEach||$U(iV,QU(e))?tV:t},oV=n(rV),sV=ze,aV=to;On({target:"Object",stat:!0,forced:i((function(){aV(1)}))},{keys:function(e){return aV(sV(e))}});var cV=n(ne.Object.keys),dV=n(Ji),lV=n(ar),uV=On,hV=qi,pV=jc,_V=te,EV=xn,mV=Wn,fV=Q,gV=rp,SV=ht,TV=qc,RV=dv("slice"),vV=SV("species"),yV=Array,CV=Math.max;uV({target:"Array",proto:!0,forced:!RV},{slice:function(e,t){var n,i,r,o=fV(this),s=mV(o),a=EV(e,s),c=EV(void 0===t?s:t,s);if(hV(o)&&(n=o.constructor,(pV(n)&&(n===yV||hV(n.prototype))||_V(n)&&null===(n=n[vV]))&&(n=void 0),n===yV||void 0===n))return TV(o,a,c);for(i=new(void 0===n?yV:n)(CV(c-a,0)),r=0;a<c;a++,r++)a in o&&gV(i,r,o[a]);return i.length=r,i}});var bV=qn("Array").slice,IV=l,AV=bV,wV=Array.prototype,OV=function(e){var t=e.slice;return e===wV||IV(wV,e)&&t===wV.slice?AV:t},NV=n(OV);function DV(e,t,n,i,r){var o,s,a,c={};return oV(o=cV(i)).call(o,(function(e){c[e]=i[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=dV(s=lV(a=NV(n).call(n)).call(a)).call(s,(function(n,i){return i(e,t,n)||n}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer&&(qR(e,t,c),c=null),c}let PV=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}({}),LV=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}({}),kV=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}({}),MV=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=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_LICENSE_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}({}),VV=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),xV=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_JOIN_INFO_WITH_PRE_JOIN_RESPONSE="request_pre_join_response",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}({}),FV=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}({}),BV=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}({}),GV=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.ON_USER_LIST="on_user_list",e}({}),jV=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),WV=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 KV(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw UD.error("Invalid Channel Name ".concat(e)),new dP(Xw.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,")}function YV(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||nO(e,1,255)))throw new dP(Xw.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&&UD.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 HV=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const XV={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},JV={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function zV(e,t){$w(e.url,"".concat(t,".url"),1,1e3,!1),tO(e.x)||qw(e.x,"".concat(t,".x"),0,1e4),tO(e.y)||qw(e.y,"".concat(t,".y"),0,1e4),tO(e.width)||qw(e.width,"".concat(t,".width"),0,1e4),tO(e.height)||qw(e.height,"".concat(t,".height"),0,1e4),tO(e.zOrder)||qw(e.zOrder,"".concat(t,".zOrder"),0,255),tO(e.alpha)||qw(e.alpha,"".concat(t,".alpha"),0,1,!1)}const ZV={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 qV=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}({}),QV=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),$V=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 ex(e){if(!e.channelName)throw new dP(Xw.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new dP(Xw.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&$w(e.token,"info.token",1,2047),YV(e.uid),KV(e.channelName),!0}let tx=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}({}),nx=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}({}),ix=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}({}),rx=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}({}),ox=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),sx=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}({}),ax=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}({}),cx=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LowVideo=2]="LowVideo",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}({}),dx=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 lx=[dx.AFRICA,dx.ASIA,dx.CHINA,dx.EUROPE,dx.GLOBAL,dx.INDIA,dx.JAPAN,dx.NORTH_AMERICA,dx.OCEANIA,dx.OVERSEA,dx.SOUTH_AMERICA];let ux=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 hx={CHINA:{},ASIA:{CODE:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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:ux.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&&(hx.CHINA={CODE:ux.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 px=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 _x(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class Ex extends uO{constructor(e,t){super(),Db(this,"onICEConnectionStateChange",void 0),Db(this,"onConnectionStateChange",void 0),Db(this,"onDTLSTransportStateChange",void 0),Db(this,"onDTLSTransportError",void 0),Db(this,"onICETransportStateChange",void 0),Db(this,"onFirstAudioReceived",void 0),Db(this,"onFirstVideoReceived",void 0),Db(this,"onFirstAudioDecoded",void 0),Db(this,"onFirstVideoDecoded",void 0),Db(this,"onFirstVideoRender",void 0),Db(this,"onFirstVideoBufferReady",void 0),Db(this,"onFirstVideoDecodedTimeout",void 0),Db(this,"onSelectedLocalCandidateChanged",void 0),Db(this,"onSelectedRemoteCandidateChanged",void 0),Db(this,"onICECandidateError",void 0),Db(this,"getLocalVideoStats",void 0)}}class mx extends Ex{constructor(e,t){super(e,t),Db(this,"establishPromise",void 0)}}let fx=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),gx=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),Sx=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 Tx=["disconnected","failed"];let Rx=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),vx=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),yx=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}({}),Cx=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),bx=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}({}),Ix=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.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}({}),wx=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}({}),Ox=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}({}),Nx=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),Dx=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}({}),Px=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}({}),Lx=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}({}),kx=function(e){return e.ABORT="abort",e}({}),Mx=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 Vx={[PV.ACCESS_POINT]:{[MV.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[MV.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[MV.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[MV.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[MV.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[MV.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[MV.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[PV.UNILBS]:{[kV.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[kV.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[kV.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[kV.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[kV.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[kV.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[kV.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[kV.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[kV.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[kV.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[kV.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[kV.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[kV.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[PV.STRING_UID_ALLOCATOR]:{[LV.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[LV.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[LV.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function xx(e){const t=Vx[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const n=t[e%1e4];if(!n){if(Math.floor(e/1e4)===PV.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 n}const Fx={[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 Bx(e){const t=Fx[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function Gx(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function jx(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Gx(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Gx(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Wx(e,t){if("string"==typeof e)return e;const{proxy:n,host:i,port:r}=e;if(t){const e=iD("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(i,"/ws/?p=").concat(Number(r)+150):"wss://".concat(i,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return n?"wss://".concat(n,"/ws/?h=").concat(i,"&p=").concat(r):"wss://".concat(i,":").concat(r)}const Kx=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Yx=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,Hx=/wss:\/\/(.+):([0-9]+)\/?/,Xx=/wss:\/\/(.[^\/]+)\/?/;let Jx=0;class zx{constructor(e,t){Db(this,"id",0),Db(this,"store",void 0),Db(this,"recordIndex",void 0),Db(this,"websockets",[]),Db(this,"try443PortDuration",2e3),Db(this,"forceCloseWSDuration",5e3),Db(this,"try443PortTimeout",null),Db(this,"forceCloseTimeout",null),Db(this,"isTry443PortFailed",!1),Db(this,"isNormalPortFailed",!1),Db(this,"useDoubleDomain",!1),Db(this,"useProxy",!1),Db(this,"startTime",Date.now()),this.id=++Jx,this.try443PortDuration=iD("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 n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];UD.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...i)}createWebSocket(e,t,n){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:n});const i=iD("GATEWAY_DOMAINS"),r=Date.now(),o=[],s=i.find((t=>{var n;return Di(n=e.host).call(n,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)i.forEach((n=>{a.push(Wx(jx(jx({},e),{},{host:e.host.replace(s,n)}),t))}));else{const n=jx({},e);if(t&&s){const e=i.find((e=>e!==s));e&&(n.host=n.host.replace(s,e))}a.push(Wx(n,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(i){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,n);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,n);throw new dP(Xw.WS_ERR,"init websocket failed! Error: ".concat(i.toString()))}const c=tw();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=n=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState));const i=o.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(i)),i&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(n.reason)),c.reject({code:n.code,reason:ax.A_ROUND_WS_FAILED})):!t&&i&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=i:this.isNormalPortFailed=i},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();lw().os===ow.MAC_OS&&Tw()&&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 n||(()=>{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,n,i){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,n,i;return[,t,n,i]=e.match(Kx)||[],t||([,n,i]=e.match(Yx)||[]),n&&i||([,n,i]=e.match(Hx)||[]),n&&i||([,n]=e.match(Xx)||[]),n||UD.warning("un-destructible url: ",e),{proxy:t,host:n,port:i||"443"}}(e)),this.recordIndex=i,this.useProxy=!!e.proxy,n&&this.useProxy&&(UD.warn("cannot use 443 only when use proxy"),n=!1),this.createWebSocket(e,!!n,!1).finally((()=>this.clearTimeout()))}}function Zx(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class qx extends uO{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Di(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(WV.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(WV.CONNECTED):"closed"===this._state?this.emit(WV.CLOSED):"failed"===this._state&&this.emit(WV.FAILED))}resetReconnectCount(e){UD.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=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(),Db(this,"_websocketUrl",null),Db(this,"connectionID",0),Db(this,"currentURLIndex",0),Db(this,"urls",[]),Db(this,"_reconnectMode","tryNext"),Db(this,"reconnectReason",void 0),Db(this,"_initMutex",void 0),Db(this,"name",void 0),Db(this,"_state","closed"),Db(this,"reconnectInterrupter",void 0),Db(this,"websocket",void 0),Db(this,"retryConfig",void 0),Db(this,"reconnectCount",0),Db(this,"forceCloseTimeout",5e3),Db(this,"onlineReconnectListener",void 0),Db(this,"useCompress",void 0),Db(this,"tryDoubleDomain",!1),Db(this,"use443PortOnly",!1),Db(this,"wsInflateLength",0),Db(this,"wsDeflateLength",0),Db(this,"closeEstablishingWs",(()=>{})),Db(this,"store",void 0),Db(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Zx(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Zx(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this.useCompress=n,this.tryDoubleDomain=i,this.use443PortOnly=r,this._initMutex=new pN("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);IO.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),PO.on(AO.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===IO.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 n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{var i;const e=tw(),t=this.urls[this.currentURLIndex];null===(i=this.store)||void 0===i||i.beforeConnect(),(function(e){return!(pP()||iD("USE_NEW_TOKEN")||!iD("ENABLE_PREALLOC_PC")&&(null==e||!e.autoSubscribe||iD("FORCE_DISABLE_AUTO_SUB")))}(this.store)||iD("ENABLE_JOIN_V4"))&&this.emit(wx.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(WV.CLOSED,(()=>{e.reject(new Jw(Xw.WS_DISCONNECT))})),this.once(WV.CONNECTED,e.resolve),await e.promise}catch(e){}finally{n()}}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 UD.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),UD.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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.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(Xw.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new Jw(Xw.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 n=tw();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const i=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),UD.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},r=async e=>{var t;if(UD.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)n.reject(new Jw(Xw.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=NO(this,WV.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,i=await this.reconnectWithAction(t);if("closed"===this.state)return void UD.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!i)return n.reject(new Jw(Xw.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},o=e=>{this.emit(WV.ON_MESSAGE,e)},s=e=>{UD.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),iD("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=iD("GATEWAY_WSS_ADDRESS")),UD.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=Wx(e);const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,i&&i(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,i=e instanceof Jw,o=i&&e.code===Xw.WS_ABORT,s=i&&e.code===Xw.WS_ERR,c=i?e.message:e&&(e.reason||e.toString());UD.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?(n.reject(t?new Jw(Xw.WS_DISCONNECT,"websocket is closed: ".concat(c)):new Jw(Xw.WS_ERR,"init websocket failed: ".concat(c))),s&&UD.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return n.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;UD.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||PO.isOnline||!PO.onlineWaiter||(this.onlineReconnectListener=PO.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=mN(this.reconnectCount,this.retryConfig);UD.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Wh.race([QO(t),this.onlineReconnectListener||new Wh((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const i=async(e,t)=>{this.emit(WV.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await i(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);UD.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await i(this.urls[this.currentURLIndex],e)}else"recover"===e&&(UD.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await wO(this,WV.REQUEST_NEW_URLS),this.currentURLIndex=0,await i(this.urls[this.currentURLIndex],e))}catch(n){var r;UD.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const i=null==n||null===(r=n.data)||void 0===r?void 0:r.desc;if(Array.isArray(i)){if(Di(i).call(i,"dynamic key expired"))return this.emit(WV.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(Di(i).call(i,"request downgrade fallback"))return this.emit(WV.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class Qx extends qx{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 n=tw(),i=function(e,t){return new zx(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{UD.debug("[choose-best-ws] close establishing websockets"),i.closeAllWebsockets(),n.reject(new Jw(Xw.WS_ABORT,"choose best websocket aborted"))};const r=iD("GATEWAY_DOMAINS");return UD.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),i.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(n.resolve).catch(n.reject),n.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class $x extends qx{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(((n,i)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{UD.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),i(new Jw(Xw.WS_ABORT,"choose best websocket aborted"))};const s=iD("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=s.find((t=>-1!==c?Di(e).call(e,t,c):Di(e).call(e,t)));UD.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 n=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),i=new WebSocket(n);i.binaryType="arraybuffer",o.push(i),UD.debug("[choose-best-ws] ws is connecting:",i.url)}))}catch(e){for(UD.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;UD.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{UD.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,n(e)},e.onclose=e=>{if(a=e,r)return;o.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(UD.debug("[choose-best-ws] all websocket is closed"),r=!0,i(a))},e.onmessage=t=>{UD.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),QO(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;UD.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(Xw.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return UD.error("[".concat(this.name,"]").concat(t)),void i(t)}r.onopen=()=>{n(r)},r.onclose=e=>{i(e)},r.onmessage=e=>{UD.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},QO(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 eF extends uO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===VV.CONNECTED?this.emit(xV.WS_CONNECTED):e===VV.RECONNECTING?this.emit(xV.WS_RECONNECTING,this._websocketReconnectReason):e===VV.CLOSED&&this.emit(xV.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(),Db(this,"__name__","AgoraRTCSignal"),Db(this,"_disconnectedReason",void 0),Db(this,"_websocketReconnectReason",void 0),Db(this,"_connectionState",VV.CLOSED),Db(this,"reconnectToken",void 0),Db(this,"websocket",void 0),Db(this,"openConnectionTime",void 0),Db(this,"clientId",void 0),Db(this,"lastMsgTime",Date.now()),Db(this,"uploadCache",[]),Db(this,"uploadCacheInterval",void 0),Db(this,"rttRolling",new SN(5)),Db(this,"pingpongTimer",void 0),Db(this,"wsInflateDataTimer",void 0),Db(this,"pingpongTimeoutCount",0),Db(this,"ortc",void 0),Db(this,"joinResponse",void 0),Db(this,"multiIpOption",void 0),Db(this,"initError",void 0),Db(this,"spec",void 0),Db(this,"store",void 0),Db(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(xV.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===GV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===GV.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(gO.UID_BANNED);break;case 15:this.close(gO.IP_BANNED);break;case 16:this.close(gO.CHANNEL_BANNED)}if(t._type===GV.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case UV.ERR_LICENSE_MISSING:this.close(gO.LICENSE_MISSING);break;case UV.ERR_LICENSE_EXPIRED:this.close(gO.LICENSE_EXPIRED);break;case UV.ERR_LICENSE_MINUTES_EXCEEDED:this.close(gO.LICENSE_MINUTES_EXCEEDED);break;case UV.ERR_LICENSE_PERIOD_INVALID:this.close(gO.LICENSE_PERIOD_INVALID);break;case UV.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(gO.LICENSE_MULTIPLE_SDK_SERVICE);break;case UV.ERR_LICENSE_ILLEGAL:this.close(gO.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Qx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,iD("JOIN_GATEWAY_USE_DUAL_DOMAIN"),iD("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===VV.CONNECTED&&this.reconnect("retry",bO.OFFLINE)}))}async request(e,t,n,i){const r=$O(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((t,n)=>{if(this.connectionState===VV.CONNECTED)return t();const i=()=>{this.off(xV.WS_CLOSED,r),t()},r=()=>{this.off(xV.WS_CONNECTED,i),n(new dP(Xw.WS_ABORT))};this.once(xV.WS_CONNECTED,i),this.once(xV.WS_CLOSED,r),e!==FV.PUBLISH&&e!==FV.PUBLISH_DATASTREAM&&e!==FV.SUBSCRIBE&&e!==FV.SUBSCRIBE_DATASTREAM&&e!==FV.UNSUBSCRIBE&&e!==FV.UNSUBSCRIBE_DATASTREAM&&e!==FV.UNPUBLISH&&e!==FV.UNPUBLISH_DATASTREAM&&e!==FV.CONTROL&&e!==FV.RESTART_ICE||this.once(xV.DISCONNECT_P2P,(()=>{n(new dP(Xw.DISCONNECT_P2P))})),e!==FV.PUBLISH&&e!==FV.RESTART_ICE||this.once(xV.ABORT_P2P_EXECUTION,(()=>{n(new dP(Xw.DISCONNECT_P2P))}))}));if(this.connectionState!==VV.CONNECTING&&this.connectionState!==VV.RECONNECTING||e===FV.JOIN||e===FV.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new Wh(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.emit(xV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new dP(Xw.WS_ABORT,"type: ".concat(e))),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(xV.WS_CLOSED,c),this.once(xV.WS_RECONNECTING,c),QO(iD("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(UD.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(xV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===VV.CLOSED||e===FV.LEAVE)throw new dP(Xw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===FV.JOIN||e===FV.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=Bx(l),h=new dP(Xw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(UD.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===FV.JOIN||e===FV.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,UD.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",bO.MULTI_IP)):this.reconnect(u.action,bO.SERVER_ERROR),e===FV.JOIN||e===FV.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void UD.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(BV.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=iD("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==VV.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)}),iD("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}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,n)=>{this.once(xV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(xV.WS_CLOSED,(e=>n(this.initError||new dP(Xw.WS_ABORT,e)))),this.connectionState=VV.CONNECTING,this.websocket.init(e).catch(n),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||gO.LEAVE,this.connectionState=VV.CLOSED,UD.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(xV.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await wO(this,xV.REQUEST_JOIN_INFO);this.store.joinReq();let t=await wO(this,xV.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(t){UD.debug("join response from pre join response");const n=await this.request(FV.JOIN,e);n&&"ortc"in n&&(t=n)}else UD.debug("join response from request join_v3"),t=await this.request(FV.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(xV.REPORT_JOIN_GATEWAY,ax.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(xV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=VV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new dP(Xw.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=DO(this,xV.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(FV.REJOIN,e);return!!t&&(this.connectionState=VV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(GV.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(GV.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(GV.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(GV.MUTE_AUDIO,{uid:e.uid}):this.emit(GV.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(GV.MUTE_VIDEO,{uid:e.uid}):this.emit(GV.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(GV.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(GV.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(GV.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(GV.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(GV.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(FV.DOWNGRADE_CODEC,t)}handleNotification(e){UD.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Bx(e.code);if(28===e.code&&"detail"in e&&(UD.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(xV.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===UV.ERR_REPEAT_JOIN_CHANNEL&&iD("IGNORE_UID_CHECK")?void this.close(gO.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(gO.UID_BANNED),void this.close()):e.code===UV.K_VOS_FALLBACK&&"detail"in e?(UD.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&iD("ENABLE_QUALITY_FALLBACK")?void wO(this,xV.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{UD.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&iD("ENABLE_FALLBACK_TO_HLS")?(this.emit(xV.VOS_FALLBACK,e.detail),void this.close(gO.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,bO.SERVER_ERROR);UD.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=iD("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(UD.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>iD("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",bO.TIMEOUT):this.request(FV.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),iD("REPORT_STATS")&&this.send(FV.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(BV.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(WV.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(xV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(WV.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(WV.CLOSED,(()=>{this.connectionState=VV.CLOSED})),this.websocket.on(WV.FAILED,(()=>{this._disconnectedReason=gO.NETWORK_ERROR,this.connectionState=VV.CLOSED})),this.websocket.on(WV.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===VV.CONNECTED?this.connectionState=VV.RECONNECTING:this.connectionState=VV.CONNECTING})),this.websocket.on(WV.WILL_RECONNECT,((e,t,n)=>{const i=DO(this,xV.IS_P2P_DISCONNECTED),r=i||"retry"!==e;i&&"retry"===e&&(UD.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=ax.P2P_DISCONNECTED),r&&(UD.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(xV.REPORT_JOIN_GATEWAY,t||ax.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(xV.DISCONNECT_P2P)),n(e)})),this.websocket.on(WV.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{UD.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",bO.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(xV.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof dP){if(e.code===Xw.UNEXPECTED_RESPONSE&&e.data.code===UV.ERR_NO_AUTHORIZED)return this.initError=new dP(Xw.TOKEN_EXPIRE,"dynamic key expired"),void this.close(gO.TOKEN_EXPIRE);UD.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",bO.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(WV.REQUEST_NEW_URLS,((e,t)=>{wO(this,xV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(WV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(GV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(wx.PRE_CONNECT_PC,(()=>{this.emit(xV.PRE_CONNECT_PC)})),this.websocket.on(WV.ON_FALLBACK,(()=>{iD("ENABLE_FALLBACK_TO_HLS")&&this.emit(xV.VOS_FALLBACK,"fallback_hls")}))}}var tF=l,nF=OS,iF=RegExp.prototype,rF=function(e){return e===iF||tF(iF,e)?nF(e):e.flags},oF=n(rF);function sF(e){let t=e.length;for(;--t>=0;)e[t]=0}const aF=256,cF=286,dF=30,lF=15,uF=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]),hF=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]),pF=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),_F=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),EF=new Array(576);sF(EF);const mF=new Array(60);sF(mF);const fF=new Array(512);sF(fF);const gF=new Array(256);sF(gF);const SF=new Array(29);sF(SF);const TF=new Array(dF);function RF(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let vF,yF,CF;function bF(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}sF(TF);const IF=e=>e<256?fF[e]:fF[256+(e>>>7)],AF=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},wF=(e,t,n)=>{e.bi_valid>16-n?(e.bi_buf|=t<<e.bi_valid&65535,AF(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=n-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},OF=(e,t,n)=>{wF(e,n[2*t],n[2*t+1])},NF=(e,t)=>{let n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1},DF=(e,t,n)=>{const i=new Array(16);let r,o,s=0;for(r=1;r<=lF;r++)s=s+n[r-1]<<1,i[r]=s;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=NF(i[t]++,t))}},PF=e=>{let t;for(t=0;t<cF;t++)e.dyn_ltree[2*t]=0;for(t=0;t<dF;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},LF=e=>{e.bi_valid>8?AF(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},kF=(e,t,n,i)=>{const r=2*t,o=2*n;return e[r]<e[o]||e[r]===e[o]&&i[t]<=i[n]},MF=(e,t,n)=>{const i=e.heap[n];let r=n<<1;for(;r<=e.heap_len&&(r<e.heap_len&&kF(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!kF(t,i,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=i},UF=(e,t,n)=>{let i,r,o,s,a=0;if(0!==e.sym_next)do{i=255&e.pending_buf[e.sym_buf+a++],i+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===i?OF(e,r,t):(o=gF[r],OF(e,o+aF+1,t),s=uF[o],0!==s&&(r-=SF[o],wF(e,r,s)),i--,o=IF(i),OF(e,o,n),s=hF[o],0!==s&&(i-=TF[o],wF(e,i,s)))}while(a<e.sym_next);OF(e,256,t)},VF=(e,t)=>{const n=t.dyn_tree,i=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!==n[2*s]?(e.heap[++e.heap_len]=d=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,n[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=i[2*c+1]);for(t.max_code=d,s=e.heap_len>>1;s>=1;s--)MF(e,n,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],MF(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,n[2*c]=n[2*s]+n[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,n[2*s+1]=n[2*a+1]=c,e.heap[1]=c++,MF(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const n=t.dyn_tree,i=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<=lF;h++)e.bl_count[h]=0;for(n[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=n[2*n[2*l+1]+1]+1,h>c&&(h=c,E++),n[2*l+1]=h,l>i||(e.bl_count[h]++,p=0,l>=a&&(p=s[l-a]),_=n[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>i||(n[2*u+1]!==h&&(e.opt_len+=(h-n[2*u+1])*n[2*u],n[2*u+1]=h),l--)}})(e,t),DF(n,d,e.bl_count)},xF=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=s,s=t[2*(i+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))},FF=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),i=0;i<=n;i++)if(r=s,s=t[2*(i+1)+1],!(++a<c&&r===s)){if(a<d)do{OF(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==o&&(OF(e,r,e.bl_tree),a--),OF(e,16,e.bl_tree),wF(e,a-3,2)):a<=10?(OF(e,17,e.bl_tree),wF(e,a-3,3)):(OF(e,18,e.bl_tree),wF(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 BF=!1;const GF=(e,t,n,i)=>{wF(e,0+(i?1:0),3),LF(e),AF(e,n),AF(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n};var jF=e=>{BF||((()=>{let e,t,n,i,r;const o=new Array(16);for(n=0,i=0;i<28;i++)for(SF[i]=n,e=0;e<1<<uF[i];e++)gF[n++]=i;for(gF[n-1]=i,r=0,i=0;i<16;i++)for(TF[i]=r,e=0;e<1<<hF[i];e++)fF[r++]=i;for(r>>=7;i<dF;i++)for(TF[i]=r<<7,e=0;e<1<<hF[i]-7;e++)fF[256+r++]=i;for(t=0;t<=lF;t++)o[t]=0;for(e=0;e<=143;)EF[2*e+1]=8,e++,o[8]++;for(;e<=255;)EF[2*e+1]=9,e++,o[9]++;for(;e<=279;)EF[2*e+1]=7,e++,o[7]++;for(;e<=287;)EF[2*e+1]=8,e++,o[8]++;for(DF(EF,287,o),e=0;e<dF;e++)mF[2*e+1]=5,mF[2*e]=NF(e,5);vF=new RF(EF,uF,257,cF,lF),yF=new RF(mF,hF,0,dF,lF),CF=new RF(new Array(0),pF,0,19,7)})(),BF=!0),e.l_desc=new bF(e.dyn_ltree,vF),e.d_desc=new bF(e.dyn_dtree,yF),e.bl_desc=new bF(e.bl_tree,CF),e.bi_buf=0,e.bi_valid=0,PF(e)},WF=(e,t,n,i)=>{let r,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,n=4093624447;for(t=0;t<=31;t++,n>>>=1)if(1&n&&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<aF;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),VF(e,e.l_desc),VF(e,e.d_desc),s=(e=>{let t;for(xF(e,e.dyn_ltree,e.l_desc.max_code),xF(e,e.dyn_dtree,e.d_desc.max_code),VF(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*_F[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=n+5,n+4<=r&&-1!==t?GF(e,t,n,i):4===e.strategy||o===r?(wF(e,2+(i?1:0),3),UF(e,EF,mF)):(wF(e,4+(i?1:0),3),((e,t,n,i)=>{let r;for(wF(e,t-257,5),wF(e,n-1,5),wF(e,i-4,4),r=0;r<i;r++)wF(e,e.bl_tree[2*_F[r]+1],3);FF(e,e.dyn_ltree,t-1),FF(e,e.dyn_dtree,n-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),UF(e,e.dyn_ltree,e.dyn_dtree)),PF(e),i&&LF(e)},KF=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(gF[n]+aF+1)]++,e.dyn_dtree[2*IF(t)]++),e.sym_next===e.sym_end),YF=e=>{wF(e,2,3),OF(e,256,EF),(e=>{16===e.bi_valid?(AF(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)},HF={_tr_init:jF,_tr_stored_block:GF,_tr_flush_block:WF,_tr_tally:KF,_tr_align:YF};var XF=(e,t,n,i)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;0!==n;){s=n>2e3?2e3:n,n-=s;do{r=r+t[i++]|0,o=o+r|0}while(--s);r%=65521,o%=65521}return r|o<<16|0};const JF=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t})());var zF=(e,t,n,i)=>{const r=JF,o=i+n;e^=-1;for(let n=i;n<o;n++)e=e>>>8^r[255&(e^t[n])];return-1^e},ZF={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"},qF={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:QF,_tr_stored_block:$F,_tr_flush_block:eB,_tr_tally:tB,_tr_align:nB}=HF,{Z_NO_FLUSH:iB,Z_PARTIAL_FLUSH:rB,Z_FULL_FLUSH:oB,Z_FINISH:sB,Z_BLOCK:aB,Z_OK:cB,Z_STREAM_END:dB,Z_STREAM_ERROR:lB,Z_DATA_ERROR:uB,Z_BUF_ERROR:hB,Z_DEFAULT_COMPRESSION:pB,Z_FILTERED:_B,Z_HUFFMAN_ONLY:EB,Z_RLE:mB,Z_FIXED:fB,Z_DEFAULT_STRATEGY:gB,Z_UNKNOWN:SB,Z_DEFLATED:TB}=qF,RB=286,vB=30,yB=19,CB=2*RB+1,bB=15,IB=258,AB=262,wB=42,OB=113,NB=666,DB=(e,t)=>(e.msg=ZF[t],t),PB=e=>2*e-(e>4?9:0),LB=e=>{let t=e.length;for(;--t>=0;)e[t]=0},kB=e=>{let t,n,i,r=e.w_size;t=e.hash_size,i=t;do{n=e.head[--i],e.head[i]=n>=r?n-r:0}while(--t);t=r,i=t;do{n=e.prev[--i],e.prev[i]=n>=r?n-r:0}while(--t)};let MB=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask;const UB=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))},VB=(e,t)=>{eB(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,UB(e.strm)},xB=(e,t)=>{e.pending_buf[e.pending++]=t},FB=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},BB=(e,t,n,i)=>{let r=e.avail_in;return r>i&&(r=i),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),n),1===e.state.wrap?e.adler=XF(e.adler,t,r,n):2===e.state.wrap&&(e.adler=zF(e.adler,t,r,n)),e.next_in+=r,e.total_in+=r,r)},GB=(e,t)=>{let n,i,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-AB?e.strstart-(e.w_size-AB):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+IB;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(n=t,d[n+s]===_&&d[n+s-1]===p&&d[n]===d[o]&&d[++n]===d[o+1]){o+=2,n++;do{}while(d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&o<h);if(i=IB-(h-o),o=h-IB,i>s){if(e.match_start=t,s=i,i>=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},jB=e=>{const t=e.w_size;let n,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-AB)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),kB(e),i+=t),0===e.strm.avail_in)break;if(n=BB(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=n,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=MB(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=MB(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<AB&&0!==e.strm.avail_in)},WB=(e,t)=>{let n,i,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(n=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,i=e.strstart-e.block_start,n>i+e.strm.avail_in&&(n=i+e.strm.avail_in),n>r&&(n=r),n<o&&(0===n&&t!==sB||t===iB||n!==i+e.strm.avail_in))break;s=t===sB&&n===i+e.strm.avail_in?1:0,$F(e,0,0,s),e.pending_buf[e.pending-4]=n,e.pending_buf[e.pending-3]=n>>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,UB(e.strm),i&&(i>n&&(i=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,n-=i),n&&(BB(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}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!==iB&&t!==sB&&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&&(BB(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,i=e.strstart-e.block_start,(i>=o||(i||t===sB)&&t!==iB&&0===e.strm.avail_in&&i<=r)&&(n=i>r?r:i,s=t===sB&&0===e.strm.avail_in&&n===i?1:0,$F(e,e.block_start,n,s),e.block_start+=n,UB(e.strm)),s?3:1)},KB=(e,t)=>{let n,i;for(;;){if(e.lookahead<AB){if(jB(e),e.lookahead<AB&&t===iB)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=MB(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==n&&e.strstart-n<=e.w_size-AB&&(e.match_length=GB(e,n)),e.match_length>=3)if(i=tB(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=MB(e,e.ins_h,e.window[e.strstart+3-1]),n=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=MB(e,e.ins_h,e.window[e.strstart+1]);else i=tB(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(VB(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===sB?(VB(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(VB(e,!1),0===e.strm.avail_out)?1:2},YB=(e,t)=>{let n,i,r;for(;;){if(e.lookahead<AB){if(jB(e),e.lookahead<AB&&t===iB)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=MB(e,e.ins_h,e.window[e.strstart+3-1]),n=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!==n&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-AB&&(e.match_length=GB(e,n),e.match_length<=5&&(e.strategy===_B||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,i=tB(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=MB(e,e.ins_h,e.window[e.strstart+3-1]),n=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++,i&&(VB(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(i=tB(e,0,e.window[e.strstart-1]),i&&VB(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&&(i=tB(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===sB?(VB(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(VB(e,!1),0===e.strm.avail_out)?1:2};function HB(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}const XB=[new HB(0,0,0,0,WB),new HB(4,4,8,4,KB),new HB(4,5,16,8,KB),new HB(4,6,32,32,KB),new HB(4,4,16,16,YB),new HB(8,16,32,32,YB),new HB(8,16,128,128,YB),new HB(8,32,128,256,YB),new HB(32,128,258,1024,YB),new HB(32,258,258,4096,YB)];function JB(){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=TB,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*CB),this.dyn_dtree=new Uint16Array(2*(2*vB+1)),this.bl_tree=new Uint16Array(2*(2*yB+1)),LB(this.dyn_ltree),LB(this.dyn_dtree),LB(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(bB+1),this.heap=new Uint16Array(2*RB+1),LB(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*RB+1),LB(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 zB=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==wB&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==OB&&t.status!==NB?1:0},ZB=e=>{if(zB(e))return DB(e,lB);e.total_in=e.total_out=0,e.data_type=SB;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?wB:OB,e.adler=2===t.wrap?0:1,t.last_flush=-2,QF(t),cB},qB=e=>{const t=ZB(e);return t===cB&&(e=>{e.window_size=2*e.w_size,LB(e.head),e.max_lazy_match=XB[e.level].max_lazy,e.good_match=XB[e.level].good_length,e.nice_match=XB[e.level].nice_length,e.max_chain_length=XB[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},QB=(e,t,n,i,r,o)=>{if(!e)return lB;let s=1;if(t===pB&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),r<1||r>9||n!==TB||i<8||i>15||t<0||t>9||o<0||o>fB||8===i&&1!==s)return DB(e,lB);8===i&&(i=9);const a=new JB;return e.state=a,a.strm=e,a.status=wB,a.wrap=s,a.gzhead=null,a.w_bits=i,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=n,qB(e)};var $B=(e,t)=>{if(zB(e)||t>aB||t<0)return e?DB(e,lB):lB;const n=e.state;if(!e.output||0!==e.avail_in&&!e.input||n.status===NB&&t!==sB)return DB(e,0===e.avail_out?hB:lB);const i=n.last_flush;if(n.last_flush=t,0!==n.pending){if(UB(e),0===e.avail_out)return n.last_flush=-1,cB}else if(0===e.avail_in&&PB(t)<=PB(i)&&t!==sB)return DB(e,hB);if(n.status===NB&&0!==e.avail_in)return DB(e,hB);if(n.status===wB&&0===n.wrap&&(n.status=OB),n.status===wB){let t=TB+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=EB||n.level<2?0:n.level<6?1:6===n.level?2:3,t|=i<<6,0!==n.strstart&&(t|=32),t+=31-t%31,FB(n,t),0!==n.strstart&&(FB(n,e.adler>>>16),FB(n,65535&e.adler)),e.adler=1,n.status=OB,UB(e),0!==n.pending)return n.last_flush=-1,cB}if(57===n.status)if(e.adler=0,xB(n,31),xB(n,139),xB(n,8),n.gzhead)xB(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),xB(n,255&n.gzhead.time),xB(n,n.gzhead.time>>8&255),xB(n,n.gzhead.time>>16&255),xB(n,n.gzhead.time>>24&255),xB(n,9===n.level?2:n.strategy>=EB||n.level<2?4:0),xB(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(xB(n,255&n.gzhead.extra.length),xB(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=zF(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69;else if(xB(n,0),xB(n,0),xB(n,0),xB(n,0),xB(n,0),xB(n,9===n.level?2:n.strategy>=EB||n.level<2?4:0),xB(n,3),n.status=OB,UB(e),0!==n.pending)return n.last_flush=-1,cB;if(69===n.status){if(n.gzhead.extra){let t=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>t&&(e.adler=zF(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex+=r,UB(e),0!==n.pending)return n.last_flush=-1,cB;t=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>t&&(e.adler=zF(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=73}if(73===n.status){if(n.gzhead.name){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=zF(e.adler,n.pending_buf,n.pending-i,i)),UB(e),0!==n.pending)return n.last_flush=-1,cB;i=0}t=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,xB(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=zF(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=91}if(91===n.status){if(n.gzhead.comment){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=zF(e.adler,n.pending_buf,n.pending-i,i)),UB(e),0!==n.pending)return n.last_flush=-1,cB;i=0}t=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,xB(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=zF(e.adler,n.pending_buf,n.pending-i,i))}n.status=103}if(103===n.status){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(UB(e),0!==n.pending))return n.last_flush=-1,cB;xB(n,255&e.adler),xB(n,e.adler>>8&255),e.adler=0}if(n.status=OB,UB(e),0!==n.pending)return n.last_flush=-1,cB}if(0!==e.avail_in||0!==n.lookahead||t!==iB&&n.status!==NB){let i=0===n.level?WB(n,t):n.strategy===EB?((e,t)=>{let n;for(;;){if(0===e.lookahead&&(jB(e),0===e.lookahead)){if(t===iB)return 1;break}if(e.match_length=0,n=tB(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(VB(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===sB?(VB(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(VB(e,!1),0===e.strm.avail_out)?1:2})(n,t):n.strategy===mB?((e,t)=>{let n,i,r,o;const s=e.window;for(;;){if(e.lookahead<=IB){if(jB(e),e.lookahead<=IB&&t===iB)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,i=s[r],i===s[++r]&&i===s[++r]&&i===s[++r])){o=e.strstart+IB;do{}while(i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&r<o);e.match_length=IB-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(n=tB(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=tB(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(VB(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===sB?(VB(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(VB(e,!1),0===e.strm.avail_out)?1:2})(n,t):XB[n.level].func(n,t);if(3!==i&&4!==i||(n.status=NB),1===i||3===i)return 0===e.avail_out&&(n.last_flush=-1),cB;if(2===i&&(t===rB?nB(n):t!==aB&&($F(n,0,0,!1),t===oB&&(LB(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),UB(e),0===e.avail_out))return n.last_flush=-1,cB}return t!==sB?cB:n.wrap<=0?dB:(2===n.wrap?(xB(n,255&e.adler),xB(n,e.adler>>8&255),xB(n,e.adler>>16&255),xB(n,e.adler>>24&255),xB(n,255&e.total_in),xB(n,e.total_in>>8&255),xB(n,e.total_in>>16&255),xB(n,e.total_in>>24&255)):(FB(n,e.adler>>>16),FB(n,65535&e.adler)),UB(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?cB:dB)},eG=(e,t)=>{let n=t.length;if(zB(e))return lB;const i=e.state,r=i.wrap;if(2===r||1===r&&i.status!==wB||i.lookahead)return lB;if(1===r&&(e.adler=XF(e.adler,t,n,0)),i.wrap=0,n>=i.w_size){0===r&&(LB(i.head),i.strstart=0,i.block_start=0,i.insert=0);let e=new Uint8Array(i.w_size);e.set(t.subarray(n-i.w_size,n),0),t=e,n=i.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,jB(i);i.lookahead>=3;){let e=i.strstart,t=i.lookahead-2;do{i.ins_h=MB(i,i.ins_h,i.window[e+3-1]),i.prev[e&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=e,e++}while(--t);i.strstart=e,i.lookahead=2,jB(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,i.wrap=r,cB},tG={deflateInit:(e,t)=>QB(e,t,TB,15,8,gB),deflateInit2:QB,deflateReset:qB,deflateResetKeep:ZB,deflateSetHeader:(e,t)=>zB(e)||2!==e.state.wrap?lB:(e.state.gzhead=t,cB),deflate:$B,deflateEnd:e=>{if(zB(e))return lB;const t=e.state.status;return e.state=null,t===OB?DB(e,uB):cB},deflateSetDictionary:eG,deflateInfo:"pako deflate (from Nodeca project)"};const nG=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var iG={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const t in n)nG(n,t)&&(e[t]=n[t])}}return e},flattenChunks:e=>{let t=0;for(let n=0,i=e.length;n<i;n++)t+=e[n].length;const n=new Uint8Array(t);for(let t=0,i=0,r=e.length;t<r;t++){let r=e[t];n.set(r,i),i+=r.length}return n}};let rG=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){rG=!1}const oG=new Uint8Array(256);for(let e=0;e<256;e++)oG[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;oG[254]=oG[254]=1;var sG={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,n,i,r,o,s=e.length,a=0;for(r=0;r<s;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),a+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(a),o=0,r=0;o<a;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?t[o++]=n:n<2048?(t[o++]=192|n>>>6,t[o++]=128|63&n):n<65536?(t[o++]=224|n>>>12,t[o++]=128|n>>>6&63,t[o++]=128|63&n):(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63,t[o++]=128|n>>>6&63,t[o++]=128|63&n);return t},buf2string:(e,t)=>{const n=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let i,r;const o=new Array(2*n);for(r=0,i=0;i<n;){let t=e[i++];if(t<128){o[r++]=t;continue}let s=oG[t];if(s>4)o[r++]=65533,i+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&i<n;)t=t<<6|63&e[i++],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&&rG)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let i=0;i<t;i++)n+=String.fromCharCode(e[i]);return n})(o,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let n=t-1;for(;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+oG[e[n]]>t?n:t}};var aG=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 cG=Object.prototype.toString,{Z_NO_FLUSH:dG,Z_SYNC_FLUSH:lG,Z_FULL_FLUSH:uG,Z_FINISH:hG,Z_OK:pG,Z_STREAM_END:_G,Z_DEFAULT_COMPRESSION:EG,Z_DEFAULT_STRATEGY:mG,Z_DEFLATED:fG}=qF;function gG(e){this.options=iG.assign({level:EG,method:fG,chunkSize:16384,windowBits:15,memLevel:8,strategy:mG},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 aG,this.strm.avail_out=0;let n=tG.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==pG)throw new Error(ZF[n]);if(t.header&&tG.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?sG.string2buf(t.dictionary):"[object ArrayBuffer]"===cG.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,n=tG.deflateSetDictionary(this.strm,e),n!==pG)throw new Error(ZF[n]);this._dict_set=!0}}function SG(e,t){const n=new gG(t);if(n.push(e,!0),n.err)throw n.msg||ZF[n.err];return n.result}gG.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?hG:dG,"string"==typeof e?n.input=sG.string2buf(e):"[object ArrayBuffer]"===cG.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(o===lG||o===uG)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=tG.deflate(n,o),r===_G)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=tG.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===pG;if(0!==n.avail_out){if(o>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},gG.prototype.onData=function(e){this.chunks.push(e)},gG.prototype.onEnd=function(e){e===pG&&(this.result=iG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var TG={Deflate:gG,deflate:SG,deflateRaw:function(e,t){return(t=t||{}).raw=!0,SG(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,SG(e,t)},constants:qF};const RG=16209;var vG=function(e,t){let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C,b;const I=e.state;n=e.next_in,C=e.input,i=n+(e.avail_in-5),r=e.next_out,b=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=I.dmax,c=I.wsize,d=I.whave,l=I.wnext,u=I.window,h=I.hold,p=I.bits,_=I.lencode,E=I.distcode,m=(1<<I.lenbits)-1,f=(1<<I.distbits)-1;e:do{p<15&&(h+=C[n++]<<p,p+=8,h+=C[n++]<<p,p+=8),g=_[h&m];t:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,0===S)b[r++]=65535&g;else{if(!(16&S)){if(0==(64&S)){g=_[(65535&g)+(h&(1<<S)-1)];continue t}if(32&S){I.mode=16191;break e}e.msg="invalid literal/length code",I.mode=RG;break e}T=65535&g,S&=15,S&&(p<S&&(h+=C[n++]<<p,p+=8),T+=h&(1<<S)-1,h>>>=S,p-=S),p<15&&(h+=C[n++]<<p,p+=8,h+=C[n++]<<p,p+=8),g=E[h&f];n:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,!(16&S)){if(0==(64&S)){g=E[(65535&g)+(h&(1<<S)-1)];continue n}e.msg="invalid distance code",I.mode=RG;break e}if(R=65535&g,S&=15,p<S&&(h+=C[n++]<<p,p+=8,p<S&&(h+=C[n++]<<p,p+=8)),R+=h&(1<<S)-1,R>a){e.msg="invalid distance too far back",I.mode=RG;break e}if(h>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&I.sane){e.msg="invalid distance too far back",I.mode=RG;break e}if(v=0,y=u,0===l){if(v+=c-S,S<T){T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}}else if(l<S){if(v+=c+l-S,S-=l,S<T){T-=S;do{b[r++]=u[v++]}while(--S);if(v=0,l<T){S=l,T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}}}else if(v+=l-S,S<T){T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}for(;T>2;)b[r++]=y[v++],b[r++]=y[v++],b[r++]=y[v++],T-=3;T&&(b[r++]=y[v++],T>1&&(b[r++]=y[v++]))}else{v=r-R;do{b[r++]=b[v++],b[r++]=b[v++],b[r++]=b[v++],T-=3}while(T>2);T&&(b[r++]=b[v++],T>1&&(b[r++]=b[v++]))}break}}break}}while(n<i&&r<s);T=p>>3,n-=T,p-=T<<3,h&=(1<<p)-1,e.next_in=n,e.next_out=r,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=r<s?s-r+257:257-(r-s),I.hold=h,I.bits=p};const yG=15,CG=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]),bG=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]),IG=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]),AG=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 wG=(e,t,n,i,r,o,s,a)=>{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,S=0,T=0,R=0,v=0,y=0,C=0,b=null;const I=new Uint16Array(16),A=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=yG;E++)I[E]=0;for(m=0;m<i;m++)I[t[n+m]]++;for(S=c,g=yG;g>=1&&0===I[g];g--);if(S>g&&(S=g),0===g)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f<g&&0===I[f];f++);for(S<f&&(S=f),v=1,E=1;E<=yG;E++)if(v<<=1,v-=I[E],v<0)return-1;if(v>0&&(0===e||1!==g))return-1;for(A[1]=0,E=1;E<yG;E++)A[E+1]=A[E]+I[E];for(m=0;m<i;m++)0!==t[n+m]&&(s[A[t[n+m]]++]=m);if(0===e?(b=D=s,_=20):1===e?(b=CG,D=bG,_=257):(b=IG,D=AG,_=0),C=0,m=0,E=f,p=o,T=S,R=0,u=-1,y=1<<S,h=y-1,1===e&&y>852||2===e&&y>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=b[s[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(C>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;C&d;)d>>=1;if(0!==d?(C&=d-1,C+=d):C=0,m++,0==--I[E]){if(E===g)break;E=t[n+s[m]]}if(E>S&&(C&h)!==u){for(0===R&&(R=S),p+=f,T=E-R,v=1<<T;T+R<g&&(v-=I[T+R],!(v<=0));)T++,v<<=1;if(y+=1<<T,1===e&&y>852||2===e&&y>592)return 1;u=C&h,r[u]=S<<24|T<<16|p-o|0}}return 0!==C&&(r[p+C]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:OG,Z_BLOCK:NG,Z_TREES:DG,Z_OK:PG,Z_STREAM_END:LG,Z_NEED_DICT:kG,Z_STREAM_ERROR:MG,Z_DATA_ERROR:UG,Z_MEM_ERROR:VG,Z_BUF_ERROR:xG,Z_DEFLATED:FG}=qF,BG=16180,GG=16190,jG=16191,WG=16192,KG=16194,YG=16199,HG=16200,XG=16206,JG=16209,zG=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function ZG(){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 qG=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<BG||t.mode>16211?1:0},QG=e=>{if(qG(e))return MG;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=BG,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,PG},$G=e=>{if(qG(e))return MG;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,QG(e)},ej=(e,t)=>{let n;if(qG(e))return MG;const i=e.state;return t<0?(n=0,t=-t):(n=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?MG:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,$G(e))},tj=(e,t)=>{if(!e)return MG;const n=new ZG;e.state=n,n.strm=e,n.window=null,n.mode=BG;const i=ej(e,t);return i!==PG&&(e.state=null),i};let nj,ij,rj=!0;const oj=e=>{if(rj){nj=new Int32Array(512),ij=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(wG(1,e.lens,0,288,nj,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;wG(2,e.lens,0,32,ij,0,e.work,{bits:5}),rj=!1}e.lencode=nj,e.lenbits=9,e.distcode=ij,e.distbits=5},sj=(e,t,n,i)=>{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)),i>=o.wsize?(o.window.set(t.subarray(n-o.wsize,n),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>i&&(r=i),o.window.set(t.subarray(n-i,n-i+r),o.wnext),(i-=r)?(o.window.set(t.subarray(n-i,n),0),o.wnext=i,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0};var aj=(e,t)=>{let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C=0;const b=new Uint8Array(4);let I,A;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(qG(e)||!e.output||!e.input&&0!==e.avail_in)return MG;n=e.state,n.mode===jG&&(n.mode=WG),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,u=a,h=c,y=PG;e:for(;;)switch(n.mode){case BG:if(0===n.wrap){n.mode=WG;break}for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(2&n.wrap&&35615===d){0===n.wbits&&(n.wbits=15),n.check=0,b[0]=255&d,b[1]=d>>>8&255,n.check=zF(n.check,b,2,0),d=0,l=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",n.mode=JG;break}if((15&d)!==FG){e.msg="unknown compression method",n.mode=JG;break}if(d>>>=4,l-=4,v=8+(15&d),0===n.wbits&&(n.wbits=v),v>15||v>n.wbits){e.msg="invalid window size",n.mode=JG;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=512&d?16189:jG,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.flags=d,(255&oF(n))!==FG){e.msg="unknown compression method",n.mode=JG;break}if(57344&oF(n)){e.msg="unknown header flags set",n.mode=JG;break}n.head&&(n.head.text=d>>8&1),512&oF(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=zF(n.check,b,2,0)),d=0,l=0,n.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.time=d),512&oF(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,b[2]=d>>>16&255,b[3]=d>>>24&255,n.check=zF(n.check,b,4,0)),d=0,l=0,n.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.xflags=255&d,n.head.os=d>>8),512&oF(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=zF(n.check,b,2,0)),d=0,l=0,n.mode=16184;case 16184:if(1024&oF(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length=d,n.head&&(n.head.extra_len=d),512&oF(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=zF(n.check,b,2,0)),d=0,l=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&oF(n)&&(p=n.length,p>a&&(p=a),p&&(n.head&&(v=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(o,o+p),v)),512&oF(n)&&4&n.wrap&&(n.check=zF(n.check,i,p,o)),a-=p,o+=p,n.length-=p),n.length))break e;n.length=0,n.mode=16186;case 16186:if(2048&oF(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.name+=String.fromCharCode(v))}while(v&&p<a);if(512&oF(n)&&4&n.wrap&&(n.check=zF(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=16187;case 16187:if(4096&oF(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.comment+=String.fromCharCode(v))}while(v&&p<a);if(512&oF(n)&&4&n.wrap&&(n.check=zF(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.comment=null);n.mode=16188;case 16188:if(512&oF(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(65535&n.check)){e.msg="header crc mismatch",n.mode=JG;break}d=0,l=0}n.head&&(n.head.hcrc=oF(n)>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=jG;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}e.adler=n.check=zG(d),d=0,l=0,n.mode=GG;case GG:if(0===n.havedict)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,kG;e.adler=n.check=1,n.mode=jG;case jG:if(t===NG||t===DG)break e;case WG:if(n.last){d>>>=7&l,l-=7&l,n.mode=XG;break}for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}switch(n.last=1&d,d>>>=1,l-=1,3&d){case 0:n.mode=16193;break;case 1:if(oj(n),n.mode=YG,t===DG){d>>>=2,l-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=JG}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",n.mode=JG;break}if(n.length=65535&d,d=0,l=0,n.mode=KG,t===DG)break e;case KG:n.mode=16195;case 16195:if(p=n.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(i.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,n.length-=p;break}n.mode=jG;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.nlen=257+(31&d),d>>>=5,l-=5,n.ndist=1+(31&d),d>>>=5,l-=5,n.ncode=4+(15&d),d>>>=4,l-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=JG;break}n.have=0,n.mode=16197;case 16197:for(;n.have<n.ncode;){for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.lens[w[n.have++]]=7&d,d>>>=3,l-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,I={bits:n.lenbits},y=wG(0,n.lens,0,19,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid code lengths set",n.mode=JG;break}n.have=0,n.mode=16198;case 16198:for(;n.have<n.nlen+n.ndist;){for(;C=n.lencode[d&(1<<n.lenbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(g<16)d>>>=m,l-=m,n.lens[n.have++]=g;else{if(16===g){for(A=m+2;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(d>>>=m,l-=m,0===n.have){e.msg="invalid bit length repeat",n.mode=JG;break}v=n.lens[n.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(A=m+3;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=3+(7&d),d>>>=3,l-=3}else{for(A=m+7;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=11+(127&d),d>>>=7,l-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=JG;break}for(;p--;)n.lens[n.have++]=v}}if(n.mode===JG)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=JG;break}if(n.lenbits=9,I={bits:n.lenbits},y=wG(1,n.lens,0,n.nlen,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid literal/lengths set",n.mode=JG;break}if(n.distbits=6,n.distcode=n.distdyn,I={bits:n.distbits},y=wG(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,I),n.distbits=I.bits,y){e.msg="invalid distances set",n.mode=JG;break}if(n.mode=YG,t===DG)break e;case YG:n.mode=HG;case HG:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,vG(e,h),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,n.mode===jG&&(n.back=-1);break}for(n.back=0;C=n.lencode[d&(1<<n.lenbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(f&&0==(240&f)){for(S=m,T=f,R=g;C=n.lencode[R+((d&(1<<S+T)-1)>>S)],m=C>>>24,f=C>>>16&255,g=65535&C,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,n.length=g,0===f){n.mode=16205;break}if(32&f){n.back=-1,n.mode=jG;break}if(64&f){e.msg="invalid literal/length code",n.mode=JG;break}n.extra=15&f,n.mode=16201;case 16201:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;C=n.distcode[d&(1<<n.distbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(0==(240&f)){for(S=m,T=f,R=g;C=n.distcode[R+((d&(1<<S+T)-1)>>S)],m=C>>>24,f=C>>>16&255,g=65535&C,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,64&f){e.msg="invalid distance code",n.mode=JG;break}n.offset=g,n.extra=15&f,n.mode=16203;case 16203:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.offset+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=JG;break}n.mode=16204;case 16204:if(0===c)break e;if(p=h-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=JG;break}p>n.wnext?(p-=n.wnext,_=n.wsize-p):_=n.wnext-p,p>n.length&&(p=n.length),E=n.window}else E=r,_=s-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do{r[s++]=E[_++]}while(--p);0===n.length&&(n.mode=HG);break;case 16205:if(0===c)break e;r[s++]=n.length,c--,n.mode=HG;break;case XG:if(n.wrap){for(;l<32;){if(0===a)break e;a--,d|=i[o++]<<l,l+=8}if(h-=c,e.total_out+=h,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=oF(n)?zF(n.check,r,h,s-h):XF(n.check,r,h,s-h)),h=c,4&n.wrap&&(oF(n)?d:zG(d))!==n.check){e.msg="incorrect data check",n.mode=JG;break}d=0,l=0}n.mode=16207;case 16207:if(n.wrap&&oF(n)){for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=JG;break}d=0,l=0}n.mode=16208;case 16208:y=LG;break e;case JG:y=UG;break e;case 16210:return VG;default:return MG}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,(n.wsize||h!==e.avail_out&&n.mode<JG&&(n.mode<XG||t!==OG))&&sj(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,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=oF(n)?zF(n.check,r,h,e.next_out-h):XF(n.check,r,h,e.next_out-h)),e.data_type=n.bits+(n.last?64:0)+(n.mode===jG?128:0)+(n.mode===YG||n.mode===KG?256:0),(0===u&&0===h||t===OG)&&y===PG&&(y=xG),y},cj={inflateReset:$G,inflateReset2:ej,inflateResetKeep:QG,inflateInit:e=>tj(e,15),inflateInit2:tj,inflate:aj,inflateEnd:e=>{if(qG(e))return MG;let t=e.state;return t.window&&(t.window=null),e.state=null,PG},inflateGetHeader:(e,t)=>{if(qG(e))return MG;const n=e.state;return 0==(2&n.wrap)?MG:(n.head=t,t.done=!1,PG)},inflateSetDictionary:(e,t)=>{const n=t.length;let i,r,o;return qG(e)?MG:(i=e.state,0!==i.wrap&&i.mode!==GG?MG:i.mode===GG&&(r=1,r=XF(r,t,n,0),r!==i.check)?UG:(o=sj(e,t,n,n),o?(i.mode=16210,VG):(i.havedict=1,PG)))},inflateInfo:"pako inflate (from Nodeca project)"};var dj=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 lj=Object.prototype.toString,{Z_NO_FLUSH:uj,Z_FINISH:hj,Z_OK:pj,Z_STREAM_END:_j,Z_NEED_DICT:Ej,Z_STREAM_ERROR:mj,Z_DATA_ERROR:fj,Z_MEM_ERROR:gj}=qF;function Sj(e){this.options=iG.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 aG,this.strm.avail_out=0;let n=cj.inflateInit2(this.strm,t.windowBits);if(n!==pj)throw new Error(ZF[n]);if(this.header=new dj,cj.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=sG.string2buf(t.dictionary):"[object ArrayBuffer]"===lj.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=cj.inflateSetDictionary(this.strm,t.dictionary),n!==pj)))throw new Error(ZF[n])}function Tj(e,t){const n=new Sj(t);if(n.push(e),n.err)throw n.msg||ZF[n.err];return n.result}Sj.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?hj:uj,"[object ArrayBuffer]"===lj.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),o=cj.inflate(n,s),o===Ej&&r&&(o=cj.inflateSetDictionary(n,r),o===pj?o=cj.inflate(n,s):o===fj&&(o=Ej));n.avail_in>0&&o===_j&&n.state.wrap>0&&0!==e[n.next_in];)cj.inflateReset(n),o=cj.inflate(n,s);switch(o){case mj:case fj:case Ej:case gj:return this.onEnd(o),this.ended=!0,!1}if(a=n.avail_out,n.next_out&&(0===n.avail_out||o===_j))if("string"===this.options.to){let e=sG.utf8border(n.output,n.next_out),t=n.next_out-e,r=sG.buf2string(n.output,e);n.next_out=t,n.avail_out=i-t,t&&n.output.set(n.output.subarray(e,e+t),0),this.onData(r)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(o!==pj||0!==a){if(o===_j)return o=cj.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},Sj.prototype.onData=function(e){this.chunks.push(e)},Sj.prototype.onEnd=function(e){e===pj&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=iG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Rj={Inflate:Sj,inflate:Tj,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Tj(e,t)},ungzip:Tj,constants:qF};const{Deflate:vj,deflate:yj,deflateRaw:Cj,gzip:bj}=TG,{Inflate:Ij,inflate:Aj,inflateRaw:wj,ungzip:Oj}=Rj;var Nj,Dj=yj,Pj=Cj,Lj=Aj,kj=wj,Mj=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}(Mj||{});function Uj(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}function Vj(e){return e.replace(/[A-Z]/g,(e=>"_"+e.toLowerCase()))}const xj=new Set(["constructor","toString","toJSON","valueOf"]);function Fj(e){return xj.has(e)?e+"$":e}var Bj=void 0!==uT?uT:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Gj(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var jj,Wj,Kj=function(e){try{return!!e()}catch(e){return!0}},Yj=!Kj((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),Hj=Yj,Xj=Function.prototype,Jj=Xj.call,zj=Hj&&Xj.bind.bind(Jj,Jj),Zj=Hj?zj:function(e){return function(){return Jj.apply(e,arguments)}},qj=Zj,Qj=qj({}.toString),$j=qj("".slice),eW=function(e){return $j(Qj(e),8,-1)},tW=Kj,nW=eW,iW=Object,rW=Zj("".split),oW=tW((function(){return!iW("z").propertyIsEnumerable(0)}))?function(e){return"String"==nW(e)?rW(e,""):iW(e)}:iW,sW=function(e){return null==e},aW=sW,cW=TypeError,dW=function(e){if(aW(e))throw cW("Can't call method on "+e);return e},lW=oW,uW=dW,hW=function(e){return lW(uW(e))},pW={},_W=function(e){return e&&e.Math==Math&&e},EW=_W("object"==typeof uT&&uT)||_W("object"==typeof window&&window)||_W("object"==typeof self&&self)||_W("object"==typeof Bj&&Bj)||function(){return this}()||Bj||Function("return this")(),mW="object"==typeof document&&document.all,fW={all:mW,IS_HTMLDDA:void 0===mW&&void 0!==mW},gW=fW.all,SW=fW.IS_HTMLDDA?function(e){return"function"==typeof e||e===gW}:function(e){return"function"==typeof e},TW=SW,RW=EW.WeakMap,vW=TW(RW)&&/native code/.test(String(RW)),yW=SW,CW=fW.all,bW=fW.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:yW(e)||e===CW}:function(e){return"object"==typeof e?null!==e:yW(e)},IW=!Kj((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),AW={},wW=bW,OW=EW.document,NW=wW(OW)&&wW(OW.createElement),DW=function(e){return NW?OW.createElement(e):{}},PW=DW,LW=!IW&&!Kj((function(){return 7!=Object.defineProperty(PW("div"),"a",{get:function(){return 7}}).a})),kW=IW&&Kj((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),MW=bW,UW=String,VW=TypeError,xW=function(e){if(MW(e))return e;throw VW(UW(e)+" is not an object")},FW=Yj,BW=Function.prototype.call,GW=FW?BW.bind(BW):function(){return BW.apply(BW,arguments)},jW={},WW=jW,KW=EW,YW=SW,HW=function(e){return YW(e)?e:void 0},XW=function(e,t){return arguments.length<2?HW(WW[e])||HW(KW[e]):WW[e]&&WW[e][t]||KW[e]&&KW[e][t]},JW=Zj({}.isPrototypeOf),zW="undefined"!=typeof navigator&&String(navigator.userAgent)||"",ZW=EW,qW=zW,QW=ZW.process,$W=ZW.Deno,eK=QW&&QW.versions||$W&&$W.version,tK=eK&&eK.v8;tK&&(Wj=(jj=tK.split("."))[0]>0&&jj[0]<4?1:+(jj[0]+jj[1])),!Wj&&qW&&(!(jj=qW.match(/Edge\/(\d+)/))||jj[1]>=74)&&(jj=qW.match(/Chrome\/(\d+)/))&&(Wj=+jj[1]);var nK=Wj,iK=nK,rK=Kj,oK=EW.String,sK=!!Object.getOwnPropertySymbols&&!rK((function(){var e=Symbol();return!oK(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&iK&&iK<41})),aK=sK&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,cK=XW,dK=SW,lK=JW,uK=Object,hK=aK?function(e){return"symbol"==typeof e}:function(e){var t=cK("Symbol");return dK(t)&&lK(t.prototype,uK(e))},pK=String,_K=function(e){try{return pK(e)}catch(e){return"Object"}},EK=SW,mK=_K,fK=TypeError,gK=function(e){if(EK(e))return e;throw fK(mK(e)+" is not a function")},SK=gK,TK=sW,RK=GW,vK=SW,yK=bW,CK=TypeError,bK={exports:{}},IK=EW,AK=Object.defineProperty,wK="__core-js_shared__",OK=EW[wK]||function(e,t){try{AK(IK,e,{value:t,configurable:!0,writable:!0})}catch(n){IK[e]=t}return t}(wK,{}),NK=OK;(bK.exports=function(e,t){return NK[e]||(NK[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 DK=bK.exports,PK=dW,LK=Object,kK=function(e){return LK(PK(e))},MK=kK,UK=Zj({}.hasOwnProperty),VK=Object.hasOwn||function(e,t){return UK(MK(e),t)},xK=Zj,FK=0,BK=Math.random(),GK=xK(1..toString),jK=function(e){return"Symbol("+(void 0===e?"":e)+")_"+GK(++FK+BK,36)},WK=DK,KK=VK,YK=jK,HK=sK,XK=aK,JK=EW.Symbol,zK=WK("wks"),ZK=XK?JK.for||JK:JK&&JK.withoutSetter||YK,qK=function(e){return KK(zK,e)||(zK[e]=HK&&KK(JK,e)?JK[e]:ZK("Symbol."+e)),zK[e]},QK=GW,$K=bW,eY=hK,tY=TypeError,nY=qK("toPrimitive"),iY=function(e,t){if(!$K(e)||eY(e))return e;var n,i=function(e,t){var n=e[t];return TK(n)?void 0:SK(n)}(e,nY);if(i){if(void 0===t&&(t="default"),n=QK(i,e,t),!$K(n)||eY(n))return n;throw tY("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var n,i;if("string"===t&&vK(n=e.toString)&&!yK(i=RK(n,e)))return i;if(vK(n=e.valueOf)&&!yK(i=RK(n,e)))return i;if("string"!==t&&vK(n=e.toString)&&!yK(i=RK(n,e)))return i;throw CK("Can't convert object to primitive value")}(e,t)},rY=hK,oY=function(e){var t=iY(e,"string");return rY(t)?t:t+""},sY=IW,aY=LW,cY=kW,dY=xW,lY=oY,uY=TypeError,hY=Object.defineProperty,pY=Object.getOwnPropertyDescriptor,_Y="enumerable",EY="configurable",mY="writable";AW.f=sY?cY?function(e,t,n){if(dY(e),t=lY(t),dY(n),"function"==typeof e&&"prototype"===t&&"value"in n&&mY in n&&!n[mY]){var i=pY(e,t);i&&i[mY]&&(e[t]=n.value,n={configurable:EY in n?n[EY]:i[EY],enumerable:_Y in n?n[_Y]:i[_Y],writable:!1})}return hY(e,t,n)}:hY:function(e,t,n){if(dY(e),t=lY(t),dY(n),aY)try{return hY(e,t,n)}catch(e){}if("get"in n||"set"in n)throw uY("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var fY,gY,SY,TY=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},RY=AW,vY=TY,yY=IW?function(e,t,n){return RY.f(e,t,vY(1,n))}:function(e,t,n){return e[t]=n,e},CY=jK,bY=DK("keys"),IY=function(e){return bY[e]||(bY[e]=CY(e))},AY={},wY=vW,OY=EW,NY=bW,DY=yY,PY=VK,LY=OK,kY=IY,MY=AY,UY="Object already initialized",VY=OY.TypeError,xY=OY.WeakMap;if(wY||LY.state){var FY=LY.state||(LY.state=new xY);FY.get=FY.get,FY.has=FY.has,FY.set=FY.set,fY=function(e,t){if(FY.has(e))throw VY(UY);return t.facade=e,FY.set(e,t),t},gY=function(e){return FY.get(e)||{}},SY=function(e){return FY.has(e)}}else{var BY=kY("state");MY[BY]=!0,fY=function(e,t){if(PY(e,BY))throw VY(UY);return t.facade=e,DY(e,BY,t),t},gY=function(e){return PY(e,BY)?e[BY]:{}},SY=function(e){return PY(e,BY)}}var GY={set:fY,get:gY,has:SY,enforce:function(e){return SY(e)?gY(e):fY(e,{})},getterFor:function(e){return function(t){var n;if(!NY(t)||(n=gY(t)).type!==e)throw VY("Incompatible receiver, "+e+" required");return n}}},jY=Yj,WY=Function.prototype,KY=WY.apply,YY=WY.call,HY="object"==typeof Reflect&&Reflect.apply||(jY?YY.bind(KY):function(){return YY.apply(KY,arguments)}),XY=eW,JY=Zj,zY=function(e){if("Function"===XY(e))return JY(e)},ZY={},qY={},QY={}.propertyIsEnumerable,$Y=Object.getOwnPropertyDescriptor,eH=$Y&&!QY.call({1:2},1);qY.f=eH?function(e){var t=$Y(this,e);return!!t&&t.enumerable}:QY;var tH=IW,nH=GW,iH=qY,rH=TY,oH=hW,sH=oY,aH=VK,cH=LW,dH=Object.getOwnPropertyDescriptor;ZY.f=tH?dH:function(e,t){if(e=oH(e),t=sH(t),cH)try{return dH(e,t)}catch(e){}if(aH(e,t))return rH(!nH(iH.f,e,t),e[t])};var lH=Kj,uH=SW,hH=/#|\.prototype\./,pH=function(e,t){var n=EH[_H(e)];return n==fH||n!=mH&&(uH(t)?lH(t):!!t)},_H=pH.normalize=function(e){return String(e).replace(hH,".").toLowerCase()},EH=pH.data={},mH=pH.NATIVE="N",fH=pH.POLYFILL="P",gH=pH,SH=gK,TH=Yj,RH=zY(zY.bind),vH=EW,yH=HY,CH=zY,bH=SW,IH=ZY.f,AH=gH,wH=jW,OH=function(e,t){return SH(e),void 0===t?e:TH?RH(e,t):function(){return e.apply(t,arguments)}},NH=yY,DH=VK,PH=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return yH(e,this,arguments)};return t.prototype=e.prototype,t},LH=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?vH:p?vH[u]:(vH[u]||{}).prototype,m=h?wH:wH[u]||NH(wH,u,{})[u],f=m.prototype;for(o in t)i=!(n=AH(h?o:u+(p?".":"#")+o,e.forced))&&E&&DH(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=IH(E,o))&&l.value:E[o]),s=i&&c?c:t[o],i&&typeof a==typeof s||(d=e.bind&&i?OH(s,vH):e.wrap&&i?PH(s):_&&bH(s)?CH(s):s,(e.sham||s&&s.sham||a&&a.sham)&&NH(d,"sham",!0),NH(m,o,d),_&&(DH(wH,r=u+"Prototype")||NH(wH,r,{}),NH(wH[r],o,s),e.real&&f&&(n||!f[o])&&NH(f,o,s)))},kH=IW,MH=VK,UH=Function.prototype,VH=kH&&Object.getOwnPropertyDescriptor,xH=MH(UH,"name"),FH={EXISTS:xH,PROPER:xH&&"something"===function(){}.name,CONFIGURABLE:xH&&(!kH||kH&&VH(UH,"name").configurable)},BH={},GH=Math.ceil,jH=Math.floor,WH=Math.trunc||function(e){var t=+e;return(t>0?jH:GH)(t)},KH=function(e){var t=+e;return t!=t||0===t?0:WH(t)},YH=KH,HH=Math.max,XH=Math.min,JH=function(e,t){var n=YH(e);return n<0?HH(n+t,0):XH(n,t)},zH=KH,ZH=Math.min,qH=function(e){return function(e){return e>0?ZH(zH(e),9007199254740991):0}(e.length)},QH=hW,$H=JH,eX=qH,tX=function(e){return function(t,n,i){var r,o=QH(t),s=eX(o),a=$H(i,s);if(e&&n!=n){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===n)return e||a||0;return!e&&-1}},nX={includes:tX(!0),indexOf:tX(!1)},iX=VK,rX=hW,oX=nX.indexOf,sX=AY,aX=Zj([].push),cX=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],dX=cX,lX=Object.keys||function(e){return function(e,t){var n,i=rX(e),r=0,o=[];for(n in i)!iX(sX,n)&&iX(i,n)&&aX(o,n);for(;t.length>r;)iX(i,n=t[r++])&&(~oX(o,n)||aX(o,n));return o}(e,dX)},uX=IW,hX=kW,pX=AW,_X=xW,EX=hW,mX=lX;BH.f=uX&&!hX?Object.defineProperties:function(e,t){_X(e);for(var n,i=EX(t),r=mX(t),o=r.length,s=0;o>s;)pX.f(e,n=r[s++],i[n]);return e};var fX,gX=XW("document","documentElement"),SX=xW,TX=BH,RX=cX,vX=AY,yX=gX,CX=DW,bX="prototype",IX="script",AX=IY("IE_PROTO"),wX=function(){},OX=function(e){return"<"+IX+">"+e+"</"+IX+">"},NX=function(e){e.write(OX("")),e.close();var t=e.parentWindow.Object;return e=null,t},DX=function(){try{fX=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;DX="undefined"!=typeof document?document.domain&&fX?NX(fX):(t=CX("iframe"),n="java"+IX+":",t.style.display="none",yX.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(OX("document.F=Object")),e.close(),e.F):NX(fX);for(var i=RX.length;i--;)delete DX[bX][RX[i]];return DX()};vX[AX]=!0;var PX,LX,kX,MX=Object.create||function(e,t){var n;return null!==e?(wX[bX]=SX(e),n=new wX,wX[bX]=null,n[AX]=e):n=DX(),void 0===t?n:TX.f(n,t)},UX=!Kj((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),VX=VK,xX=SW,FX=kK,BX=UX,GX=IY("IE_PROTO"),jX=Object,WX=jX.prototype,KX=BX?jX.getPrototypeOf:function(e){var t=FX(e);if(VX(t,GX))return t[GX];var n=t.constructor;return xX(n)&&t instanceof n?n.prototype:t instanceof jX?WX:null},YX=yY,HX=function(e,t,n,i){return i&&i.enumerable?e[t]=n:YX(e,t,n),e},XX=Kj,JX=SW,zX=bW,ZX=MX,qX=KX,QX=HX,$X=qK("iterator"),eJ=!1;CD([])&&("next"in(kX=CD(Nj=[]).call(Nj))?(LX=qX(qX(kX)))!==Object.prototype&&(PX=LX):eJ=!0);var tJ=!zX(PX)||XX((function(){var e={};return PX[$X].call(e)!==e}));JX((PX=tJ?{}:ZX(PX))[$X])||QX(PX,$X,(function(){return this}));var nJ={IteratorPrototype:PX,BUGGY_SAFARI_ITERATORS:eJ},iJ={};iJ[qK("toStringTag")]="z";var rJ="[object z]"===String(iJ),oJ=rJ,sJ=SW,aJ=eW,cJ=qK("toStringTag"),dJ=Object,lJ="Arguments"==aJ(function(){return arguments}()),uJ=oJ?aJ:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=dJ(e),cJ))?n:lJ?aJ(t):"Object"==(i=aJ(t))&&sJ(t.callee)?"Arguments":i},hJ=uJ,pJ=rJ?{}.toString:function(){return"[object "+hJ(this)+"]"},_J=rJ,EJ=AW.f,mJ=yY,fJ=VK,gJ=pJ,SJ=qK("toStringTag"),TJ=function(e,t,n,i){if(e){var r=n?e:e.prototype;fJ(r,SJ)||EJ(r,SJ,{configurable:!0,value:t}),i&&!_J&&mJ(r,"toString",gJ)}},RJ=nJ.IteratorPrototype,vJ=MX,yJ=TY,CJ=TJ,bJ=pW,IJ=function(){return this},AJ=LH,wJ=GW,OJ=KX,NJ=TJ,DJ=HX,PJ=pW,LJ=FH.PROPER,kJ=nJ.BUGGY_SAFARI_ITERATORS,MJ=qK("iterator"),UJ="keys",VJ="values",xJ="entries",FJ=function(){return this},BJ=hW,GJ=pW,jJ=GY;AW.f;var WJ=function(e,t){return{value:e,done:t}},KJ="Array Iterator",YJ=jJ.set,HJ=jJ.getterFor(KJ);(function(e,t,n,i,r,o,s){!function(e,t,n,i){var r=t+" Iterator";e.prototype=vJ(RJ,{next:yJ(+!i,n)}),CJ(e,r,!1,!0),bJ[r]=IJ}(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!kJ&&e in p)return p[e];switch(e){case UJ:case VJ:case xJ:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[MJ]||p["@@iterator"]||r&&p[r],E=!kJ&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=OJ(m.call(new e)))!==Object.prototype&&a.next&&(NJ(a,u,!0,!0),PJ[u]=FJ),LJ&&r==VJ&&_&&_.name!==VJ&&(h=!0,E=function(){return wJ(_,this)}),r)if(c={values:l(VJ),keys:o?E:l(UJ),entries:l(xJ)},s)for(d in c)(kJ||h||!(d in p))&&DJ(p,d,c[d]);else AJ({target:t,proto:!0,forced:kJ||h},c);s&&p[MJ]!==E&&DJ(p,MJ,E,{name:r}),PJ[t]=E})(Array,"Array",(function(e,t){YJ(this,{type:KJ,target:BJ(e),index:0,kind:t})}),(function(){var e=HJ(this),t=e.target,n=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,WJ(void 0,!0)):WJ("keys"==n?i:"values"==n?t[i]:[i,t[i]],!1)}),"values"),GJ.Arguments=GJ.Array;var XJ=EW,JJ=uJ,zJ=yY,ZJ=pW,qJ=qK("toStringTag");for(var QJ in{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}){var $J=XJ[QJ],ez=$J&&$J.prototype;ez&&JJ(ez)!==qJ&&zJ(ez,qJ,QJ),ZJ[QJ]=ZJ.Array}var tz=jW,nz=function(e){return tz[e+"Prototype"]},iz=Qh(nz("Array")),rz=uJ,oz=VK,sz=JW,az=iz,cz=Array.prototype,dz={DOMTokenList:!0,NodeList:!0},lz=Gj((function(e){var t=Qh(e);return e===cz||sz(cz,e)&&t===Qh(cz)||oz(dz,rz(e))?az:t})),uz=EW;LH({global:!0,forced:uz.globalThis!==uz},{globalThis:uz});var hz=Gj(EW);function pz(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function _z(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,o=!(r>>>7==0&&0==t),s=255&(o?128|r:r);if(n.push(s),!o)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),o=255&(r?128|i:i);if(n.push(o),!r)return}n.push(t>>>31&1)}}const Ez=4294967296;function mz(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(t,o){const s=Number(e.slice(t,o));r*=n,i=i*n+s,i>=Ez&&(r+=i/Ez|0,i%=Ez)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?Sz(i,r):gz(i,r)}function fz(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(Ez*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,o=n+8147497*i,s=2*i;const a=1e7;return r>=a&&(o+=Math.floor(r/a),r%=a),o>=a&&(s+=Math.floor(o/a),o%=a),s.toString()+Tz(o)+Tz(r)}function gz(e,t){return{lo:0|e,hi:0|t}}function Sz(e,t){return t=~t,e?e=1+~e:t+=1,gz(e,t)}const Tz=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Rz(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function vz(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const yz=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&(hz.Deno||"object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("invalid int64: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)throw new Error("invalid uint64: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),Cz(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),bz(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),Cz(e),mz(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),bz(e),mz(e)),dec:(e,t)=>function(e,t){let n=gz(e,t);const i=2147483648&n.hi;i&&(n=Sz(n.lo,n.hi));const r=fz(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>fz(e,t)}}();function Cz(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function bz(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}var Iz;function Az(e,t){switch(e){case Iz.STRING:return"";case Iz.BOOL:return!1;case Iz.DOUBLE:case Iz.FLOAT:return 0;case Iz.INT64:case Iz.UINT64:case Iz.SFIXED64:case Iz.FIXED64:case Iz.SINT64:return t?"0":yz.zero;case Iz.BYTES:return new Uint8Array(0);default:return 0}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(Iz||(Iz={}));const wz=2,Oz=Symbol.for("reflect unsafe local");function Nz(e,t){const n=e[t.localName].case;return void 0===n?n:t.fields.find((e=>e.localName===n))}function Dz(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&void 0!==e[t]}function Pz(e,t){if(t.oneof){const n=e[t.oneof.localName];return n.case===t.localName?n.value:void 0}return e[t.localName]}function Lz(e,t,n){t.oneof?e[t.oneof.localName]={case:t.localName,value:n}:e[t.localName]=n}function kz(e){for(const t of e.field)Dz(t,"jsonName")||(t.jsonName=Uj(t.name));e.nestedType.forEach(kz)}var Mz=eW,Uz=LH,Vz=Array.isArray||function(e){return"Array"==Mz(e)},xz=Zj(cr([])),Fz=[1,2];Uz({target:"Array",proto:!0,forced:String(Fz)===String(cr(Fz).call(Fz))},{reverse:function(){return Vz(this)&&(this.length=this.length),xz(this)}});var Bz=cr(nz("Array")),Gz=JW,jz=Bz,Wz=Array.prototype,Kz=Gj((function(e){var t=cr(e);return e===Wz||Gz(Wz,e)&&t===cr(Wz)?jz:t}));function*Yz(e){switch(e.kind){case"file":for(const t of e.messages)yield t,yield*Yz(t);yield*e.enums,yield*e.services,yield*e.extensions;break;case"message":for(const t of e.nestedMessages)yield t,yield*Yz(t);yield*e.nestedEnums,yield*e.nestedExtensions}}function Hz(){const e=function(){const e=new Map,t=new Map,n=new Map;return{kind:"registry",types:e,extendees:t,[Symbol.iterator]:()=>lz(e).call(e),get files(){return lz(n).call(n)},addFile(e,t,i){if(n.set(e.proto.name,e),!t)for(const t of Yz(e))this.add(t);if(i)for(const n of e.dependencies)this.addFile(n,t,i)},add(n){if("extension"==n.kind){let e=t.get(n.extendee.typeName);e||t.set(n.extendee.typeName,e=new Map),e.set(n.number,n)}e.set(n.typeName,n)},get:t=>e.get(t),getFile:e=>n.get(e),getMessage(t){const n=e.get(t);return"message"==(null==n?void 0:n.kind)?n:void 0},getEnum(t){const n=e.get(t);return"enum"==(null==n?void 0:n.kind)?n:void 0},getExtension(t){const n=e.get(t);return"extension"==(null==n?void 0:n.kind)?n:void 0},getExtensionFor(e,n){var i;return null===(i=t.get(e.typeName))||void 0===i?void 0:i.get(n)},getService(t){const n=e.get(t);return"service"==(null==n?void 0:n.kind)?n:void 0}}}();for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];if(!n.length)return e;if("$typeName"in n[0]&&"google.protobuf.FileDescriptorSet"==n[0].$typeName){for(const t of n[0].file)uZ(t,e);return e}if("$typeName"in n[0]){const t=n[0],i=n[1],o=new Set;for(const n of Kz(r=[t,...function t(n){const r=[];for(const t of n.dependency){if(null!=e.getFile(t))continue;if(o.has(t))continue;const s=i(t);if(!s)throw new Error("Unable to resolve ".concat(t,", imported by ").concat(n.name));"kind"in s?e.addFile(s,!1,!0):(o.add(s.name),r.push(s))}return r.concat(...r.map(t))}(t)]).call(r)){var r;uZ(n,e)}}else for(const t of n)for(const n of t.files)e.addFile(n);return e}const Xz=998,Jz=999,zz=9,Zz=10,qz=11,Qz=12,$z=14,eZ=3,tZ=2,nZ=1,iZ=0,rZ=1,oZ=2,sZ=3,aZ=1,cZ=2,dZ=1,lZ={998:{fieldPresence:1,enumType:2,repeatedFieldEncoding:2,utf8Validation:3,messageEncoding:1,jsonFormat:2,enforceNamingStyle:2,defaultSymbolVisibility:1},999:{fieldPresence:2,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1e3:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1001:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:1,defaultSymbolVisibility:2}};function uZ(e,t){var n,i;const r={kind:"file",proto:e,deprecated:null!==(i=null===(n=e.options)||void 0===n?void 0:n.deprecated)&&void 0!==i&&i,edition:SZ(e),name:e.name.replace(/\.proto$/,""),dependencies:TZ(e,t),enums:[],messages:[],extensions:[],services:[],toString:()=>"file ".concat(e.name)},o=new Map,s={get:e=>o.get(e),add(e){var t;AZ(!0===(null===(t=e.proto.options)||void 0===t?void 0:t.mapEntry)),o.set(e.typeName,e)}};for(const n of e.enumType)_Z(n,r,void 0,t);for(const n of e.messageType)EZ(n,r,void 0,t,s);for(const n of e.service)mZ(n,r,t);hZ(r,t);for(const e of lz(o).call(o))pZ(e,t,s);for(const e of r.messages)pZ(e,t,s),hZ(e,t);t.addFile(r,!0)}function hZ(e,t){switch(e.kind){case"file":for(const n of e.proto.extension){const i=gZ(n,e,t);e.extensions.push(i),t.add(i)}break;case"message":for(const n of e.proto.extension){const i=gZ(n,e,t);e.nestedExtensions.push(i),t.add(i)}for(const n of e.nestedMessages)hZ(n,t)}}function pZ(e,t,n){const i=e.proto.oneofDecl.map((t=>function(e,t){return{kind:"oneof",proto:e,deprecated:!1,parent:t,fields:[],name:e.name,localName:Fj(Uj(e.name)),toString(){return"oneof ".concat(t.typeName,".").concat(this.name)}}}(t,e))),r=new Set;for(const o of e.proto.field){const s=yZ(o,i),a=gZ(o,e,t,s,n);e.fields.push(a),e.field[a.localName]=a,void 0===s?e.members.push(a):(s.fields.push(a),r.has(s)||(r.add(s),e.members.push(s)))}for(const t of i.filter((e=>r.has(e))))e.oneofs.push(t);for(const i of e.nestedMessages)pZ(i,t,n)}function _Z(e,t,n,i){var r,o,s,a,c;const d=function(e,t){const n=((i=e).substring(0,1)+i.substring(1).replace(/[A-Z]/g,(e=>"_"+e))).toLowerCase()+"_";var i;for(const e of t){if(!e.name.toLowerCase().startsWith(n))return;const t=e.name.substring(n.length);if(0==t.length)return;if(/^\d/.test(t))return}return n}(e.name,e.value),l={kind:"enum",proto:e,deprecated:null!==(o=null===(r=e.options)||void 0===r?void 0:r.deprecated)&&void 0!==o&&o,file:t,parent:n,open:!0,name:e.name,typeName:RZ(e,n,t),value:{},values:[],sharedPrefix:d,toString(){return"enum ".concat(this.typeName)}};l.open=function(e){var t;return dZ==IZ("enumType",{proto:e.proto,parent:null!==(t=e.parent)&&void 0!==t?t:e.file})}(l),i.add(l);for(const t of e.value){const e=t.name;lz(l).push(l.value[t.number]={kind:"enum_value",proto:t,deprecated:null!==(a=null===(s=t.options)||void 0===s?void 0:s.deprecated)&&void 0!==a&&a,parent:l,name:e,localName:Fj(null==d?e:e.substring(d.length)),number:t.number,toString:()=>"enum value ".concat(l.typeName,".").concat(e)})}(null!==(c=null==n?void 0:n.nestedEnums)&&void 0!==c?c:t.enums).push(l)}function EZ(e,t,n,i,r){var o,s,a,c;const d={kind:"message",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,file:t,parent:n,name:e.name,typeName:RZ(e,n,t),fields:[],field:{},oneofs:[],members:[],nestedEnums:[],nestedMessages:[],nestedExtensions:[],toString(){return"message ".concat(this.typeName)}};!0===(null===(a=e.options)||void 0===a?void 0:a.mapEntry)?r.add(d):((null!==(c=null==n?void 0:n.nestedMessages)&&void 0!==c?c:t.messages).push(d),i.add(d));for(const n of e.enumType)_Z(n,t,d,i);for(const n of e.nestedType)EZ(n,t,d,i,r)}function mZ(e,t,n){var i,r;const o={kind:"service",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,file:t,name:e.name,typeName:RZ(e,void 0,t),methods:[],method:{},toString(){return"service ".concat(this.typeName)}};t.services.push(o),n.add(o);for(const t of e.method){const e=fZ(t,o,n);o.methods.push(e),o.method[e.localName]=e}}function fZ(e,t,n){var i,r,o,s;let a;a=e.clientStreaming&&e.serverStreaming?"bidi_streaming":e.clientStreaming?"client_streaming":e.serverStreaming?"server_streaming":"unary";const c=n.getMessage(vZ(e.inputType)),d=n.getMessage(vZ(e.outputType));AZ(c,"invalid MethodDescriptorProto: input_type ".concat(e.inputType," not found")),AZ(d,"invalid MethodDescriptorProto: output_type ".concat(e.inputType," not found"));const l=e.name;return{kind:"rpc",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,parent:t,name:l,localName:Fj(l.length?Fj(l[0].toLowerCase()+l.substring(1)):l),methodKind:a,input:c,output:d,idempotency:null!==(s=null===(o=e.options)||void 0===o?void 0:o.idempotencyLevel)&&void 0!==s?s:iZ,toString:()=>"rpc ".concat(t.typeName,".").concat(l)}}function gZ(e,t,n,i,r){var o,s,a;const c=void 0===r,d={kind:"field",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,name:e.name,number:e.number,scalar:void 0,message:void 0,enum:void 0,presence:CZ(e,i,c,t),listKind:void 0,mapKind:void 0,mapKey:void 0,delimitedEncoding:void 0,packed:void 0,longAsString:!1,getDefaultValue:void 0};if(c){const i="file"==t.kind?t:t.file,r="file"==t.kind?void 0:t,o=RZ(e,r,i);d.kind="extension",d.file=i,d.parent=r,d.oneof=void 0,d.typeName=o,d.jsonName="[".concat(o,"]"),d.toString=()=>"extension ".concat(o);const s=n.getMessage(vZ(e.extendee));AZ(s,"invalid FieldDescriptorProto: extendee ".concat(e.extendee," not found")),d.extendee=s}else{const n=t;AZ("message"==n.kind),d.parent=n,d.oneof=i,d.localName=i?Uj(e.name):Fj(Uj(e.name)),d.jsonName=e.jsonName,d.toString=()=>"field ".concat(n.typeName,".").concat(e.name)}const l=e.label,u=e.type,h=null===(a=e.options)||void 0===a?void 0:a.jstype;if(l===eZ){const i=u==qz?null==r?void 0:r.get(vZ(e.typeName)):void 0;if(i){d.fieldKind="map";const{key:e,value:t}=function(e){const t=e.fields.find((e=>1===e.number)),n=e.fields.find((e=>2===e.number));return AZ(t&&"scalar"==t.fieldKind&&t.scalar!=Iz.BYTES&&t.scalar!=Iz.FLOAT&&t.scalar!=Iz.DOUBLE&&n&&"list"!=n.fieldKind&&"map"!=n.fieldKind),{key:t,value:n}}(i);return d.mapKey=e.scalar,d.mapKind=t.fieldKind,d.message=t.message,d.delimitedEncoding=!1,d.enum=t.enum,d.scalar=t.scalar,d}switch(d.fieldKind="list",u){case qz:case Zz:d.listKind="message",d.message=n.getMessage(vZ(e.typeName)),AZ(d.message),d.delimitedEncoding=bZ(e,t);break;case $z:d.listKind="enum",d.enum=n.getEnum(vZ(e.typeName)),AZ(d.enum);break;default:d.listKind="scalar",d.scalar=u,d.longAsString=h==nZ}return d.packed=function(e,t){if(e.label!=eZ)return!1;switch(e.type){case zz:case Qz:case Zz:case qz:return!1}const n=e.options;return n&&Dz(n,"packed")?n.packed:aZ==IZ("repeatedFieldEncoding",{proto:e,parent:t})}(e,t),d}switch(u){case qz:case Zz:d.fieldKind="message",d.message=n.getMessage(vZ(e.typeName)),AZ(d.message,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.delimitedEncoding=bZ(e,t),d.getDefaultValue=()=>{};break;case $z:{const t=n.getEnum(vZ(e.typeName));AZ(void 0!==t,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.fieldKind="enum",d.enum=n.getEnum(vZ(e.typeName)),d.getDefaultValue=()=>Dz(e,"defaultValue")?function(e,t){const n=lz(e).find((e=>e.name===t));if(!n)throw new Error("cannot parse ".concat(e," default value: ").concat(t));return n.number}(t,e.defaultValue):void 0;break}default:d.fieldKind="scalar",d.scalar=u,d.longAsString=h==nZ,d.getDefaultValue=()=>Dz(e,"defaultValue")?function(e,t){switch(e){case Iz.STRING:return t;case Iz.BYTES:{const n=function(e){const t=[],n={tail:e,c:"",next(){return 0!=this.tail.length&&(this.c=this.tail[0],this.tail=this.tail.substring(1),!0)},take(e){if(this.tail.length>=e){const t=this.tail.substring(0,e);return this.tail=this.tail.substring(e),t}return!1}};for(;n.next();)if("\\"===n.c){if(n.next())switch(n.c){case"\\":t.push(n.c.charCodeAt(0));break;case"b":t.push(8);break;case"f":t.push(12);break;case"n":t.push(10);break;case"r":t.push(13);break;case"t":t.push(9);break;case"v":t.push(11);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,8);if(Number.isNaN(r))return!1;t.push(r);break}case"x":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;t.push(r);break}case"u":{const e=n.c,i=n.take(4);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;const o=new Uint8Array(4);new DataView(o.buffer).setInt32(0,r,!0),t.push(o[0],o[1],o[2],o[3]);break}case"U":{const e=n.c,i=n.take(8);if(!1===i)return!1;const r=yz.uEnc(e+i),o=new Uint8Array(8),s=new DataView(o.buffer);s.setInt32(0,r.lo,!0),s.setInt32(4,r.hi,!0),t.push(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]);break}}}else t.push(n.c.charCodeAt(0));return new Uint8Array(t)}(t);if(!1===n)throw new Error("cannot parse ".concat(Iz[e]," default value: ").concat(t));return n}case Iz.INT64:case Iz.SFIXED64:case Iz.SINT64:return yz.parse(t);case Iz.UINT64:case Iz.FIXED64:return yz.uParse(t);case Iz.DOUBLE:case Iz.FLOAT:switch(t){case"inf":return Number.POSITIVE_INFINITY;case"-inf":return Number.NEGATIVE_INFINITY;case"nan":return Number.NaN;default:return parseFloat(t)}case Iz.BOOL:return"true"===t;case Iz.INT32:case Iz.UINT32:case Iz.SINT32:case Iz.FIXED32:case Iz.SFIXED32:return parseInt(t,10)}}(u,e.defaultValue):void 0}return d}function SZ(e){switch(e.syntax){case"":case"proto2":return Xz;case"proto3":return Jz;case"editions":if(e.edition in lZ)return e.edition;throw new Error("".concat(e.name,": unsupported edition"));default:throw new Error("".concat(e.name,': unsupported syntax "').concat(e.syntax,'"'))}}function TZ(e,t){return e.dependency.map((n=>{const i=t.getFile(n);if(!i)throw new Error("Cannot find ".concat(n,", imported by ").concat(e.name));return i}))}function RZ(e,t,n){let i;return i=t?"".concat(t.typeName,".").concat(e.name):n.proto.package.length>0?"".concat(n.proto.package,".").concat(e.name):"".concat(e.name),i}function vZ(e){return e.startsWith(".")?e.substring(1):e}function yZ(e,t){if(!Dz(e,"oneofIndex"))return;if(e.proto3Optional)return;const n=t[e.oneofIndex];return AZ(n,"invalid FieldDescriptorProto: oneof #".concat(e.oneofIndex," for field #").concat(e.number," not found")),n}function CZ(e,t,n,i){if(e.label==tZ)return sZ;if(e.label==eZ)return oZ;if(t||e.proto3Optional)return rZ;if(n)return rZ;const r=IZ("fieldPresence",{proto:e,parent:i});return r!=oZ||e.type!=qz&&e.type!=Zz?r:rZ}function bZ(e,t){return e.type==Zz||cZ==IZ("messageEncoding",{proto:e,parent:t})}function IZ(e,t){var n,i;const r=null===(n=t.proto.options)||void 0===n?void 0:n.features;if(r){const t=r[e];if(0!=t)return t}if("kind"in t){if("message"==t.kind)return IZ(e,null!==(i=t.parent)&&void 0!==i?i:t.file);const n=lZ[t.edition];if(!n)throw new Error("feature default for edition ".concat(t.edition," not found"));return n[e]}return IZ(e,t.parent)}function AZ(e,t){if(!e)throw new Error(t)}function wZ(e){var t,n,i,r,o,s,a,c;const d=Object.create({visibility:0});return Object.assign(d,{$typeName:"google.protobuf.DescriptorProto",name:e.name,field:null!==(n=null===(t=e.field)||void 0===t?void 0:t.map(OZ))&&void 0!==n?n:[],extension:[],nestedType:null!==(r=null===(i=e.nestedType)||void 0===i?void 0:i.map(wZ))&&void 0!==r?r:[],enumType:null!==(s=null===(o=e.enumType)||void 0===o?void 0:o.map(DZ))&&void 0!==s?s:[],extensionRange:null!==(c=null===(a=e.extensionRange)||void 0===a?void 0:a.map((e=>Object.assign({$typeName:"google.protobuf.DescriptorProto.ExtensionRange"},e))))&&void 0!==c?c:[],oneofDecl:[],reservedRange:[],reservedName:[]})}function OZ(e){const t=Object.create({label:1,typeName:"",extendee:"",defaultValue:"",oneofIndex:0,jsonName:"",proto3Optional:!1});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FieldDescriptorProto"},e),{options:e.options?NZ(e.options):void 0}))}function NZ(e){var t,n,i;const r=Object.create({ctype:0,packed:!1,jstype:0,lazy:!1,unverifiedLazy:!1,deprecated:!1,weak:!1,debugRedact:!1,retention:0});return Object.assign(r,Object.assign(Object.assign({$typeName:"google.protobuf.FieldOptions"},e),{targets:null!==(t=e.targets)&&void 0!==t?t:[],editionDefaults:null!==(i=null===(n=e.editionDefaults)||void 0===n?void 0:n.map((e=>Object.assign({$typeName:"google.protobuf.FieldOptions.EditionDefault"},e))))&&void 0!==i?i:[],uninterpretedOption:[]}))}function DZ(e){const t=Object.create({visibility:0});return Object.assign(t,{$typeName:"google.protobuf.EnumDescriptorProto",name:e.name,reservedName:[],reservedRange:[],value:e.value.map((e=>Object.assign({$typeName:"google.protobuf.EnumValueDescriptorProto"},e)))})}function PZ(e){const t=function(){if(!MZ){MZ=[];const e=UZ("std");for(let t=0;t<e.length;t++)MZ[e[t].charCodeAt(0)]=t;MZ["-".charCodeAt(0)]=e.indexOf("+"),MZ["_".charCodeAt(0)]=e.indexOf("/")}return MZ}();let n=3*e.length/4;"="==e[e.length-2]?n-=2:"="==e[e.length-1]&&(n-=1);let i,r=new Uint8Array(n),o=0,s=0,a=0;for(let n=0;n<e.length;n++){if(i=t[e.charCodeAt(n)],void 0===i)switch(e[n]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:a=i,s=1;break;case 1:r[o++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:r[o++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:r[o++]=(3&a)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string");return r.subarray(0,o)}let LZ,kZ,MZ;function UZ(e){return LZ||(LZ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),kZ=LZ.slice(0,-2).concat("-","_")),"url"==e?kZ:LZ}var VZ=_K,xZ=TypeError,FZ=uJ,BZ=String,GZ=function(e){if("Symbol"===FZ(e))throw TypeError("Cannot convert a Symbol value to a string");return BZ(e)},jZ=oY,WZ=AW,KZ=TY,YZ=JH,HZ=qH,XZ=function(e,t,n){var i=jZ(t);i in e?WZ.f(e,i,KZ(0,n)):e[i]=n},JZ=Array,zZ=Math.max,ZZ=function(e,t,n){for(var i=HZ(e),r=YZ(t,i),o=YZ(void 0===n?i:n,i),s=JZ(zZ(o-r,0)),a=0;r<o;r++,a++)XZ(s,a,e[r]);return s.length=a,s},qZ=Math.floor,QZ=function(e,t){var n=e.length,i=qZ(n/2);return n<8?$Z(e,t):eq(e,QZ(ZZ(e,0,i),t),QZ(ZZ(e,i),t),t)},$Z=function(e,t){for(var n,i,r=e.length,o=1;o<r;){for(i=o,n=e[o];i&&t(e[i-1],n)>0;)e[i]=e[--i];i!==o++&&(e[i]=n)}return e},eq=function(e,t,n,i){for(var r=t.length,o=n.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?i(t[s],n[a])<=0?t[s++]:n[a++]:s<r?t[s++]:n[a++];return e},tq=QZ,nq=Kj,iq=function(e,t){var n=[][e];return!!n&&nq((function(){n.call(null,t||function(){return 1},1)}))},rq=zW.match(/firefox\/(\d+)/i),oq=!!rq&&+rq[1],sq=/MSIE|Trident/.test(zW),aq=zW.match(/AppleWebKit\/(\d+)\./),cq=!!aq&&+aq[1],dq=LH,lq=Zj,uq=gK,hq=kK,pq=qH,_q=function(e,t){if(!delete e[t])throw xZ("Cannot delete property "+VZ(t)+" of "+VZ(e))},Eq=GZ,mq=Kj,fq=tq,gq=iq,Sq=oq,Tq=sq,Rq=nK,vq=cq,yq=[],Cq=lq(Jp(yq)),bq=lq(yq.push),Iq=mq((function(){Jp(yq).call(yq,void 0)})),Aq=mq((function(){Jp(yq).call(yq,null)})),wq=gq("sort"),Oq=!mq((function(){if(Rq)return Rq<70;if(!(Sq&&Sq>3)){if(Tq)return!0;if(vq)return vq<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)yq.push({k:t+i,v:n})}for(Jp(yq).call(yq,(function(e,t){return t.v-e.v})),i=0;i<yq.length;i++)t=yq[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));dq({target:"Array",proto:!0,forced:Iq||!Aq||!wq||!Oq},{sort:function(e){void 0!==e&&uq(e);var t=hq(this);if(Oq)return void 0===e?Cq(t):Cq(t,e);var n,i,r=[],o=pq(t);for(i=0;i<o;i++)i in t&&bq(r,t[i]);for(fq(r,function(e){return function(t,n){return void 0===n?-1:void 0===t?1:void 0!==e?+e(t,n)||0:Eq(t)>Eq(n)?1:-1}}(e)),n=pq(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)_q(t,i++);return t}});var Nq=Jp(nz("Array")),Dq=JW,Pq=Nq,Lq=Array.prototype,kq=Gj((function(e){var t=Jp(e);return e===Lq||Dq(Lq,e)&&t===Jp(Lq)?Pq:t})),Mq=CD(nz("Array")),Uq=uJ,Vq=VK,xq=JW,Fq=Mq,Bq=Array.prototype,Gq={DOMTokenList:!0,NodeList:!0},jq=Gj((function(e){var t=CD(e);return e===Bq||xq(Bq,e)&&t===CD(Bq)||Vq(Gq,Uq(e))?Fq:t}));function Wq(e,t){return!(null===e||"object"!=typeof e||!("$typeName"in e)||"string"!=typeof e.$typeName||void 0!==t&&t.typeName!==e.$typeName)}var Kq=Di(nX);LH({target:"Array",proto:!0,forced:Kj((function(){var e;return!Di(e=Array(1)).call(e)}))},{includes:function(e){return Kq(this,e,arguments.length>1?arguments[1]:void 0)}});var Yq=Di(nz("Array")),Hq=bW,Xq=eW,Jq=qK("match"),zq=TypeError,Zq=qK("match"),qq=LH,Qq=function(e){if(function(e){var t;return Hq(e)&&(void 0!==(t=e[Jq])?!!t:"RegExp"==Xq(e))}(e))throw zq("The method doesn't accept regular expressions");return e},$q=dW,eQ=GZ,tQ=Zj("".indexOf);qq({target:"String",proto:!0,forced:!function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[Zq]=!1,"/./"[e](t)}catch(e){}}return!1}("includes")},{includes:function(e){return!!~tQ(eQ($q(this)),eQ(Qq(e)),arguments.length>1?arguments[1]:void 0)}});var nQ=Di(nz("String")),iQ=JW,rQ=Yq,oQ=nQ,sQ=Array.prototype,aQ=String.prototype,cQ=Gj((function(e){var t=Di(e);return e===sQ||iQ(sQ,e)&&t===Di(sQ)?rQ:"string"==typeof e||e===aQ||iQ(aQ,e)&&t===Di(aQ)?oQ:t}));const dQ=["FieldValueInvalidError","FieldListRangeError","ForeignFieldError"];class lQ extends Error{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"FieldValueInvalidError";super(t),this.name=n,this.field=()=>e}}function uQ(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function hQ(e,t){var n,i,r,o;if(uQ(e)&&Oz in e&&"add"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.listKind==a.listKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function pQ(e,t){var n,i,r,o;if(uQ(e)&&Oz in e&&"has"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.mapKey===a.mapKey&&s.mapKind==a.mapKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function _Q(e,t){return uQ(e)&&Oz in e&&"desc"in e&&uQ(e.desc)&&"message"===e.desc.kind&&(void 0===t||e.desc.typeName==t.typeName)}const EQ=Symbol.for("@bufbuild/protobuf/text-encoding");function mQ(){if(null==hz[EQ]){const e=new hz.TextEncoder,t=new hz.TextDecoder;hz[EQ]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return hz[EQ]}var fQ;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(fQ||(fQ={}));const gQ=34028234663852886e22,SQ=-34028234663852886e22,TQ=4294967295,RQ=2147483647,vQ=-2147483648;class yQ{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mQ().encodeUtf8;this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(IQ(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return bQ(e),Rz(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){!function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>gQ||e<SQ))throw new Error("invalid float32: "+e)}(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){IQ(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){bQ(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return bQ(e),Rz(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=yz.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=yz.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=yz.enc(e);return _z(t.lo,t.hi,this.buf),this}sint64(e){const t=yz.enc(e),n=t.hi>>31;return _z(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){const t=yz.uEnc(e);return _z(t.lo,t.hi,this.buf),this}}class CQ{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mQ().decodeUtf8;this.decodeUtf8=t,this.varint64=pz,this.uint32=vz,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case fQ.Varint:for(;128&this.buf[this.pos++];);break;case fQ.Bit64:this.pos+=4;case fQ.Bit32:this.pos+=4;break;case fQ.LengthDelimited:let n=this.uint32();this.pos+=n;break;case fQ.StartGroup:for(;;){const[e,n]=this.tag();if(n===fQ.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return yz.dec(...this.varint64())}uint64(){return yz.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,yz.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return yz.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return yz.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}function bQ(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>RQ||e<vQ)throw new Error("invalid int32: "+e)}function IQ(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>TQ||e<0)throw new Error("invalid uint32: "+e)}function AQ(e,t){const n="list"==e.fieldKind?hQ(t,e):"map"==e.fieldKind?pQ(t,e):OQ(e,t);if(!0===n)return;let i;switch(e.fieldKind){case"list":i="expected ".concat(kQ(e),", got ").concat(PQ(t));break;case"map":i="expected ".concat(MQ(e),", got ").concat(PQ(t));break;default:i=DQ(e,t,n)}return new lQ(e,i)}function wQ(e,t,n){const i=OQ(e,n);if(!0!==i)return new lQ(e,"list item #".concat(t+1,": ").concat(DQ(e,n,i)))}function OQ(e,t){return void 0!==e.scalar?NQ(t,e.scalar):void 0!==e.enum?e.enum.open?Number.isInteger(t):lz(e.enum).some((e=>e.number===t)):_Q(t,e.message)}function NQ(e,t){switch(t){case Iz.DOUBLE:return"number"==typeof e;case Iz.FLOAT:return"number"==typeof e&&(!(!Number.isNaN(e)&&Number.isFinite(e))||!(e>gQ||e<SQ)||"".concat(e.toFixed()," out of range"));case Iz.INT32:case Iz.SFIXED32:case Iz.SINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>RQ||e<vQ)||"".concat(e.toFixed()," out of range"));case Iz.FIXED32:case Iz.UINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>TQ||e<0)||"".concat(e.toFixed()," out of range"));case Iz.BOOL:return"boolean"==typeof e;case Iz.STRING:return"string"==typeof e&&(mQ().checkUtf8(e)||"invalid UTF8");case Iz.BYTES:return e instanceof Uint8Array;case Iz.INT64:case Iz.SFIXED64:case Iz.SINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return yz.parse(e),!0}catch(t){return"".concat(e," out of range")}return!1;case Iz.FIXED64:case Iz.UINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return yz.uParse(e),!0}catch(t){return"".concat(e," out of range")}return!1}}function DQ(e,t,n){return n="string"==typeof n?": ".concat(n):", got ".concat(PQ(t)),void 0!==e.scalar?"expected ".concat(function(e){switch(e){case Iz.STRING:return"string";case Iz.BOOL:return"boolean";case Iz.INT64:case Iz.SINT64:case Iz.SFIXED64:return"bigint (int64)";case Iz.UINT64:case Iz.FIXED64:return"bigint (uint64)";case Iz.BYTES:return"Uint8Array";case Iz.DOUBLE:return"number (float64)";case Iz.FLOAT:return"number (float32)";case Iz.FIXED32:case Iz.UINT32:return"number (uint32)";case Iz.INT32:case Iz.SFIXED32:case Iz.SINT32:return"number (int32)"}}(e.scalar))+n:void 0!==e.enum?"expected ".concat(e.enum.toString())+n:"expected ".concat(LQ(e.message))+n}function PQ(e){switch(typeof e){case"object":return null===e?"null":e instanceof Uint8Array?"Uint8Array(".concat(e.length,")"):Array.isArray(e)?"Array(".concat(e.length,")"):hQ(e)?kQ(e.field()):pQ(e)?MQ(e.field()):_Q(e)?LQ(e.desc):Wq(e)?"message ".concat(e.$typeName):"object";case"string":return e.length>30?"string":'"'.concat(e.split('"').join('\\"'),'"');case"boolean":case"number":return String(e);case"bigint":return String(e)+"n";default:return typeof e}}function LQ(e){return"ReflectMessage (".concat(e.typeName,")")}function kQ(e){switch(e.listKind){case"message":return"ReflectList (".concat(e.message.toString(),")");case"enum":return"ReflectList (".concat(e.enum.toString(),")");case"scalar":return"ReflectList (".concat(Iz[e.scalar],")")}}function MQ(e){switch(e.mapKind){case"message":return"ReflectMap (".concat(Iz[e.mapKey],", ").concat(e.message.toString(),")");case"enum":return"ReflectMap (".concat(Iz[e.mapKey],", ").concat(e.enum.toString(),")");case"scalar":return"ReflectMap (".concat(Iz[e.mapKey],", ").concat(Iz[e.scalar],")")}}function UQ(e){const t=e.fields[0];return VQ(e.typeName)&&void 0!==t&&"scalar"==t.fieldKind&&"value"==t.name&&1==t.number}function VQ(e){var t;return e.startsWith("google.protobuf.")&&cQ(t=["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"]).call(t,e.substring(16))}const xQ=999,FQ=998,BQ=2;function GQ(e,t){if(Wq(t,e))return t;const n=function(e){let t;if(function(e){switch(e.file.edition){case xQ:return!1;case FQ:return!0;default:return e.fields.some((e=>e.presence!=BQ&&"message"!=e.fieldKind&&!e.oneof))}}(e)){const n=zQ.get(e);let i,r;if(n)({prototype:i,members:r}=n);else{i={},r=new Set;for(const t of e.members)"oneof"!=t.kind&&("scalar"!=t.fieldKind&&"enum"!=t.fieldKind||t.presence!=BQ&&(r.add(t),i[t.localName]=ZQ(t)));zQ.set(e,{prototype:i,members:r})}t=Object.create(i),t.$typeName=e.typeName;for(const n of e.members)if(!r.has(n)){if("field"==n.kind){if("message"==n.fieldKind)continue;if(("scalar"==n.fieldKind||"enum"==n.fieldKind)&&n.presence!=BQ)continue}t[n.localName]=ZQ(n)}}else{t={$typeName:e.typeName};for(const n of e.members)"oneof"!=n.kind&&n.presence!=BQ||(t[n.localName]=ZQ(n))}return t}(e);return void 0!==t&&function(e,t,n){for(const i of e.members){let e,r=n[i.localName];if(null!=r){if("oneof"==i.kind){const t=Nz(n,i);if(!t)continue;e=t,r=Pz(n,t)}else e=i;switch(e.fieldKind){case"message":r=YQ(e,r);break;case"scalar":r=jQ(e,r);break;case"list":r=KQ(e,r);break;case"map":r=WQ(e,r)}Lz(t,e,r)}}}(e,n,t),n}function jQ(e,t){return e.scalar==Iz.BYTES?HQ(t):t}function WQ(e,t){if(uQ(t)){if(e.scalar==Iz.BYTES)return XQ(t,HQ);if("message"==e.mapKind)return XQ(t,(t=>YQ(e,t)))}return t}function KQ(e,t){if(Array.isArray(t)){if(e.scalar==Iz.BYTES)return t.map(HQ);if("message"==e.listKind)return t.map((t=>YQ(e,t)))}return t}function YQ(e,t){if("message"==e.fieldKind&&!e.oneof&&UQ(e.message))return jQ(e.message.fields[0],t);if(uQ(t)){if("google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!==e.parent.typeName)return t;if(!Wq(t,e.message))return GQ(e.message,t)}return t}function HQ(e){return Array.isArray(e)?new Uint8Array(e):e}function XQ(e,t){const n={};for(const i of Object.entries(e))n[i[0]]=t(i[1]);return n}const JQ=Symbol(),zQ=new WeakMap;function ZQ(e){if("oneof"==e.kind)return{case:void 0};if("list"==e.fieldKind)return[];if("map"==e.fieldKind)return{};if("message"==e.fieldKind)return JQ;const t=e.getDefaultValue();return void 0!==t?"scalar"==e.fieldKind&&e.longAsString?t.toString():t:"scalar"==e.fieldKind?Az(e.scalar,e.longAsString):lz(e.enum)[0].number}function qQ(e,t){return new $Q(e,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2])}const QQ=new WeakMap;class $Q{get sortedFields(){var e;const t=QQ.get(this.desc);if(t)return t;const n=kq(e=this.desc.fields.concat()).call(e,((e,t)=>e.number-t.number));return QQ.set(this.desc,n),n}constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.lists=new Map,this.maps=new Map,this.check=n,this.desc=e,this.message=this[Oz]=null!=t?t:GQ(e),this.fields=e.fields,this.oneofs=e.oneofs,this.members=e.members}findNumber(e){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map((e=>[e.number,e])))),this._fieldsByNumber.get(e)}oneofCase(e){return e$(this.message,e),Nz(this.message,e)}isSet(e){return e$(this.message,e),function(e,t){const n=t.localName;if(t.oneof)return e[t.oneof.localName].case===n;if(t.presence!=wz)return void 0!==e[n]&&Object.prototype.hasOwnProperty.call(e,n);switch(t.fieldKind){case"list":return e[n].length>0;case"map":return Object.keys(e[n]).length>0;case"scalar":return!function(e,t){switch(e){case Iz.BOOL:return!1===t;case Iz.STRING:return""===t;case Iz.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(t.scalar,e[n]);case"enum":return e[n]!==lz(t.enum)[0].number}throw new Error("message field with implicit presence")}(this.message,e)}clear(e){e$(this.message,e),function(e,t){const n=t.localName;if(t.oneof){const i=t.oneof.localName;e[i].case===n&&(e[i]={case:void 0})}else if(t.presence!=wz)delete e[n];else switch(t.fieldKind){case"map":e[n]={};break;case"list":e[n]=[];break;case"enum":e[n]=lz(t.enum)[0].number;break;case"scalar":e[n]=Az(t.scalar,t.longAsString)}}(this.message,e)}get(e){e$(this.message,e);const t=Pz(this.message,e);switch(e.fieldKind){case"list":let n=this.lists.get(e);return n&&n[Oz]===t||this.lists.set(e,n=new t$(e,t,this.check)),n;case"map":let i=this.maps.get(e);return i&&i[Oz]===t||this.maps.set(e,i=new n$(e,t,this.check)),i;case"message":return r$(e,t,this.check);case"scalar":return void 0===t?Az(e.scalar,!1):l$(e,t);case"enum":return null!=t?t:lz(e.enum)[0].number}}set(e,t){if(e$(this.message,e),this.check){const n=AQ(e,t);if(n)throw n}let n;n="message"==e.fieldKind?i$(e,t):pQ(t)||hQ(t)?t[Oz]:u$(e,t),Lz(this.message,e,n)}getUnknown(){return this.message.$unknown}setUnknown(e){this.message.$unknown=e}}function e$(e,t){if(t.parent.typeName!==e.$typeName)throw new lQ(t,"cannot use ".concat(t.toString()," with message ").concat(e.$typeName),"ForeignFieldError")}class t${field(){return this._field}get size(){return this._arr.length}constructor(e,t,n){this._field=e,this._arr=this[Oz]=t,this.check=n}get(e){const t=this._arr[e];return void 0===t?void 0:s$(this._field,t,this.check)}set(e,t){if(e<0||e>=this._arr.length)throw new lQ(this._field,"list item #".concat(e+1,": out of range"));if(this.check){const n=wQ(this._field,e,t);if(n)throw n}this._arr[e]=o$(this._field,t)}add(e){if(this.check){const t=wQ(this._field,this._arr.length,e);if(t)throw t}this._arr.push(o$(this._field,e))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return lz(this).call(this)}keys(){var e;return jq(e=this._arr).call(e)}*values(){for(const e of this._arr)yield s$(this._field,e,this.check)}*entries(){for(let e=0;e<this._arr.length;e++)yield[e,s$(this._field,this._arr[e],this.check)]}}class n${constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.obj=this[Oz]=null!=t?t:{},this.check=n,this._field=e}field(){return this._field}set(e,t){if(this.check){const n=function(e,t,n){const i=NQ(t,e.mapKey);if(!0!==i)return new lQ(e,"invalid map key: ".concat(DQ({scalar:e.mapKey},t,i)));const r=OQ(e,n);return!0!==r?new lQ(e,"map entry ".concat(PQ(t),": ").concat(DQ(e,n,r))):void 0}(this._field,e,t);if(n)throw n}return this.obj[c$(e)]=function(e,t){return"message"==e.mapKind?i$(e,t):u$(e,t)}(this._field,t),this}delete(e){const t=c$(e),n=Object.prototype.hasOwnProperty.call(this.obj,t);return n&&delete this.obj[t],n}clear(){for(const e of Object.keys(this.obj))delete this.obj[e]}get(e){let t=this.obj[c$(e)];return void 0!==t&&(t=a$(this._field,t,this.check)),t}has(e){return Object.prototype.hasOwnProperty.call(this.obj,c$(e))}*keys(){for(const e of Object.keys(this.obj))yield d$(e,this._field.mapKey)}*entries(){for(const e of Object.entries(this.obj))yield[d$(e[0],this._field.mapKey),a$(this._field,e[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(const e of Object.values(this.obj))yield a$(this._field,e,this.check)}forEach(e,t){for(const n of this.entries())e.call(t,n[1],n[0],this)}}function i$(e,t){return _Q(t)?VQ(t.message.$typeName)&&!e.oneof&&"message"==e.fieldKind?t.message.value:"google.protobuf.Struct"==t.desc.typeName&&"google.protobuf.Value"!=e.parent.typeName?p$(t.message):t.message:t}function r$(e,t,n){return void 0!==t&&(UQ(e.message)&&!e.oneof&&"message"==e.fieldKind?t={$typeName:e.message.typeName,value:l$(e.message.fields[0],t)}:"google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!=e.parent.typeName&&uQ(t)&&(t=h$(t))),new $Q(e.message,t,n)}function o$(e,t){return"message"==e.listKind?i$(e,t):u$(e,t)}function s$(e,t,n){return"message"==e.listKind?r$(e,t,n):l$(e,t)}function a$(e,t,n){return"message"==e.mapKind?r$(e,t,n):t}function c$(e){return"string"==typeof e||"number"==typeof e?e:String(e)}function d$(e,t){switch(t){case Iz.STRING:return e;case Iz.INT32:case Iz.FIXED32:case Iz.UINT32:case Iz.SFIXED32:case Iz.SINT32:{const t=Number.parseInt(e);if(Number.isFinite(t))return t;break}case Iz.BOOL:switch(e){case"true":return!0;case"false":return!1}break;case Iz.UINT64:case Iz.FIXED64:try{return yz.uParse(e)}catch(e){}break;default:try{return yz.parse(e)}catch(e){}}return e}function l$(e,t){switch(e.scalar){case Iz.INT64:case Iz.SFIXED64:case Iz.SINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=yz.parse(t));break;case Iz.FIXED64:case Iz.UINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=yz.uParse(t))}return t}function u$(e,t){switch(e.scalar){case Iz.INT64:case Iz.SFIXED64:case Iz.SINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=yz.parse(t));break;case Iz.FIXED64:case Iz.UINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=yz.uParse(t))}return t}function h$(e){const t={$typeName:"google.protobuf.Struct",fields:{}};if(uQ(e))for(const[n,i]of Object.entries(e))t.fields[n]=E$(i);return t}function p$(e){const t={};for(const[n,i]of Object.entries(e.fields))t[n]=_$(i);return t}function _$(e){switch(e.kind.case){case"structValue":return p$(e.kind.value);case"listValue":return lz(e.kind.value).map(_$);case"nullValue":case void 0:return null;default:return e.kind.value}}function E$(e){const t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof e){case"number":t.kind={case:"numberValue",value:e};break;case"string":t.kind={case:"stringValue",value:e};break;case"boolean":t.kind={case:"boolValue",value:e};break;case"object":if(null===e){const e=0;t.kind={case:"nullValue",value:e}}else if(Array.isArray(e)){const n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(e))for(const t of e)lz(n).push(E$(t));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:h$(e)}}return t}const m$=3,f$={writeUnknownFields:!0};function g$(e,t,n){return S$(new yQ,function(e){return e?Object.assign(Object.assign({},f$),e):f$}(n),qQ(e,t)).finish()}function S$(e,t,n){var i;for(const i of n.sortedFields)if(n.isSet(i))T$(e,t,n,i);else if(i.presence==m$)throw new Error("cannot encode ".concat(i," to binary: required field not set"));if(t.writeUnknownFields)for(const{no:t,wireType:r,data:o}of null!==(i=n.getUnknown())&&void 0!==i?i:[])e.tag(t,r).raw(o);return e}function T$(e,t,n,i){var r;switch(i.fieldKind){case"scalar":case"enum":R$(e,n.desc.typeName,i.name,null!==(r=i.scalar)&&void 0!==r?r:Iz.INT32,i.number,n.get(i));break;case"list":!function(e,t,n,i){var r;if("message"==n.listKind){for(const r of i)v$(e,t,n,r);return}const o=null!==(r=n.scalar)&&void 0!==r?r:Iz.INT32;if(n.packed){if(!i.size)return;e.tag(n.number,fQ.LengthDelimited).fork();for(const t of i)C$(e,n.parent.typeName,n.name,o,t);e.join()}else for(const t of i)R$(e,n.parent.typeName,n.name,o,n.number,t)}(e,t,i,n.get(i));break;case"message":v$(e,t,i,n.get(i));break;case"map":for(const[r,o]of n.get(i))y$(e,t,i,r,o)}}function R$(e,t,n,i,r,o){C$(e.tag(r,function(e){switch(e){case Iz.BYTES:case Iz.STRING:return fQ.LengthDelimited;case Iz.DOUBLE:case Iz.FIXED64:case Iz.SFIXED64:return fQ.Bit64;case Iz.FIXED32:case Iz.SFIXED32:case Iz.FLOAT:return fQ.Bit32;default:return fQ.Varint}}(i)),t,n,i,o)}function v$(e,t,n,i){n.delimitedEncoding?S$(e.tag(n.number,fQ.StartGroup),t,i).tag(n.number,fQ.EndGroup):S$(e.tag(n.number,fQ.LengthDelimited).fork(),t,i).join()}function y$(e,t,n,i,r){var o;switch(e.tag(n.number,fQ.LengthDelimited).fork(),R$(e,n.parent.typeName,n.name,n.mapKey,1,i),n.mapKind){case"scalar":case"enum":R$(e,n.parent.typeName,n.name,null!==(o=n.scalar)&&void 0!==o?o:Iz.INT32,2,r);break;case"message":S$(e.tag(2,fQ.LengthDelimited).fork(),t,r).join()}e.join()}function C$(e,t,n,i,r){try{switch(i){case Iz.STRING:e.string(r);break;case Iz.BOOL:e.bool(r);break;case Iz.DOUBLE:e.double(r);break;case Iz.FLOAT:e.float(r);break;case Iz.INT32:e.int32(r);break;case Iz.INT64:e.int64(r);break;case Iz.UINT64:e.uint64(r);break;case Iz.FIXED64:e.fixed64(r);break;case Iz.BYTES:e.bytes(r);break;case Iz.FIXED32:e.fixed32(r);break;case Iz.SFIXED32:e.sfixed32(r);break;case Iz.SFIXED64:e.sfixed64(r);break;case Iz.SINT64:e.sint64(r);break;case Iz.UINT32:e.uint32(r);break;case Iz.SINT32:e.sint32(r)}}catch(e){if(e instanceof Error)throw new Error("cannot encode field ".concat(t,".").concat(n," to binary: ").concat(e.message));throw e}}var b$=gK,I$=kK,A$=oW,w$=qH,O$=TypeError,N$=function(e){return function(t,n,i,r){b$(n);var o=I$(t),s=A$(o),a=w$(o),c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw O$("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},D$={left:N$(!1),right:N$(!0)},P$="undefined"!=typeof process&&"process"==eW(process),L$=D$.left;LH({target:"Array",proto:!0,forced:!P$&&nK>79&&nK<83||!iq("reduce")},{reduce:function(e){var t=arguments.length;return L$(this,e,t,t>1?arguments[1]:void 0)}});var k$=zi(nz("Array")),M$=JW,U$=k$,V$=Array.prototype,x$=Gj((function(e){var t=zi(e);return e===V$||M$(V$,e)&&t===zi(V$)?U$:t}));function F$(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return x$(i).call(i,((e,t)=>e.nestedMessages[t]),e.messages[t])}const B$=F$(function(e){const t=function(e){const t=Object.create({syntax:"",edition:0});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FileDescriptorProto",dependency:[],publicDependency:[],weakDependency:[],optionDependency:[],service:[],extension:[]},e),{messageType:e.messageType.map(wZ),enumType:e.enumType.map(DZ)}))}(e);return t.messageType.forEach(kz),Hz(t,(()=>{})).getFile(t.name)}({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false"},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_UNSTABLE",number:9999},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]}),1);var G$,j$,W$,K$,Y$,H$,X$,J$,z$,Z$,q$,Q$,$$,e0,t0,n0,i0,r0,o0,s0;!function(e){e[e.DECLARATION=0]="DECLARATION",e[e.UNVERIFIED=1]="UNVERIFIED"}(G$||(G$={})),function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.GROUP=10]="GROUP",e[e.MESSAGE=11]="MESSAGE",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.ENUM=14]="ENUM",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(j$||(j$={})),function(e){e[e.OPTIONAL=1]="OPTIONAL",e[e.REPEATED=3]="REPEATED",e[e.REQUIRED=2]="REQUIRED"}(W$||(W$={})),function(e){e[e.SPEED=1]="SPEED",e[e.CODE_SIZE=2]="CODE_SIZE",e[e.LITE_RUNTIME=3]="LITE_RUNTIME"}(K$||(K$={})),function(e){e[e.STRING=0]="STRING",e[e.CORD=1]="CORD",e[e.STRING_PIECE=2]="STRING_PIECE"}(Y$||(Y$={})),function(e){e[e.JS_NORMAL=0]="JS_NORMAL",e[e.JS_STRING=1]="JS_STRING",e[e.JS_NUMBER=2]="JS_NUMBER"}(H$||(H$={})),function(e){e[e.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",e[e.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",e[e.RETENTION_SOURCE=2]="RETENTION_SOURCE"}(X$||(X$={})),function(e){e[e.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",e[e.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",e[e.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",e[e.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",e[e.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",e[e.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",e[e.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",e[e.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",e[e.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",e[e.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"}(J$||(J$={})),function(e){e[e.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",e[e.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",e[e.IDEMPOTENT=2]="IDEMPOTENT"}(z$||(z$={})),function(e){e[e.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",e[e.EXPORT_ALL=1]="EXPORT_ALL",e[e.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",e[e.LOCAL_ALL=3]="LOCAL_ALL",e[e.STRICT=4]="STRICT"}(Z$||(Z$={})),function(e){e[e.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",e[e.EXPLICIT=1]="EXPLICIT",e[e.IMPLICIT=2]="IMPLICIT",e[e.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"}(q$||(q$={})),function(e){e[e.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",e[e.OPEN=1]="OPEN",e[e.CLOSED=2]="CLOSED"}(Q$||(Q$={})),function(e){e[e.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",e[e.PACKED=1]="PACKED",e[e.EXPANDED=2]="EXPANDED"}($$||($$={})),function(e){e[e.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",e[e.VERIFY=2]="VERIFY",e[e.NONE=3]="NONE"}(e0||(e0={})),function(e){e[e.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",e[e.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",e[e.DELIMITED=2]="DELIMITED"}(t0||(t0={})),function(e){e[e.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",e[e.ALLOW=1]="ALLOW",e[e.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"}(n0||(n0={})),function(e){e[e.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",e[e.STYLE2024=1]="STYLE2024",e[e.STYLE_LEGACY=2]="STYLE_LEGACY"}(i0||(i0={})),function(e){e[e.NONE=0]="NONE",e[e.SET=1]="SET",e[e.ALIAS=2]="ALIAS"}(r0||(r0={})),function(e){e[e.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",e[e.EDITION_LEGACY=900]="EDITION_LEGACY",e[e.EDITION_PROTO2=998]="EDITION_PROTO2",e[e.EDITION_PROTO3=999]="EDITION_PROTO3",e[e.EDITION_2023=1e3]="EDITION_2023",e[e.EDITION_2024=1001]="EDITION_2024",e[e.EDITION_UNSTABLE=9999]="EDITION_UNSTABLE",e[e.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",e[e.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",e[e.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",e[e.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",e[e.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",e[e.EDITION_MAX=2147483647]="EDITION_MAX"}(o0||(o0={})),function(e){e[e.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",e[e.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",e[e.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"}(s0||(s0={}));const a0={readUnknownFields:!0};function c0(e,t,n){const i=qQ(e,void 0,!1);return d0(i,new CQ(t),function(e){return e?Object.assign(Object.assign({},a0),e):a0}(n),!1,t.byteLength),i.message}function d0(e,t,n,i,r){var o;const s=i?t.len:t.pos+r;let a,c;const d=null!==(o=e.getUnknown())&&void 0!==o?o:[];for(;t.pos<s&&([a,c]=t.tag(),!i||c!=fQ.EndGroup);){const i=e.findNumber(a);if(i)l0(e,t,i,c,n);else{const e=t.skip(c,a);n.readUnknownFields&&d.push({no:a,wireType:c,data:e})}}if(i&&(c!=fQ.EndGroup||a!==r))throw new Error("invalid end group tag");d.length>0&&e.setUnknown(d)}function l0(e,t,n,i,r){var o;switch(n.fieldKind){case"scalar":e.set(n,h0(t,n.scalar));break;case"enum":const s=h0(t,Iz.INT32);if(n.enum.open)e.set(n,s);else if(lz(n.enum).some((e=>e.number===s)))e.set(n,s);else if(r.readUnknownFields){const t=[];Rz(s,t);const r=null!==(o=e.getUnknown())&&void 0!==o?o:[];r.push({no:n.number,wireType:i,data:new Uint8Array(t)}),e.setUnknown(r)}break;case"message":e.set(n,u0(t,r,n,e.get(n)));break;case"list":!function(e,t,n,i){var r;const o=n.field();if("message"===o.listKind)return void n.add(u0(e,i,o));const s=null!==(r=o.scalar)&&void 0!==r?r:Iz.INT32;if(!(t==fQ.LengthDelimited&&s!=Iz.STRING&&s!=Iz.BYTES))return void n.add(h0(e,s));const a=e.uint32()+e.pos;for(;e.pos<a;)n.add(h0(e,s))}(t,i,e.get(n),r);break;case"map":!function(e,t,n){const i=t.field();let r,o;const s=e.uint32(),a=e.pos+s;for(;e.pos<a;){const[t]=e.tag();switch(t){case 1:r=h0(e,i.mapKey);break;case 2:switch(i.mapKind){case"scalar":o=h0(e,i.scalar);break;case"enum":o=e.int32();break;case"message":o=u0(e,n,i)}}}if(void 0===r&&(r=Az(i.mapKey,!1)),void 0===o)switch(i.mapKind){case"scalar":o=Az(i.scalar,!1);break;case"enum":o=lz(i.enum)[0].number;break;case"message":o=qQ(i.message,void 0,!1)}t.set(r,o)}(t,e.get(n),r)}}function u0(e,t,n,i){const r=n.delimitedEncoding,o=null!=i?i:qQ(n.message,void 0,!1);return d0(o,e,t,r,r?n.number:e.uint32()),o}function h0(e,t){switch(t){case Iz.STRING:return e.string();case Iz.BOOL:return e.bool();case Iz.DOUBLE:return e.double();case Iz.FLOAT:return e.float();case Iz.INT32:return e.int32();case Iz.INT64:return e.int64();case Iz.UINT64:return e.uint64();case Iz.FIXED64:return e.fixed64();case Iz.BYTES:return e.bytes();case Iz.FIXED32:return e.fixed32();case Iz.SFIXED32:return e.sfixed32();case Iz.SFIXED64:return e.sfixed64();case Iz.SINT64:return e.sint64();case Iz.UINT32:return e.uint32();case Iz.SINT32:return e.sint32()}}function p0(e,t){var n;const i=c0(B$,PZ(e));return i.messageType.forEach(kz),i.dependency=null!==(n=null==t?void 0:t.map((e=>e.proto.name)))&&void 0!==n?n:[],Hz(i,(e=>null==t?void 0:t.find((t=>t.proto.name===e)))).getFile(i.name)}const _0=F$(p0("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),0);function E0(e){const t=e.lastIndexOf("/"),n=t>=0?e.substring(t+1):e;if(!n.length)throw new Error("invalid type url: ".concat(e));return n}const m0=p0("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),f0=F$(m0,0),g0=F$(m0,1),S0=F$(m0,2);var T0;!function(e){e[e.NULL_VALUE=0]="NULL_VALUE"}(T0||(T0={}));const R0=p0("CgpvcnRjLnByb3RvEgtpby5hZ29yYS5wYiKoAQoET1JUQxILCgNpY2UYASADKAkSJQoEZHRscxgCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSIQoEc2VuZBgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAQgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgFIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCLQAQoGUnRwQ2FwEjMKDGF1ZGlvX2NvZGVjcxgBIAMoCzIdLmlvLmFnb3JhLnBiLlBheWxvYWRBdHRyaWJ1dGUSMwoMdmlkZW9fY29kZWNzGAIgAygLMh0uaW8uYWdvcmEucGIuUGF5bG9hZEF0dHJpYnV0ZRItChBhdWRpb19leHRlbnNpb25zGAMgAygLMhMuaW8uYWdvcmEucGIuRXh0bWFwEi0KEHZpZGVvX2V4dGVuc2lvbnMYBCADKAsyEy5pby5hZ29yYS5wYi5FeHRtYXAiqQEKBkV4dG1hcBINCgVlbnRyeRgBIAEoDRIuCg5leHRlbnNpb25fbmFtZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRIWCglkaXJlY3Rpb24YAyABKAlIAIgBARIhChRleHRlbnNpb25fYXR0cmlidXRlcxgEIAEoCUgBiAEBQgwKCl9kaXJlY3Rpb25CFwoVX2V4dGVuc2lvbl9hdHRyaWJ1dGVzIp4BChBQYXlsb2FkQXR0cmlidXRlEiQKB3J0cF9tYXAYASABKAsyEy5pby5hZ29yYS5wYi5SdHBNYXASHwoEZm10cBgCIAEoCzIRLmlvLmFnb3JhLnBiLkZtdHASLQoOcnRjcF9mZWVkYmFja3MYAyADKAsyFS5pby5hZ29yYS5wYi5GZWVkYmFjaxIUCgxwYXlsb2FkX3R5cGUYBCABKA0i4gEKBlJ0cE1hcBIfChJlbnVtX2VuY29kaW5nX25hbWUYASABKA1IAIgBARIhChRzdHJpbmdfZW5jb2RpbmdfbmFtZRgCIAEoCUgBiAEBEioKCmNsb2NrX3JhdGUYAyABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSIAoTZW5jb2RpbmdfcGFyYW1ldGVycxgEIAEoDUgCiAEBQhUKE19lbnVtX2VuY29kaW5nX25hbWVCFwoVX3N0cmluZ19lbmNvZGluZ19uYW1lQhYKFF9lbmNvZGluZ19wYXJhbWV0ZXJzIqoCCgRGbXRwEj4KD2VudW1fcGFyYW1ldGVycxgBIAMoCzIlLmlvLmFnb3JhLnBiLkZtdHAuRW51bVBhcmFtZXRlcnNFbnRyeRJCChFzdHJpbmdfcGFyYW1ldGVycxgCIAMoCzInLmlvLmFnb3JhLnBiLkZtdHAuU3RyaW5nUGFyYW1ldGVyc0VudHJ5Gk0KE0VudW1QYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgNEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ARpPChVTdHJpbmdQYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgJEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ASLMAQoIRmVlZGJhY2sSFgoJZW51bV90eXBlGAEgASgNSACIAQESGAoLc3RyaW5nX3R5cGUYAiABKAlIAYgBARIWCglwYXJhbWV0ZXIYAyABKAlIAogBARIXCgphZGRpdGlvbmFsGAQgASgJSAOIAQESFQoIaW50ZXJ2YWwYBSABKAlIBIgBAUIMCgpfZW51bV90eXBlQg4KDF9zdHJpbmdfdHlwZUIMCgpfcGFyYW1ldGVyQg0KC19hZGRpdGlvbmFsQgsKCV9pbnRlcnZhbCKBAQoRUnRwQ2FwQmVmb3JlTWVyZ2USIQoEc2VuZBgBIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAIgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCKrEQoPT3J0Y05lZ290aWF0aW9uEk4KE2luX291dF9hdWRpb19wdF9tYXAYASADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uSW5PdXRBdWRpb1B0TWFwRW50cnkSTgoTaW5fb3V0X3ZpZGVvX3B0X21hcBgCIAMoCzIxLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvUHRNYXBFbnRyeRJOChNvdXRfaW5fYXVkaW9fcHRfbWFwGAMgAygLMjEuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluQXVkaW9QdE1hcEVudHJ5Ek4KE291dF9pbl92aWRlb19wdF9tYXAYBCADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5WaWRlb1B0TWFwRW50cnkSYwoeaW5fb3V0X2F1ZGlvX2hlYWRlcl9leHRlbnNfbWFwGAUgAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLkluT3V0QXVkaW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJjCh5vdXRfaW5fYXVkaW9faGVhZGVyX2V4dGVuc19tYXAYBiADKAsyOy5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5BdWRpb0hlYWRlckV4dGVuc01hcEVudHJ5EmMKHmluX291dF92aWRlb19oZWFkZXJfZXh0ZW5zX21hcBgHIAMoCzI7LmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSYwoeb3V0X2luX3ZpZGVvX2hlYWRlcl9leHRlbnNfbWFwGAggAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluVmlkZW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJQChRydHBfcnR4X2F1ZGlvX3B0X21hcBgJIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHBSdHhBdWRpb1B0TWFwRW50cnkSUAoUcnRwX3J0eF92aWRlb19wdF9tYXAYCiADKAsyMi5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUnR4VmlkZW9QdE1hcEVudHJ5ElAKFHJ0eF9ydHBfYXVkaW9fcHRfbWFwGAsgAygLMjIuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLlJ0eFJ0cEF1ZGlvUHRNYXBFbnRyeRJQChRydHhfcnRwX3ZpZGVvX3B0X21hcBgMIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHhSdHBWaWRlb1B0TWFwRW50cnkSRQoOcnRwX3JlZF9wdF9tYXAYDSADKAsyLS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUmVkUHRNYXBFbnRyeRJFCg5yZWRfcnRwX3B0X21hcBgOIAMoCzItLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SZWRSdHBQdE1hcEVudHJ5Eg8KB2NmZ19ydHgYDyABKAgSFQoNaGFzX2F1ZGlvX3J0eBgQIAEoCBIVCg1oYXNfdmlkZW9fcnR4GBEgASgIEhAKCGNmZ19ycnRyGBIgASgIEhYKDmhhc192aWRlb19ycnRyGBMgASgIEhYKDmhhc19hdWRpb19ycnRyGBQgASgIEg8KB2NmZ19yZWQYFSABKAgSFQoNaGFzX2F1ZGlvX3JlZBgWIAEoCBIRCglpbl9yZWRfcHQYFyADKA0aNgoUSW5PdXRBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2ChRJbk91dFZpZGVvUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBGjYKFE91dEluQXVkaW9QdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUT3V0SW5WaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dEF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJbkF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJblZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARoyChBSdHBSZWRQdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaMgoQUmVkUnRwUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBKtACChJWaWRlb0V4dGVuc2lvbk5hbWUSGQoVVklERU9fRVhUX0hEUl9UT0ZGU0VUEAASGwoXVklERU9fRVhUX0FCU19TRU5EX1RJTUUQARIZChVWSURFT19FWFRfT1JJRU5UQVRJT04QAhISCg5WSURFT19FWFRfVFdDQxADEhsKF1ZJREVPX0VYVF9QTEFZT1VUX0RFTEFZEAQSGgoWVklERU9fRVhUX0NPTlRFTlRfVFlQRRAFEhoKFlZJREVPX0VYVF9WSURFT19USU1JTkcQBhIZChVWSURFT19FWFRfQ09MT1JfU1BBQ0UQBxIWChJWSURFT19FWFRfU0RFU19NSUQQCBIgChxWSURFT19FWFRfU0RFU19SVFBfU1RSRUFNX0lEEAkSKQolVklERU9fRVhUX1NERURfUkVQQUlSRURfUlRQX1NUUkVBTV9JRBAKKsQBChJBdWRpb0V4dGVuc2lvbk5hbWUSGQoVQVVESU9fRVhUX0FVRElPX0xFVkVMEAASGwoXQVVESU9fRVhUX0FCU19TRU5EX1RJTUUQARISCg5BVURJT19FWFRfVFdDQxACEhYKEkFVRElPX0VYVF9TREVTX01JRBADEiAKHEFVRElPX0VYVF9TREVTX1JUUF9TVFJFQU1fSUQQBBIoCiRBVURJT19FWFRfU0RTX1JFUEFJUkVEX1JUUF9TVFJFQU1fSUQQBSqBAwoMRW5jb2RpbmdOYW1lEh0KGUVOQ09ESU5HX05BTUVfVU5TUEVDSUZJRUQQABIVChFFTkNPRElOR19OQU1FX1ZQOBABEhUKEUVOQ09ESU5HX05BTUVfVlA5EAISFgoSRU5DT0RJTkdfTkFNRV9IMjY0EAMSFgoSRU5DT0RJTkdfTkFNRV9IMjY1EAQSFQoRRU5DT0RJTkdfTkFNRV9BVjEQBRIWChJFTkNPRElOR19OQU1FX0c3MTEQBhIWChJFTkNPRElOR19OQU1FX0c3MjIQBxIWChJFTkNPRElOR19OQU1FX09QVVMQCBIWChJFTkNPRElOR19OQU1FX1BDTVUQCRIWChJFTkNPRElOR19OQU1FX1BDTUEQChIUChBFTkNPRElOR19OQU1FX0NOEAsSIQodRU5DT0RJTkdfTkFNRV9URUxFUEhPTkVfRVZFTlQQDBIVChFFTkNPRElOR19OQU1FX1JUWBANEhUKEUVOQ09ESU5HX05BTUVfUkVEEA4qrgMKDUZtdHBQYXJhbWV0ZXISHgoaRk1UUF9QQVJBTUVURVJfVU5TUEVDSUZJRUQQABIbChdGTVRQX1BBUkFNRVRFUl9NSU5QVElNRRABEh8KG0ZNVFBfUEFSQU1FVEVSX1VTRUlOQkFOREZFQxACEhsKF0ZNVFBfUEFSQU1FVEVSX0xFVkVMX0lEEAMSHQoZRk1UUF9QQVJBTUVURVJfUFJPRklMRV9JRBAEEhwKGEZNVFBfUEFSQU1FVEVSX1RJRVJfRkxBRxAFEhoKFkZNVFBfUEFSQU1FVEVSX1RYX01PREUQBhIqCiZGTVRQX1BBUkFNRVRFUl9MRVZFTF9BU1lNTUVUUllfQUxMT1dFRBAHEiUKIUZNVFBfUEFSQU1FVEVSX1BBQ0tFVElaQVRJT05fTU9ERRAIEiMKH0ZNVFBfUEFSQU1FVEVSX1BST0ZJTEVfTEVWRUxfSUQQCRIcChhGTVRQX1BBUkFNRVRFUl9MRVZFTF9JRFgQChIaChZGTVRQX1BBUkFNRVRFUl9QUk9GSUxFEAsSFwoTRk1UUF9QQVJBTUVURVJfVElFUhAMKrEBCgxGZWVkYmFja1R5cGUSHQoZRkVFREJBQ0tfVFlQRV9VTlNQRUNJRklFRBAAEhsKF0ZFRURCQUNLX1RZUEVfR09PR19SRU1CEAESHgoaRkVFREJBQ0tfVFlQRV9UUkFOU1BPUlRfQ0MQAhIVChFGRUVEQkFDS19UWVBFX0NDTRADEhYKEkZFRURCQUNLX1RZUEVfTkFDSxAEEhYKEkZFRURCQUNLX1RZUEVfUlJUUhAFYgZwcm90bzM",[m0]);let v0=function(e){return e[e.VIDEO_EXT_HDR_TOFFSET=0]="VIDEO_EXT_HDR_TOFFSET",e[e.VIDEO_EXT_ABS_SEND_TIME=1]="VIDEO_EXT_ABS_SEND_TIME",e[e.VIDEO_EXT_ORIENTATION=2]="VIDEO_EXT_ORIENTATION",e[e.VIDEO_EXT_TWCC=3]="VIDEO_EXT_TWCC",e[e.VIDEO_EXT_PLAYOUT_DELAY=4]="VIDEO_EXT_PLAYOUT_DELAY",e[e.VIDEO_EXT_CONTENT_TYPE=5]="VIDEO_EXT_CONTENT_TYPE",e[e.VIDEO_EXT_VIDEO_TIMING=6]="VIDEO_EXT_VIDEO_TIMING",e[e.VIDEO_EXT_COLOR_SPACE=7]="VIDEO_EXT_COLOR_SPACE",e[e.VIDEO_EXT_SDES_MID=8]="VIDEO_EXT_SDES_MID",e[e.VIDEO_EXT_SDES_RTP_STREAM_ID=9]="VIDEO_EXT_SDES_RTP_STREAM_ID",e[e.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID=10]="VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID",e}({}),y0=function(e){return e[e.AUDIO_EXT_AUDIO_LEVEL=0]="AUDIO_EXT_AUDIO_LEVEL",e[e.AUDIO_EXT_ABS_SEND_TIME=1]="AUDIO_EXT_ABS_SEND_TIME",e[e.AUDIO_EXT_TWCC=2]="AUDIO_EXT_TWCC",e[e.AUDIO_EXT_SDES_MID=3]="AUDIO_EXT_SDES_MID",e[e.AUDIO_EXT_SDES_RTP_STREAM_ID=4]="AUDIO_EXT_SDES_RTP_STREAM_ID",e[e.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID=5]="AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID",e}({}),C0=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.VP8=1]="VP8",e[e.VP9=2]="VP9",e[e.H264=3]="H264",e[e.H265=4]="H265",e[e.AV1=5]="AV1",e[e.G711=6]="G711",e[e.G722=7]="G722",e[e.OPUS=8]="OPUS",e[e.PCMU=9]="PCMU",e[e.PCMA=10]="PCMA",e[e.CN=11]="CN",e[e.TELEPHONE_EVENT=12]="TELEPHONE_EVENT",e[e.RTX=13]="RTX",e[e.RED=14]="RED",e}({}),b0=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.MINPTIME=1]="MINPTIME",e[e.USEINBANDFEC=2]="USEINBANDFEC",e[e.LEVEL_ID=3]="LEVEL_ID",e[e.PROFILE_ID=4]="PROFILE_ID",e[e.TIER_FLAG=5]="TIER_FLAG",e[e.TX_MODE=6]="TX_MODE",e[e.LEVEL_ASYMMETRY_ALLOWED=7]="LEVEL_ASYMMETRY_ALLOWED",e[e.PACKETIZATION_MODE=8]="PACKETIZATION_MODE",e[e.PROFILE_LEVEL_ID=9]="PROFILE_LEVEL_ID",e[e.LEVEL_IDX=10]="LEVEL_IDX",e[e.PROFILE=11]="PROFILE",e[e.TIER=12]="TIER",e}({}),I0=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.GOOG_REMB=1]="GOOG_REMB",e[e.TRANSPORT_CC=2]="TRANSPORT_CC",e[e.CCM=3]="CCM",e[e.NACK=4]="NACK",e[e.RRTR=5]="RRTR",e}({});const A0=p0("CgxzaWduYWwucHJvdG8SC2lvLmFnb3JhLnBiIuUFCg5Vc2VyQXR0cmlidXRlcxIVCghmZWF0dXJlMRgBIAEoDUgAiAEBEhUKCGZlYXR1cmUyGAIgASgNSAGIAQESHAoPdG9wblNtb290aExldmVsGAMgASgNSAKIAQESIAoTdG9wbk5ld1NwZWFrZXJEZWxheRgEIAEoDUgDiAEBEh0KEHRvcG5Td2l0Y2hIb2xkTXMYBSABKA1IBIgBARIaCg10b3BuQXVkaW9HYWluGAYgASgNSAWIAQESHAoPbWF4U3Vic2NyaXB0aW9uGAcgASgNSAaIAQESJQoYc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOGAggASgNSAeIAQESFQoIcnRtMkZsYWcYCSABKA1ICIgBARIWCglwcmVTdWJOdW0YCiABKA1ICYgBARIpCglwcmVTdWJVaWQYCyADKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSFAoMZW5hYmxlU3ViU1ZDGAwgAygJEhkKEWVuYWJsZVN2Y0V4dGVuZGVkGA0gAygJEhsKDmF1ZGlvRHVwbGljYXRlGA4gASgNSAqIAQESGwoObnRwRml4ZWRPZmZzZXQYDyABKAVIC4gBARIxCgtleHBlcmltZW50cxgQIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIDIgBAUILCglfZmVhdHVyZTFCCwoJX2ZlYXR1cmUyQhIKEF90b3BuU21vb3RoTGV2ZWxCFgoUX3RvcG5OZXdTcGVha2VyRGVsYXlCEwoRX3RvcG5Td2l0Y2hIb2xkTXNCEAoOX3RvcG5BdWRpb0dhaW5CEgoQX21heFN1YnNjcmlwdGlvbkIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOQgsKCV9ydG0yRmxhZ0IMCgpfcHJlU3ViTnVtQhEKD19hdWRpb0R1cGxpY2F0ZUIRCg9fbnRwRml4ZWRPZmZzZXRCDgoMX2V4cGVyaW1lbnRzIrcBChZVc2VyQXR0cmlidXRlc1Jlc3BvbnNlEiwKC3ByZVN1YlNzcmNzGAEgAygLMhcuaW8uYWdvcmEucGIuUHJlU3ViU3NyYxIlChhzdWJzY3JpYmVBdWRpb0ZpbHRlclRvcE4YAiABKA1IAIgBARIrCgpleHRlbnNpb25zGAMgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdEIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOInIKClByZVN1YlNzcmMSKAoDdWlkGAEgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlSACIAQESCQoBYRgCIAEoDRINCgVhX3J0eBgDIAEoDRIJCgF2GAQgASgNEg0KBXZfcnR4GAUgASgNQgYKBF91aWQizwYKDVNpZ25hbFJlcXVlc3QSFAoHbGljZW5zZRgBIAEoCUgAiAEBEg4KBnAycF9pZBgCIAEoDRISCgpzZXNzaW9uX2lkGAMgASgJEg4KBmFwcF9pZBgEIAEoCRITCgtjaGFubmVsX2tleRgFIAEoCRIUCgxjaGFubmVsX25hbWUYBiABKAkSEwoLc2RrX3ZlcnNpb24YByABKAkSFAoHYnJvd3NlchgIIAEoCUgBiAEBEioKCnByb2Nlc3NfaWQYCSABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSDAoEbW9kZRgKIAEoCRINCgVjb2RlYxgLIAEoCRIRCgRyb2xlGAwgASgJSAKIAQESIAoTaGFzX2NoYW5nZWRfZ2F0ZXdheRgNIAEoCEgDiAEBEhMKBmV4dGVuZBgOIAEoCUgEiAEBEhkKDGNzZXJ2aWNlX21hcBgPIAEoCUgFiAEBEhoKDW9wdGlvbmFsX2luZm8YECABKAlIBogBARIZCgxhcHBfc2NlbmFyaW8YESABKAlIB4gBARIvCgphdHRyaWJ1dGVzGBIgASgLMhsuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXMSEgoKcmVxdWVzdF90cxgTIAEoBBIXCgpzdHJpbmdfdWlkGBQgASgJSAiIAQESFQoIYWVzX21vZGUYFSABKAlICYgBARIXCgphZXNfc2VjcmV0GBYgASgJSAqIAQESGAoLYWVzX2VuY3J5cHQYFyABKAhIC4gBARIVCghhZXNfc2FsdBgYIAEoCUgMiAEBEiEKFGRlZmF1bHRfdmlkZW9fc3RyZWFtGBkgASgNSA2IAQFCCgoIX2xpY2Vuc2VCCgoIX2Jyb3dzZXJCBwoFX3JvbGVCFgoUX2hhc19jaGFuZ2VkX2dhdGV3YXlCCQoHX2V4dGVuZEIPCg1fY3NlcnZpY2VfbWFwQhAKDl9vcHRpb25hbF9pbmZvQg8KDV9hcHBfc2NlbmFyaW9CDQoLX3N0cmluZ191aWRCCwoJX2Flc19tb2RlQg0KC19hZXNfc2VjcmV0Qg4KDF9hZXNfZW5jcnlwdEILCglfYWVzX3NhbHRCFwoVX2RlZmF1bHRfdmlkZW9fc3RyZWFtIl8KEk11bHRpVW5pbGJzUmVxdWVzdBILCgN1cmkYASABKA0SJwoGZGV0YWlsGAIgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBITCgtzZXJ2aWNlX2lkcxgDIAMoDSKtAQoSU2RwRW5kcG9pbnRSZXF1ZXN0Ei8KBnVuaWxicxgBIAMoCzIfLmlvLmFnb3JhLnBiLk11bHRpVW5pbGJzUmVxdWVzdBILCgN1aWQYAiABKA0SDAoEb3BpZBgDIAEoBBIqCgZzaWduYWwYBCABKAsyGi5pby5hZ29yYS5wYi5TaWduYWxSZXF1ZXN0Eh8KBG9ydGMYBSABKAsyES5pby5hZ29yYS5wYi5PUlRDIvQCChNTZHBFbmRwb2ludFJlc3BvbnNlEicKBmRldGFpbBgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEAoIZW50ZXJfdHMYAiABKAQSEAoIbGVhdmVfdHMYAyABKAQSDAoEb3BpZBgEIAEoBBI5Cg91bmlsYnNfcmVzcG9uc2UYBSADKAsyIC5pby5hZ29yYS5wYi5NdWx0aVVuaWxic1Jlc3BvbnNlEgsKA3VpZBgGIAEoDRJAChNhdHRyaWJ1dGVzX3Jlc3BvbnNlGAcgASgLMiMuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXNSZXNwb25zZRIUCgxyZWpvaW5fdG9rZW4YCCABKAkSMAoIYWRkX29ydGMYCSABKAsyHi5pby5hZ29yYS5wYi5SdHBDYXBCZWZvcmVNZXJnZRIwCghkZWxfb3J0YxgKIAEoCzIeLmlvLmFnb3JhLnBiLlJ0cENhcEJlZm9yZU1lcmdlIq4BChNNdWx0aVVuaWxic1Jlc3BvbnNlEgwKBGNlcnQYASABKAkSCwoDY2lkGAIgASgNEgwKBGNvZGUYAyABKA0SJwoGZGV0YWlsGAQgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBIqCghzZXJ2aWNlcxgFIAMoCzIYLmlvLmFnb3JhLnBiLlNlcnZpY2VJbmZvEgwKBGZsYWcYBiABKA0SCwoDdXJpGAcgASgNIkkKC1NlcnZpY2VJbmZvEgoKAmlwGAEgASgJEgwKBHBvcnQYAiABKA0SEwoLZmluZ2VycHJpbnQYAyABKAkSCwoDaWNlGAQgAygJIn0KCkFQUmVzcG9uc2USCwoDdWlkGAEgASgNEgsKA2NpZBgCIAEoDRIMCgRjZXJ0GAMgASgJEicKBmRldGFpbBgEIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEwoGdGlja2V0GAUgASgJSACIAQFCCQoHX3RpY2tldCK9AQoNSm9pbkZvcndhcmRlchISCgpyZWpvaW5fa2V5GAEgASgJEioKBnNpZ25hbBgCIAEoCzIaLmlvLmFnb3JhLnBiLlNpZ25hbFJlcXVlc3QSCwoDaWNlGAMgAygJEjEKC25lZ290aWF0aW9uGAQgASgLMhwuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uEiwKC2FwX3Jlc3BvbnNlGAUgASgLMhcuaW8uYWdvcmEucGIuQVBSZXNwb25zZSrbBQoVVXNlckF0dHJpYnV0ZUZlYXR1cmUxEg8KC1VOU1BFQ0lGSUVEEAASGgoWZW5hYmxlRW5jb2RlZFRyYW5zZm9ybRABEhcKE2VuYWJsZUF1ZGlvTWV0YWRhdGEQAhISCg5lbmFibGVBdWRpb1B0cxAEEh0KGWVuYWJsZU5ldHdvcmtRdWFsaXR5UHJvYmUQCBIbChdlbmFibGVQdWJsaXNoZWRVc2VyTGlzdBAQEhwKGGVuYWJsZVB1Ymxpc2hBdWRpb0ZpbHRlchAgEhoKFmVuYWJsZVVzZXJMaWNlbnNlQ2hlY2sQQBIOCgllbmFibGVSVFgQgAESFAoPZW5hYmxlTlRQUmVwb3J0EIACEhcKEmVuYWJsZUluc3RhbnRWaWRlbxCABBIZChRlbmFibGVGdWxsbGlua0F2U3luYxCACBIWChFlbmFibGVEYXRhU3RyZWFtMhCAEBIWChFlbmFibGVBdXRGZWVkYmFjaxCAIBIhChxlbmFibGVVc2VyQXV0b1JlYmFsYW5jZUNoZWNrEIBAEg4KCGVuYWJsZVhSEICAARIYChJlbmFibGVMb3NzYmFzZWRCd2UQgIACEhEKC2VuYWJsZUF1dENDEICABBIWChBlbmFibGVDQ0ZhbGxiYWNrEICACBIWChBlbmFibGVQcmVhbGxvY1BDEICAEBITCg1lbmFibGVQdWJUV0NDEICAIBITCg1lbmFibGVTdWJUV0NDEICAQBITCgxlbmFibGVQdWJSVFgQgICAARITCgxlbmFibGVTdWJSVFgQgICAAhIcChVlbmFibGVRdWFsaXR5RmFsbGJhY2sQgICABBIcChVzZW50dHNVc2VzQWJzU2VuZFRpbWUQgICACBIbChRlbmFibGVEdWFsU3RyZWFtRmxhZxCAgIAQEhEKCmRpc2FibGVGRUMQgICAIBIYChFlbmFibGVWb3NGYWxsYmFjaxCAgIBAYgZwcm90bzM",[m0,R0]),w0=F$(A0,5),O0=F$(A0,6);let N0=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.enableEncodedTransform=1]="enableEncodedTransform",e[e.enableAudioMetadata=2]="enableAudioMetadata",e[e.enableAudioPts=4]="enableAudioPts",e[e.enableNetworkQualityProbe=8]="enableNetworkQualityProbe",e[e.enablePublishedUserList=16]="enablePublishedUserList",e[e.enablePublishAudioFilter=32]="enablePublishAudioFilter",e[e.enableUserLicenseCheck=64]="enableUserLicenseCheck",e[e.enableRTX=128]="enableRTX",e[e.enableNTPReport=256]="enableNTPReport",e[e.enableInstantVideo=512]="enableInstantVideo",e[e.enableFulllinkAvSync=1024]="enableFulllinkAvSync",e[e.enableDataStream2=2048]="enableDataStream2",e[e.enableAutFeedback=4096]="enableAutFeedback",e[e.enableUserAutoRebalanceCheck=8192]="enableUserAutoRebalanceCheck",e[e.enableXR=16384]="enableXR",e[e.enableLossbasedBwe=32768]="enableLossbasedBwe",e[e.enableAutCC=65536]="enableAutCC",e[e.enableCCFallback=131072]="enableCCFallback",e[e.enablePreallocPC=262144]="enablePreallocPC",e[e.enablePubTWCC=524288]="enablePubTWCC",e[e.enableSubTWCC=1048576]="enableSubTWCC",e[e.enablePubRTX=2097152]="enablePubRTX",e[e.enableSubRTX=4194304]="enableSubRTX",e[e.enableQualityFallback=8388608]="enableQualityFallback",e[e.senttsUsesAbsSendTime=16777216]="senttsUsesAbsSendTime",e[e.enableDualStreamFlag=33554432]="enableDualStreamFlag",e[e.disableFEC=67108864]="disableFEC",e[e.enableVosFallback=134217728]="enableVosFallback",e}({});const D0={VP8:C0.VP8,VP9:C0.VP9,H264:C0.H264,H265:C0.H265,AV1:C0.AV1,G711:C0.G711,G722:C0.G722,opus:C0.OPUS,PCMU:C0.PCMU,PCMA:C0.PCMA,CN:C0.CN,"telephone-event":C0.TELEPHONE_EVENT,rtx:C0.RTX,red:C0.RED};const P0={minptime:b0.MINPTIME,useinbandfec:b0.USEINBANDFEC,"level-id":b0.LEVEL_ID,"profile-id":b0.PROFILE_ID,"tier-flag":b0.TIER_FLAG,"tx-mode":b0.TX_MODE,"level-asymmetry-allowed":b0.LEVEL_ASYMMETRY_ALLOWED,"packetization-mode":b0.PACKETIZATION_MODE,"profile-level-id":b0.PROFILE_LEVEL_ID,"level-idx":b0.LEVEL_IDX,profile:b0.PROFILE,tier:b0.TIER};const L0={"goog-remb":I0.GOOG_REMB,"transport-cc":I0.TRANSPORT_CC,ccm:I0.CCM,nack:I0.NACK,rrtr:I0.RRTR};function k0(e){if(e)return Object.keys(L0).find((t=>L0[t]===e))}const M0={"urn:ietf:params:rtp-hdrext:toffset":v0.VIDEO_EXT_HDR_TOFFSET,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":v0.VIDEO_EXT_ABS_SEND_TIME,"urn:3gpp:video-orientation":v0.VIDEO_EXT_ORIENTATION,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":v0.VIDEO_EXT_TWCC,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":v0.VIDEO_EXT_PLAYOUT_DELAY,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type":v0.VIDEO_EXT_CONTENT_TYPE,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing":v0.VIDEO_EXT_VIDEO_TIMING,"http://www.webrtc.org/experiments/rtp-hdrext/color-space":v0.VIDEO_EXT_COLOR_SPACE,"urn:ietf:params:rtp-hdrext:sdes:mid":v0.VIDEO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":v0.VIDEO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":v0.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID},U0={"urn:ietf:params:rtp-hdrext:ssrc-audio-level":y0.AUDIO_EXT_AUDIO_LEVEL,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":y0.AUDIO_EXT_ABS_SEND_TIME,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":y0.AUDIO_EXT_TWCC,"urn:ietf:params:rtp-hdrext:sdes:mid":y0.AUDIO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":y0.AUDIO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":y0.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID};function V0(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function F0(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?x0(Object(n),!0).forEach((function(t){V0(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):x0(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function B0(e,t){return typeof iD(e)===t?iD(e):void 0}function G0(){try{const e=iD("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:F0({},e)}catch(e){return UD.debug("handle gateway attributes failed: ",e),{}}}function j0(e,t,n){var i,r;let{mode:o,codec:s,joinGatewayStartTime:a,hasChangeBGPAddress:c}=n;const d="apResponse"in t?Object.assign({},t.apResponse):void 0;let l=!1;var u,h;d&&(l=!!iD("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(u=d.detail)||void 0===u?void 0:u[5]),"CN"===(null===(h=d.detail)||void 0===h?void 0:h[3])&&iD("ENABLE_QUALITY_FALLBACK")&&iD("ENABLE_QUALITY_FALLBACK"));let p=iD("REPORT_APP_SCENARIO");if("string"!=typeof p)try{p=JSON.stringify(p)}catch(e){p=void 0}p&&p.length>128&&(p=void 0);const _="proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0,E=function(e,t,n,i,r){var o,s,a,c;n=Object.assign({},n);const d=EP(e),l=mP(e),u=(null===(o=e.preSubOptions)||void 0===o?void 0:o.length)||0,h=u>0?null===(s=e.preSubOptions)||void 0===s?void 0:s.map((e=>e.uid)):void 0,p=B0("PRE_SUB_NUM","number")||1,_=u>p?u:p,E=G0(),m=(gw()||ww(18,4,!1))&&Nw(18,6,!0)&&"h264"===t&&iD("ENABLE_ABSSENDTIME_AS_SENTTS"),f=!("CN"!==(null===(a=n.detail)||void 0===a?void 0:a[3])||!iD("ENABLE_QUALITY_FALLBACK"))&&iD("ENABLE_QUALITY_FALLBACK"),g=F0(F0({enableEncodedTransform:(!!iD("ENABLE_AUDIO_METADATA")||!!iD("ENABLE_AUDIO_PTS"))&&W0||!!iD("ENABLE_AUDIO_TOPN")&&Cw(sw.CHROME,87,116)||void 0,enableAudioMetadata:!!iD("ENABLE_AUDIO_METADATA")&&W0,enableAudioPts:!!iD("ENABLE_AUDIO_PTS")&&W0,topnSmoothLevel:iD("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:iD("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:iD("TOPN_SWITCH_HOLD_MS"),topnAudioGain:iD("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:iD("ENABLE_PUBLISHED_USER_LIST"),enableUserList:iD("ENABLE_USER_LIST"),maxSubscription:iD("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:B0("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:B0("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:B0("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===iD("USE_PUB_RTX")||!0===iD("USE_SUB_RTX")||void 0,disableFEC:iD("DISABLE_FEC"),enableNTPReport:!!iD("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:l,enableFulllinkAvSync:!!iD("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:B0("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:gP(),rtm2Flag:"number"==typeof i?i:void 0,enableUserAutoRebalanceCheck:!!iD("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:B0("USE_XR","boolean"),enableLossbasedBwe:B0("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:fP(),enableCCFallback:B0("ENABLE_CC_FALLBACK","boolean"),preSubUid:d?h:void 0,preSubNum:d?_:void 0,enablePubTWCC:B0("PUBLISH_TWCC","boolean"),enableSubTWCC:B0("SUBSCRIBE_TWCC","boolean"),enablePubRTX:B0("USE_PUB_RTX","boolean"),enableSubRTX:B0("USE_SUB_RTX","boolean"),enableSubSVC:iD("ENABLE_SVC")?iD("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(iD("SVC"))&&0!==iD("SVC").length?iD("SVC"):void 0,enableSvcExtended:iD("ENABLE_SVC")&&Array.isArray(iD("SVC_EXTENDED"))&&0!==iD("SVC_EXTENDED").length?iD("SVC_EXTENDED"):void 0,enableVosFallback:iD("ENABLE_VOS_FALLBACK"),enableQualityFallback:f},E),{},{audioDuplicate:B0("ENABLE_AUDIO_RED","boolean")?null!==(c=B0("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!m||void 0,enableDualStreamFlag:B0("ENABLE_DUAL_STREAM_FLAG","boolean")});for(const e in g)void 0===g[e]&&delete g[e],Array.isArray(g[e])&&0===g[e].length&&delete g[e],"enablePreallocPC"===e&&delete g[e];return g.enablePreallocPC=!0,g}(e,s,d,t.rtmFlag),m=F0(F0(F0(F0(F0({},t.license?{license:t.license}:{}),{},{p2pId:e.p2pId,sessionId:t.sid,appId:t.appId,channelKey:null!==(i=t.token)&&void 0!==i?i:t.appId,channelName:t.cname,sdkVersion:XN,processId:iD("PROCESS_ID"),mode:e.useP2P?"p2p":o,codec:s,role:null!==(r=t.role)&&void 0!==r?r:"audience",hasChangedGateway:l||c,extend:iD("JOIN_EXTEND")},_?{cservice_map:_}:{}),t.optionalInfo?{optionalInfo:t.optionalInfo}:{}),p?{appScenario:p}:{}),{},{attributes:K0(E),requestTs:(f=a,Number(f))});var f;return t.stringUid&&(m.stringUid=t.stringUid),t.aesmode&&t.aespassword&&(m.aesMode=t.aesmode,iD("ENCRYPT_AES")?(m.aesSecret=t.aespassword,m.aesEncrypt=!0):m.aesSecret=t.aespassword,t.aessalt&&(m.aesSalt=t.aessalt)),void 0!==t.defaultVideoStream&&(m.defaultVideoStream=t.defaultVideoStream),m}const W0=vw(87)||fw()||Iw(117);function K0(e){const t={enableSubSVC:[],enableSvcExtended:[]},n=["topnSmoothLevel","topnNewSpeakerDelay","topnSwitchHoldMs","topnAudioGain","maxSubscription","subscribeAudioFilterTopN","rtm2Flag","preSubNum","enableSubSVC","enableSvcExtended","audioDuplicate","preSubUid"],i={};for(const e in N0){const t=N0[e];"number"==typeof t&&0!==t&&(i[e]=t)}const r=[],o={};for(const s in e){const a=e[s];if(s in i&&!0===a){const e=i[s];let t,n;for(e<4294967296?(t=0,n=e):(t=1,n=1<<Math.floor(Math.log2(e))-32);r.length<=t;)r.push(0);r[t]|=n}else Di(n).call(n,s)?t[s]=a:s in i||(o[s]=a)}r.length>0&&r.forEach(((e,n)=>{void 0!==e&&0!==e&&(t["feature".concat(n+1)]=e)}));const s=Object.keys(o);s.length>0&&(t.experiments=o,s.forEach((e=>{e in t&&delete t[e]})));for(const e in t)void 0===t[e]&&delete t[e],Array.isArray(t[e])&&0===t[e].length&&delete t[e];return t}function Y0(e){var t,n,i,r;const o=function(e){if(e)return D0[e]||void 0}(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName),s=o||null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName,a=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingParameters,c=null===(r=e.fmtp)||void 0===r?void 0:r.parameters;let d,l;c&&Object.keys(c).forEach((e=>{const t=function(e){if(e)return P0[e]||void 0}(e);t?(d||(d={}),d[t]=c[e]+""):(l||(l={}),l[e]=c[e]+"")}));const u=d||l?F0(F0({},d?{enumParameters:d}:{}),l?{stringParameters:l}:{}):void 0;return F0(F0({payloadType:e.payloadType,rtpMap:e.rtpMap?F0(F0(F0({},o?{enumEncodingName:o}:{}),s?{stringEncodingName:s}:{}),{},{clockRate:e.rtpMap.clockRate+""},a?{encodingParameters:a}:{}):void 0},u?{fmtp:u}:{}),{},{rtcpFeedbacks:e.rtcpFeedbacks.map((e=>{const t=function(e){if(e)return L0[e]||void 0}(e.type),n=F0(F0(F0({},"parameter"in e&&e.parameter?{parameter:e.parameter}:{}),"additional"in e&&e.additional?{additional:e.additional}:{}),"interval"in e&&e.interval?{interval:e.interval}:{});return F0(t?{enumType:t}:{stringType:e.type},n)}))})}function H0(e){let t;if(e.rtpMap){const{enumEncodingName:n,stringEncodingName:i,clockRate:r,encodingParameters:o}=e.rtpMap,s=n?function(e){if(e)return Object.keys(D0).find((t=>D0[t]===e))}(n):i;t={encodingName:null!=s?s:"",clockRate:(null==r?void 0:r.kind.value)+"",encodingParameters:o}}const n={parameters:{}};if(e.fmtp){const{enumParameters:t,stringParameters:i}=e.fmtp;t&&Object.keys(t).forEach((e=>{const i=function(e){if(e)return Object.keys(P0).find((t=>P0[t]===e))}(e);i&&(n.parameters[i]=t[e].kind.value+"")})),i&&Object.keys(i).forEach((e=>{n.parameters[e]=i[e].kind.value+""}))}let i=[];return e.rtcpFeedbacks&&(i=e.rtcpFeedbacks.map((e=>{const{enumType:t,stringType:n,parameter:i,additional:r,interval:o}=e,s=F0(F0(F0({},i?{parameter:i}:{}),r?{additional:r}:{}),o?{interval:o}:{});return F0(t?{type:k0(t)+""}:{type:n+""},s)}))),{payloadType:e.payloadType,rtpMap:t,fmtp:n,rtcpFeedbacks:i}}function X0(e,t){const n=function(e,t){if("video"===e){const e=M0[t];return"number"==typeof e?e:void 0}if("audio"===e){const e=M0[t];return"number"==typeof e?e:void 0}}(e,t.extensionName);return{entry:t.entry,extensionName:"number"==typeof n?n:t.extensionName}}function J0(e,t){var n,i;const r=function(e,t){if(t||"number"==typeof t)return"video"===e?Object.keys(M0).find((e=>M0[e]===t)):Object.keys(U0).find((e=>U0[e]===t))}(e,Number(null===(n=t.extensionName)||void 0===n?void 0:n.kind.value))||(null===(i=t.extensionName)||void 0===i?void 0:i.kind.value);return{entry:t.entry,extensionName:r+""}}function z0(e){var t,n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C;const b={audioCodecs:null!==(t=null===(n=e.rtpCapabilities.send)||void 0===n?void 0:n.audioCodecs.map((e=>Y0(e))))&&void 0!==t?t:[],videoCodecs:null!==(i=null===(r=e.rtpCapabilities.send)||void 0===r?void 0:r.videoCodecs.map((e=>Y0(e))))&&void 0!==i?i:[],audioExtensions:null!==(o=null===(s=e.rtpCapabilities.send)||void 0===s?void 0:s.audioExtensions.map((e=>X0("audio",e))))&&void 0!==o?o:[],videoExtensions:null!==(a=null===(c=e.rtpCapabilities.send)||void 0===c?void 0:c.videoExtensions.map((e=>X0("video",e))))&&void 0!==a?a:[]},I={audioCodecs:null!==(d=null===(l=e.rtpCapabilities.recv)||void 0===l?void 0:l.audioCodecs.map((e=>Y0(e))))&&void 0!==d?d:[],videoCodecs:null!==(u=null===(h=e.rtpCapabilities.recv)||void 0===h?void 0:h.videoCodecs.map((e=>Y0(e))))&&void 0!==u?u:[],audioExtensions:null!==(p=null===(_=e.rtpCapabilities.recv)||void 0===_?void 0:_.audioExtensions.map((e=>X0("audio",e))))&&void 0!==p?p:[],videoExtensions:null!==(E=null===(m=e.rtpCapabilities.recv)||void 0===m?void 0:m.videoExtensions.map((e=>X0("video",e))))&&void 0!==E?E:[]},A={audioCodecs:null!==(f=null===(g=e.rtpCapabilities.sendrecv)||void 0===g?void 0:g.audioCodecs.map((e=>Y0(e))))&&void 0!==f?f:[],videoCodecs:null!==(S=null===(T=e.rtpCapabilities.sendrecv)||void 0===T?void 0:T.videoCodecs.map((e=>Y0(e))))&&void 0!==S?S:[],audioExtensions:null!==(R=null===(v=e.rtpCapabilities.sendrecv)||void 0===v?void 0:v.audioExtensions.map((e=>X0("audio",e))))&&void 0!==R?R:[],videoExtensions:null!==(y=null===(C=e.rtpCapabilities.sendrecv)||void 0===C?void 0:C.videoExtensions.map((e=>X0("video",e))))&&void 0!==y?y:[]};return{ice:[e.iceParameters.iceUfrag,e.iceParameters.icePwd],dtls:e.dtlsParameters.fingerprints.map((e=>({[e.hashFunction]:e.fingerprint}))),send:b,recv:I,sendRecv:A}}function Z0(e,t,n){var i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C,b,I,A,w,O,N,D,P,L,k;t&&t.sendRecv&&(t.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(S=t.send)||void 0===S?void 0:S.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(T=t.send)||void 0===T?void 0:T.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(R=t.send)||void 0===R?void 0:R.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(v=t.send)||void 0===v?void 0:v.videoExtensions)||[],...t.sendRecv.videoExtensions]},t.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(y=t.recv)||void 0===y?void 0:y.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(C=t.recv)||void 0===C?void 0:C.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(b=t.recv)||void 0===b?void 0:b.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(I=t.recv)||void 0===I?void 0:I.videoExtensions)||[],...t.sendRecv.videoExtensions]}),n&&n.sendRecv&&(n.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(A=n.send)||void 0===A?void 0:A.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(w=n.send)||void 0===w?void 0:w.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(O=n.send)||void 0===O?void 0:O.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(N=n.send)||void 0===N?void 0:N.videoExtensions)||[],...n.sendRecv.videoExtensions]},n.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(D=n.recv)||void 0===D?void 0:D.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(P=n.recv)||void 0===P?void 0:P.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(L=n.recv)||void 0===L?void 0:L.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(k=n.recv)||void 0===k?void 0:k.videoExtensions)||[],...n.sendRecv.videoExtensions]});const M=t?{send:{audioCodecs:(null===(i=t.send)||void 0===i?void 0:i.audioCodecs.map((e=>H0(e))))||[],videoCodecs:(null===(r=t.send)||void 0===r?void 0:r.videoCodecs.map((e=>H0(e))))||[],audioExtensions:(null===(o=t.send)||void 0===o?void 0:o.audioExtensions.map((e=>J0("audio",e))))||[],videoExtensions:(null===(s=t.send)||void 0===s?void 0:s.videoExtensions.map((e=>J0("video",e))))||[]},recv:{audioCodecs:(null===(a=t.recv)||void 0===a?void 0:a.audioCodecs.map((e=>H0(e))))||[],videoCodecs:(null===(c=t.recv)||void 0===c?void 0:c.videoCodecs.map((e=>H0(e))))||[],audioExtensions:(null===(d=t.recv)||void 0===d?void 0:d.audioExtensions.map((e=>J0("audio",e))))||[],videoExtensions:(null===(l=t.recv)||void 0===l?void 0:l.videoExtensions.map((e=>J0("video",e))))||[]}}:void 0,U=n?{send:{audioCodecs:(null===(u=n.send)||void 0===u?void 0:u.audioCodecs.map((e=>H0(e))))||[],videoCodecs:(null===(h=n.send)||void 0===h?void 0:h.videoCodecs.map((e=>H0(e))))||[],audioExtensions:(null===(p=n.send)||void 0===p?void 0:p.audioExtensions.map((e=>J0("audio",e))))||[],videoExtensions:(null===(_=n.send)||void 0===_?void 0:_.videoExtensions.map((e=>J0("video",e))))||[]},recv:{audioCodecs:(null===(E=n.recv)||void 0===E?void 0:E.audioCodecs.map((e=>H0(e))))||[],videoCodecs:(null===(m=n.recv)||void 0===m?void 0:m.videoCodecs.map((e=>H0(e))))||[],audioExtensions:(null===(f=n.recv)||void 0===f?void 0:f.audioExtensions.map((e=>J0("audio",e))))||[],videoExtensions:(null===(g=n.recv)||void 0===g?void 0:g.videoExtensions.map((e=>J0("video",e))))||[]}}:void 0,V={send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},{send:x,recv:F,sendrecv:B}=e;return x&&(V.send.audioCodecs.push(...x.audioCodecs),V.send.videoCodecs.push(...x.videoCodecs),V.send.audioExtensions.push(...x.audioExtensions),V.send.videoExtensions.push(...x.videoExtensions)),F&&(V.recv.audioCodecs.push(...F.audioCodecs),V.recv.videoCodecs.push(...F.videoCodecs),V.recv.audioExtensions.push(...F.audioExtensions),V.recv.videoExtensions.push(...F.videoExtensions)),B&&(V.send.audioCodecs.push(...B.audioCodecs),V.send.videoCodecs.push(...B.videoCodecs),V.send.audioExtensions.push(...B.audioExtensions),V.send.videoExtensions.push(...B.videoExtensions),V.recv.audioCodecs.push(...B.audioCodecs),V.recv.videoCodecs.push(...B.videoCodecs),V.recv.audioExtensions.push(...B.audioExtensions),V.recv.videoExtensions.push(...B.videoExtensions)),M&&(V.send.audioCodecs.push(...M.send.audioCodecs),V.send.videoCodecs.push(...M.send.videoCodecs),V.send.audioExtensions.push(...M.send.audioExtensions),V.send.videoExtensions.push(...M.send.videoExtensions),V.recv.audioCodecs.push(...M.recv.audioCodecs),V.recv.videoCodecs.push(...M.recv.videoCodecs),V.recv.audioExtensions.push(...M.recv.audioExtensions),V.recv.videoExtensions.push(...M.recv.videoExtensions)),U&&(U.send.audioCodecs.forEach((e=>{V.send.audioCodecs=V.send.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.videoCodecs.forEach((e=>{V.send.videoCodecs=V.send.videoCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.audioExtensions.forEach((e=>{V.send.audioExtensions=V.send.audioExtensions.filter((t=>t.entry!==e.entry))})),U.send.videoExtensions.forEach((e=>{V.send.videoExtensions=V.send.videoExtensions.filter((t=>t.entry!==e.entry))})),U.recv.audioCodecs.forEach((e=>{V.recv.audioCodecs=V.recv.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.recv.videoCodecs.forEach((e=>{V.recv.videoCodecs=V.recv.videoCodecs.filter((t=>t.payloadType!==e.payloadType))}))),{send:V.recv,recv:V.send}}function q0(e,t){e1(t,e);const n=function(e,t){if(void 0===e)return[];if("enum"===t.fieldKind||"scalar"===t.fieldKind){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.number)return[e[n]];return[]}return e.filter((e=>e.no===t.number))}(e.$unknown,t),[i,r,o]=$0(t);for(const e of n)l0(i,new CQ(e.data),r,e.wireType,{readUnknownFields:!0});return o()}function Q0(e,t,n){var i;e1(t,e);const r=(null!==(i=e.$unknown)&&void 0!==i?i:[]).filter((e=>e.no!==t.number)),[o,s]=$0(t,n),a=new yQ;T$(a,{writeUnknownFields:!0},o,s);const c=new CQ(a.finish());for(;c.pos<c.len;){const[e,t]=c.tag(),n=c.skip(t,e);r.push({no:e,wireType:t,data:n})}e.$unknown=r}function $0(e,t){const n=e.typeName,i=Object.assign(Object.assign({},e),{kind:"field",parent:e.extendee,localName:n}),r=Object.assign(Object.assign({},e.extendee),{fields:[i],members:[i],oneofs:[]}),o=GQ(r,void 0!==t?{[n]:t}:void 0);return[qQ(r,o),i,()=>{const t=o[n];if(void 0===t){const t=e.message;return UQ(t)?Az(t.fields[0].scalar,t.fields[0].longAsString):GQ(t)}return t}]}function e1(e,t){if(e.extendee.typeName!=t.$typeName)throw new Error("extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const t1=3,n1=2,i1={alwaysEmitImplicit:!1,enumAsInteger:!1,useProtoFieldName:!1};function r1(e,t){var n;const i=function(e,t){var n;if(e.desc.typeName.startsWith("google.protobuf."))switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t){if(""===e.typeUrl)return{};const{registry:n}=t;let i,r;if(n&&(i=function(e,t){if(""===e.typeUrl)return;const n="message"==t.kind?t:t.getMessage(E0(e.typeUrl));return n&&function(e,t){return""!==e.typeUrl&&("string"==typeof t?t:t.typeName)===E0(e.typeUrl)}(e,n)?c0(n,e.value):void 0}(e,n),i&&(r=n.getMessage(i.$typeName))),!r||!i)throw new Error("cannot encode message ".concat(e.$typeName,' to JSON: "').concat(e.typeUrl,'" is not in the type registry'));let o=r1(qQ(r,i),t);return(r.typeName.startsWith("google.protobuf.")||null===o||Array.isArray(o)||"object"!=typeof o)&&(o={value:o}),o["@type"]=e.typeUrl,o}(e.message,t);case"google.protobuf.Timestamp":return function(e){const t=1e3*Number(e.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode message ".concat(e.$typeName," to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));if(e.nanos<0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be negative"));if(e.nanos>999999999)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be greater than 99999999"));let n="Z";if(e.nanos>0){const t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(t).toISOString().replace(".000Z",n)}(e.message);case"google.protobuf.Duration":return function(e){const t=Number(e.seconds),n=e.nanos;if(t>315576e6||t<-315576e6)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: value out of range"));if(t>0&&n<0||t<0&&n>0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos sign must match seconds sign"));let i=e.seconds.toString();if(0!==n){let e=Math.abs(n).toString();e="0".repeat(9-e.length)+e,"000000"===e.substring(3)?e=e.substring(0,3):"000"===e.substring(6)&&(e=e.substring(0,6)),i+="."+e,n<0&&0==t&&(i="-"+i)}return i+"s"}(e.message);case"google.protobuf.FieldMask":return(n=e.message).paths.map((e=>{if(Vj(Uj(e))!==e)throw new Error("cannot encode message ".concat(n.$typeName,' to JSON: lowerCamelCase of path name "').concat(e,'" is irreversible'));return Uj(e)})).join(",");case"google.protobuf.Struct":return d1(e.message);case"google.protobuf.Value":return l1(e.message);case"google.protobuf.ListValue":return u1(e.message);default:if(UQ(e.desc)){const t=e.desc.fields[0];return a1(t,e.get(t))}return}}(e,t);if(void 0!==i)return i;const r={};for(const n of e.sortedFields){if(!e.isSet(n)){if(n.presence==t1)throw new Error("cannot encode ".concat(n," to JSON: required field not set"));if(!t.alwaysEmitImplicit||n.presence!==n1)continue}const i=o1(n,e.get(n),t);void 0!==i&&(r[c1(n,t)]=i)}if(t.registry){const i=new Set;for(const{no:o}of null!==(n=e.getUnknown())&&void 0!==n?n:[])if(!i.has(o)){i.add(o);const n=t.registry.getExtensionFor(e.desc,o);if(!n)continue;const s=q0(e.message,n),[a,c]=$0(n,s),d=o1(c,a.get(c),t);void 0!==d&&(r[n.jsonName]=d)}}return r}function o1(e,t,n){switch(e.fieldKind){case"scalar":return a1(e,t);case"message":return r1(t,n);case"enum":return s1(e.enum,t,n.enumAsInteger);case"list":return function(e,t){const n=e.field(),i=[];switch(n.listKind){case"scalar":for(const t of e)i.push(a1(n,t));break;case"enum":for(const r of e)i.push(s1(n.enum,r,t.enumAsInteger));break;case"message":for(const n of e)i.push(r1(n,t))}return t.alwaysEmitImplicit||i.length>0?i:void 0}(t,n);case"map":return function(e,t){const n=e.field(),i={};switch(n.mapKind){case"scalar":for(const[t,r]of e)i[t]=a1(n,r);break;case"message":for(const[n,r]of e)i[n]=r1(r,t);break;case"enum":for(const[r,o]of e)i[r]=s1(n.enum,o,t.enumAsInteger)}return t.alwaysEmitImplicit||e.size>0?i:void 0}(t,n)}}function s1(e,t,n){var i;if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: expected number, got ").concat(PQ(t)));if("google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.value[t];return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function a1(e,t){var n,i,r,o,s,a;switch(e.scalar){case Iz.INT32:case Iz.SFIXED32:case Iz.SINT32:case Iz.FIXED32:case Iz.UINT32:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(n=AQ(e,t))||void 0===n?void 0:n.message));return t;case Iz.FLOAT:case Iz.DOUBLE:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(i=AQ(e,t))||void 0===i?void 0:i.message));return Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case Iz.STRING:if("string"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(r=AQ(e,t))||void 0===r?void 0:r.message));return t;case Iz.BOOL:if("boolean"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(o=AQ(e,t))||void 0===o?void 0:o.message));return t;case Iz.UINT64:case Iz.FIXED64:case Iz.INT64:case Iz.SFIXED64:case Iz.SINT64:if("bigint"!=typeof t&&"string"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(s=AQ(e,t))||void 0===s?void 0:s.message));return t.toString();case Iz.BYTES:if(t instanceof Uint8Array)return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"std";const n=UZ(t),i="std"==t;let r,o="",s=0,a=0;for(let t=0;t<e.length;t++)switch(r=e[t],s){case 0:o+=n[r>>2],a=(3&r)<<4,s=1;break;case 1:o+=n[a|r>>4],a=(15&r)<<2,s=2;break;case 2:o+=n[a|r>>6],o+=n[63&r],s=0}return s&&(o+=n[a],i&&(o+="=",1==s&&(o+="="))),o}(t);throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(a=AQ(e,t))||void 0===a?void 0:a.message))}}function c1(e,t){return t.useProtoFieldName?e.name:e.jsonName}function d1(e){const t={};for(const[n,i]of Object.entries(e.fields))t[n]=l1(i);return t}function l1(e){switch(e.kind.case){case"nullValue":return null;case"numberValue":if(!Number.isFinite(e.kind.value))throw new Error("".concat(e.$typeName," cannot be NaN or Infinity"));return e.kind.value;case"boolValue":case"stringValue":return e.kind.value;case"structValue":return d1(e.kind.value);case"listValue":return u1(e.kind.value);default:throw new Error("".concat(e.$typeName," must have a value"))}}function u1(e){return lz(e).map(l1)}var h1="\t\n\v\f\r                　\u2028\u2029\ufeff",p1=dW,_1=GZ,E1=h1,m1=Zj("".replace),f1=RegExp("^["+E1+"]+"),g1=RegExp("(^|[^"+E1+"])["+E1+"]+$"),S1=function(e){return function(t){var n=_1(p1(t));return 1&e&&(n=m1(n,f1,"")),2&e&&(n=m1(n,g1,"$1")),n}},T1={start:S1(1),end:S1(2),trim:S1(3)},R1=FH.PROPER,v1=Kj,y1=h1,C1=dS(T1);LH({target:"String",proto:!0,forced:function(e){return v1((function(){return!!y1[e]()||"​᠎"!=="​᠎"[e]()||R1&&y1[e].name!==e}))}("trim")},{trim:function(){return C1(this)}});var b1=dS(nz("String")),I1=JW,A1=b1,w1=String.prototype,O1=Gj((function(e){var t=dS(e);return"string"==typeof e||e===w1||I1(w1,e)&&t===dS(w1)?A1:t}));const N1={ignoreUnknownFields:!1};const D1=new WeakMap;function P1(e,t){var n;if(!D1.has(e)){const t=new Map;for(const n of e.fields)t.set(n.name,n).set(n.jsonName,n);D1.set(e,t)}return null===(n=D1.get(e))||void 0===n?void 0:n.get(t)}function L1(e,t,n){var i;if(function(e,t,n){if(!e.desc.typeName.startsWith("google.protobuf."))return!1;switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t,n){var i;if(null===t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: expected object but got ").concat(PQ(t)));if(0==Object.keys(t).length)return;const r=t["@type"];if("string"!=typeof r||""==r)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is empty'));const o=cQ(r).call(r,"/")?r.substring(r.lastIndexOf("/")+1):r;if(!o.length)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is invalid'));const s=null===(i=n.registry)||void 0===i?void 0:i.getMessage(o);if(!s)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(r," is not in the type registry"));const a=qQ(s);if(o.startsWith("google.protobuf.")&&Object.prototype.hasOwnProperty.call(t,"value"))L1(a,t.value,n);else{const e=Object.assign({},t);delete e["@type"],L1(a,e,n)}!function(e,t,n){var i;n||(n=GQ(_0)),n.value=g$(e,t),n.typeUrl=(i=t.$typeName,"type.googleapis.com/".concat(i))}(a.desc,a.message,e)}(e.message,t,n),!0;case"google.protobuf.Timestamp":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(PQ(t)));const n=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));e.seconds=yz.parse(i/1e3),e.nanos=0,n[7]&&(e.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9)}(e.message,t),!0;case"google.protobuf.Duration":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(PQ(t)));const n=t.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(null===n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(PQ(t)));const i=Number(n[1]);if(i>315576e6||i<-315576e6)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(PQ(t)));if(e.seconds=yz.parse(i),"string"!=typeof n[2])return;const r=n[2]+"0".repeat(9-n[2].length);e.nanos=parseInt(r),(i<0||Object.is(i,-0))&&(e.nanos=-e.nanos)}(e.message,t),!0;case"google.protobuf.FieldMask":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(PQ(t)));""!==t&&(e.paths=t.split(",").map((t=>{if(cQ(t).call(t,"_"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: path names must be lowerCamelCase"));return Vj(t)})))}(e.message,t),!0;case"google.protobuf.Struct":return j1(e.message,t),!0;case"google.protobuf.Value":return W1(e.message,t),!0;case"google.protobuf.ListValue":return K1(e.message,t),!0;default:if(UQ(e.desc)){const n=e.desc.fields[0];return null===t?e.clear(n):e.set(n,F1(n,t)),!0}return!1}}(e,t,n))return;if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode ".concat(e.desc," from JSON: ").concat(PQ(t)));const r=new Map;for(const[o,s]of Object.entries(t)){const t=P1(e.desc,o);if(t){if(t.oneof){if(null===s&&"scalar"==t.fieldKind)continue;const e=r.get(t.oneof);if(void 0!==e)throw new lQ(t.oneof,"oneof set multiple times by ".concat(e.name," and ").concat(t.name));r.set(t.oneof,t)}k1(e,t,s,n)}else{let t;if(o.startsWith("[")&&o.endsWith("]")&&(t=null===(i=n.registry)||void 0===i?void 0:i.getExtension(o.substring(1,o.length-1)))&&t.extendee.typeName===e.desc.typeName){const[i,r,o]=$0(t);k1(i,r,s,n),Q0(e.message,t,o())}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode ".concat(e.desc,' from JSON: key "').concat(o,'" is unknown'))}}}function k1(e,t,n,i){switch(t.fieldKind){case"scalar":!function(e,t,n){null===n?e.clear(t):e.set(t,F1(t,n))}(e,t,n);break;case"enum":!function(e,t,n,i){if(U1(t,n))return void e.clear(t);const r=x1(t.enum,n,i.ignoreUnknownFields);r!==V1&&e.set(t,r)}(e,t,n,i);break;case"message":!function(e,t,n,i){if(U1(t,n))return void e.clear(t);const r=e.isSet(t)?e.get(t):qQ(t.message);L1(r,n,i),e.set(t,r)}(e,t,n,i);break;case"list":!function(e,t,n){if(null===t)return;const i=e.field();if(!Array.isArray(t))throw new lQ(i,"expected Array, got "+PQ(t));for(const r of t){const t=M1(i,r,n);t!==V1&&e.add(t)}}(e.get(t),n,i);break;case"map":!function(e,t,n){if(null===t)return;const i=e.field();if("object"!=typeof t||Array.isArray(t))throw new lQ(i,"expected object, got "+PQ(t));for(const[r,o]of Object.entries(t)){const t=B1(i.mapKey,r),s=M1(i,o,n);s!==V1&&e.set(t,s)}}(e.get(t),n,i)}}function M1(e,t,n){if(e.scalar&&null!==t)return F1(e,t);if(e.message&&!U1(e,t)){const i=qQ(e.message);return L1(i,t,n),i}if(e.enum&&!U1(e,t))return x1(e.enum,t,n.ignoreUnknownFields);throw new lQ(e,"".concat("list"===e.fieldKind?"list item":"map value"," must not be null"))}function U1(e,t){var n,i;return null===t&&"google.protobuf.Value"!=(null===(n=e.message)||void 0===n?void 0:n.typeName)&&"google.protobuf.NullValue"!=(null===(i=e.enum)||void 0===i?void 0:i.typeName)}const V1=Symbol();function x1(e,t,n){if(null===t)return lz(e)[0].number;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=lz(e).find((e=>e.name===t));if(void 0!==i)return i.number;if(n)return V1}throw new Error("cannot decode ".concat(e," from JSON: ").concat(PQ(t)))}function F1(e,t){switch(e.scalar){case Iz.DOUBLE:case Iz.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if("number"==typeof t){if(Number.isNaN(t))throw new lQ(e,"unexpected NaN number");if(!Number.isFinite(t))throw new lQ(e,"unexpected infinite number");break}if("string"==typeof t){if(""===t)break;if(O1(t).call(t).length!==t.length)break;const e=Number(t);if(!Number.isFinite(e))break;return e}break;case Iz.INT32:case Iz.FIXED32:case Iz.SFIXED32:case Iz.SINT32:case Iz.UINT32:return G1(t);case Iz.BYTES:if("string"==typeof t){if(""===t)return new Uint8Array(0);try{return PZ(t)}catch(t){const n=t instanceof Error?t.message:String(t);throw new lQ(e,n)}}}return t}function B1(e,t){switch(e){case Iz.BOOL:switch(t){case"true":return!0;case"false":return!1}return t;case Iz.INT32:case Iz.FIXED32:case Iz.UINT32:case Iz.SFIXED32:case Iz.SINT32:return G1(t);default:return t}}function G1(e){if("string"==typeof e){if(""===e)return e;if(O1(e).call(e).length!==e.length)return e;const t=Number(e);return Number.isNaN(t)?e:t}return e}function j1(e,t){if("object"!=typeof t||null==t||Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(PQ(t)));for(const[n,i]of Object.entries(t)){const t=GQ(g0);W1(t,i),e.fields[n]=t}}function W1(e,t){switch(typeof t){case"number":e.kind={case:"numberValue",value:t};break;case"string":e.kind={case:"stringValue",value:t};break;case"boolean":e.kind={case:"boolValue",value:t};break;case"object":if(null===t)e.kind={case:"nullValue",value:T0.NULL_VALUE};else if(Array.isArray(t)){const n=GQ(S0);K1(n,t),e.kind={case:"listValue",value:n}}else{const n=GQ(f0);j1(n,t),e.kind={case:"structValue",value:n}}break;default:throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(PQ(t)))}return e}function K1(e,t){if(!Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(PQ(t)));for(const n of t){const t=GQ(g0);W1(t,n),lz(e).push(t)}}function Y1(e,t,n,i,r){let o,{opid:s,mode:a,codec:c,hasChangeBGPAddress:d=!1,ortc:l}=r;t.multiIP&&t.multiIP.gateway_ip&&(o=JSON.stringify({vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]}));const u="host"===t.role?"1":"audience"===t.role?"2":void 0,h={opid:s,unilbs:[{uri:22,detail:F0(F0(F0(F0(F0(F0({},n?{11:n,22:n}:{}),o?{5:o}:{}),iD("USE_NEW_TOKEN")?{12:"1"}:{}),u?{17:u}:{}),t.apRequestDetail?{33:t.apRequestDetail}:{}),t.apRTM?{26:"RTM2"}:{}),serviceIds:i}],uid:t.uid||0,signal:j0(e,t,{mode:a,codec:c,joinGatewayStartTime:Date.now(),hasChangeBGPAddress:d}),ortc:z0(l)},p=function(e,t,n){const i=qQ(e);try{L1(i,t,function(e){return e?Object.assign(Object.assign({},N1),e):N1}(n))}catch(e){if((r=e)instanceof Error&&cQ(dQ).call(dQ,r.name)&&"field"in r&&"function"==typeof r.field)throw new Error("cannot decode ".concat(e.field()," from JSON: ").concat(e.message),{cause:e});throw e}var r;return i.message}(w0,h),_=g$(w0,p),E=iD("ENABLE_AP_COMPRESS")?Pj(_,{raw:!0}):_;return iD("ENABLE_SDP_ENDPOINT_LOG")&&UD.debug("[sdp-endpoint] request json",h," sdpEndpointRequestJson,length is ".concat(E.length)),E}function H1(e,t,n){var i,r,o;const s=iD("ENABLE_AP_COMPRESS")?kj(n,{raw:!0}):n,a=c0(O0,new Uint8Array(s));iD("ENABLE_SDP_ENDPOINT_LOG")&&UD.debug("[sdp-endpoint] response json",function(e,t,n){return r1(qQ(e,t),function(e){return e?Object.assign(Object.assign({},i1),e):i1}(n))}(O0,a)," sdpEndpointResponseJson,length is ".concat(n.byteLength));const c=(null===(i=a.attributesResponse)||void 0===i?void 0:i.preSubSsrcs.map((e=>({a:e.a,a_rtx:e.aRtx,v:e.v,v_rtx:e.vRtx}))))||[],d=null===(r=a.attributesResponse)||void 0===r?void 0:r.subscribeAudioFilterTopN,l=null===(o=a.attributesResponse)||void 0===o?void 0:o.extensions,u=a.unilbsResponse[0].detail?Number(a.unilbsResponse[0].detail[8]):void 0;return{detail:a.detail,enter_ts:Number(a.enterTs),leave_ts:Number(a.leaveTs),opid:Number(a.opid),response_body:a.unilbsResponse.map((t=>({buffer:{cert:t.cert,cid:t.cid,cname:e.cname,code:t.code,detail:t.detail||{},edges_services:t.services.map((e=>({ip:e.ip,port:e.port,fingerprint:e.fingerprint,iceUfrag:e.ice[0],icePwd:e.ice[1]}))),flag:t.flag,uid:a.uid},uri:t.uri}))),signalResponse:{attributes:{userAttributes:F0(F0({preSubSsrcs:c},"number"==typeof d?{subscribeAudioFilterTopN:d}:{}),l)},rejoin_token:a.rejoinToken,return_vosip:!1,uid:e.stringUid?e.stringUid:a.uid,intUid:a.uid,vid:u,rtpCapabilities:Z0(t.rtpCapabilities,a.addOrtc,a.delOrtc)}}}function X1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function J1(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?X1(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):X1(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let z1=0;function Z1(e){const t=iD("TURN_DOMAINS");z1=(z1+1)%t.length;const n=t[z1]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(n):(UD.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function q1(e){try{const t=iD("TURN_DOMAINS"),n=iD("GATEWAY_DOMAINS").concat(t).find((t=>Di(e).call(e,t)));if(n){return e.split(".".concat(n))[0].replace(/-/g,".")}return e}catch(t){return UD.debug("serverUrlToIp error, fallback to url",e),e}}function Q1(e,t){e.addresses||(e.addresses=[]);const n=function(e,t){if(iD("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let{ip:t,port:n}=e;return{address:"".concat(t,":").concat(n)}}));const n=iD("GATEWAY_DOMAINS");let i=n[1]&&Di(t).call(t,n[1])?1:0;return e.map((e=>{let{domain_prefix:t,port:r,ip:o}=e;if(t)return{address:"".concat(t,".").concat(n[i++%n.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(n[i++%n.length],":").concat(r):"".concat(o,":").concat(r);return s||UD.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{ip:o,port:r,address:a}}))}(e.addresses,t),i=Array.isArray(e.detail)&&e.detail[18];if(i&&"string"==typeof i){const e=i.split(";");for(let t=0;t<e.length;t++){var r;const i=dS(r=e[t]).call(r);n[t]&&i&&(n[t].ip6=i)}}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:n,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 $1(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function e2(e){const t=e._encoderConfig;if(!t)return{};const n={resolution:t.width&&t.height?"".concat($1(t.width),"x").concat($1(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(n.maxFrameRate=t.frameRate,n.minFrameRate=t.frameRate):t.frameRate&&(n.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,n.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),n}function t2(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 n2(e,t){let n,i,r;switch(t){case Mj.CHOOSE_SERVER:i=4096,r="choose server";break;case Mj.CLOUD_PROXY:i=1048576,r="proxy";break;case Mj.CLOUD_PROXY_5:i=4194304,r="proxy5";break;case Mj.CLOUD_PROXY_FALLBACK:i=4194310,r="proxy fallback";break;default:throw new dP(Xw.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===i&&(n={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>J1(J1({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:J1(J1({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})})),!n)throw new dP(Xw.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return n}async function i2(e,t){return await Wh.all(e.addresses.map((async e=>({address:Z1(e.ip),tcpport:e.port,udpport:e.port,username:t&&iD("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():ZN.username,password:t&&iD("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await lO(t.toString()):ZN.password}))))}function r2(e,t){const n=t.getMediaStreamTrack(!0).getSettings(),i=t.videoHeight||n.height,r=t.videoWidth||n.width;return i&&r?Math.max(Math.min(i,r)/Math.min($1(e.height),$1(e.width)),1):(UD.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function o2(e){let{candidateType:t,relayProtocol:n,type:i,address:r,port:o,protocol:s}=e;const a={candidateType:t,relayProtocol:n,protocol:s};if("local-candidate"!==i){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),a.address=e.join("."),a.port=o}return a}function s2(e){const t=e.split(":"),n=e.split(/[-.]/),i=Di(e).call(e,"-")?"-":".";let r=e;return t.length>1?n.length>1?(n[1]="**",r=n[0]+i+"**:"+t[t.length-1]):r=t.length>2?t[0]+i+"**:"+t[t.length-1]:"**:"+t[t.length-1]:n.length>1&&(r=n[0]+i+"**"),r}function a2(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function c2(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iD("SVC_MODE");if(iD("ENABLE_SVC"))return function(e){return e in VN}(e)?e:VN.L1T3}const d2={[fx.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"}],[fx.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 l2(e){e.send&&(p2(fx.VIDEO,e.send.videoExtensions),p2(fx.AUDIO,e.send.audioExtensions)),e.recv&&(p2(fx.VIDEO,e.recv.videoExtensions),p2(fx.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(p2(fx.VIDEO,e.sendrecv.videoExtensions),p2(fx.AUDIO,e.sendrecv.audioExtensions))}function u2(e,t){e.send&&(h2(fx.VIDEO,e.send.videoExtensions,t.send.videoExtensions),h2(fx.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(h2(fx.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),h2(fx.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function h2(e,t,n){t.forEach((t=>{var i;const r=d2[e].find((e=>{var n;let{key:i}=e;return Di(n=t.extensionName).call(n,i)}));if(!r)return;const o=n.find((e=>{let{extensionName:t}=e;return Di(t).call(t,r.key)}));o&&Di(i=o.extensionName).call(i,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function p2(e,t){t.forEach((t=>{var n;const i=d2[e].find((e=>{var n;let{key:i}=e;return Di(n=t.extensionName).call(n,i)}));Di(n=t.extensionName).call(n,"gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function _2(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Di(e).call(e,"abs-send-time")}function E2(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Di(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function m2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function f2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?m2(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m2(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function g2(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=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}=n;let h=[],p=[],_=[],E=[],m=!1,f=!1;if(_D(e).mediaDescriptions.forEach((e=>{i&&i!==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=x2(e,p).map((e=>e.payloadType)),n=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!Di(n).call(n,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 Di(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 Di(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(r?[]:x2(e,p))}const g=iD("UNSUPPORTED_VIDEO_CODEC");if(g&&g.length>0){const e=p.filter((e=>e.rtpMap&&Di(g).call(g,e.rtpMap.encodingName.toLowerCase()))),t=x2(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Di(n).call(n,e.payloadType))),UD.debug("unsupportedVideoCodec: ".concat(g,", toBeRemoved: ").concat(n))}if(d&&d.length>0&&"sendonly"===i){const e=p.filter((e=>e.rtpMap&&Di(d).call(d,e.rtpMap.encodingName.toLowerCase()))),t=x2(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Di(n).call(n,e.payloadType))),UD.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(n))}if(l&&l.length>0&&"recvonly"===i){const e=p.filter((e=>e.rtpMap&&Di(l).call(l,e.rtpMap.encodingName.toLowerCase()))),t=x2(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Di(n).call(n,e.payloadType))),UD.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(n))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function S2(e){const t=_D(e);let n,i;for(const e of t.mediaDescriptions){if(!n){const t=e.attributes.iceUfrag,i=e.attributes.icePwd;if(!t||!i)throw new Error("Cannot get iceUfrag or icePwd from SDP.");n={iceUfrag:t,icePwd:i}}if(!i){const t=e.attributes.fingerprints;t.length>0&&(i={fingerprints:t})}}if(!i&&t.attributes.fingerprints.length>0&&(i={fingerprints:t.attributes.fingerprints}),!i||!n)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:n,dtlsParameters:i}}function T2(e,t){const n=[],i=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=i.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];n.push({ssrcId:e,rtx:t?o:void 0})}));else if(i.length>0){const e=i[0].ssrcIds[0],r=i[0].ssrcIds[1];n.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");n.push({ssrcId:o[0].ssrcId})}return n}function R2(e,t,n){const{cname:i}=e;let r=[];t&&(r=y2(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:{}}))),UD.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"}return{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:M2(e.rtpCapabilities),setup:a,cname:i,preSSRCs:v2(n)}}function v2(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach((e=>{t.push({kind:fx.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:fx.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),t}function y2(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:{}}],UD.debug("Using remote candidate from AP ".concat(s2(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:{}}),UD.debug("Using IPV6 remote candidate from AP ".concat(s2(e.ip6),":").concat(e.port)))),t}function C2(e,t,n){const i=[],r=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=$O(8,"track-"),c={ssrcId:o,attributes:f2({label:a,mslabel:n=n||$O(10,""),msid:"".concat(n," ").concat(a)},t&&{cname:t})};if(i.push(c),void 0!==s){const e={ssrcId:s,attributes:f2({label:a,mslabel:n,msid:"".concat(n," ").concat(a)},t&&{cname:t})};i.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:i,ssrcGroups:r}}function b2(e,t){t instanceof Gk&&e.attributes.payloads.forEach((e=>{var n;const i=null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase();if(!i||-1===["opus","pcmu","pcma","g722"].indexOf(i))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===i&&"number"==typeof iD("OPUS_PTIME")?e.fmtp.parameters.ptime=iD("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&("pcmu"!==i&&"pcma"!==i&&"g722"!==i&&(r.bitrate&&!Tw()&&(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 jk&&"opus"===i&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function I2(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 A2(e,t){var n;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&&iD("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof MM&&t._encoderConfig&&-1===t._hints.indexOf(xP.SCREEN_TRACK)))return;const i=t._encoderConfig;uP().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,n;Di(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))})),uP().supportMinBitrate&&!Di(n=t._hints).call(n,xP.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,n;Di(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(iD("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))}))}function w2(e){if("video"!==e.media.mediaType)return;const t=lw();if(t.name!==sw.SAFARI&&t.os!==ow.IOS)return;const n=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==n&&e.attributes.extmaps.splice(n,1)}function O2(e,t,n){if(!t)return;let i,r;if("video"===e.media.mediaType?(i=n.videoExtensions,r=n.videoCodecs):(i=n.audioExtensions,r=n.audioCodecs),!0===t.twcc){const t=i.find((e=>E2(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>E2(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>E2(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=i.find((e=>_2(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===n))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>_2(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 N2(e,t,n){if(Tw())return;if("video"!==e.media.mediaType)return;if(!(t instanceof MM))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!iD("SIMULCAST"))return;if("vp9"===n&&iD("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const i="vp8"===n?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<i;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:GO(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:GO(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function D2(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:VN.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const n=_D(t.sdp).mediaDescriptions[0];if(!n)return;const i=n.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),i}catch(e){return}}async function P2(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=new RTCPeerConnection;n.addTransceiver("video",{direction:"sendonly"}),n.addTransceiver("audio",{direction:"sendonly"}),n.addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"});const i=(await n.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]:{},n=arguments.length>2?arguments[2]:void 0;const i=g2(n,e,t,"sendonly"),r=g2(n,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(k2(i,r,"videoExtensions",o,s,a),k2(i,r,"videoCodecs",o,s,a),k2(i,r,"audioExtensions",o,s,a),k2(i,r,"audioCodecs",o,s,a),iD("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){var o,s;const r=a.videoCodecs[i+1],c=r&&K2(n,r),d=null===(o=n.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(s=n.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==iD("FIRST_H264_PROFILE_LEVEL_ID")||iD("FIRST_PACKETIZATION_MODE")&&l!==iD("FIRST_PACKETIZATION_MODE")?c?t.push([n,r]):t.push([n]):c?e.push([n,r]):e.push([n])}})),e.length>0&&t.length>0){UD.debug("raising H264 baseline profile priority"),a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){const r=K2(n,a.videoCodecs[i+1]),o=e.shift()||t.shift()||[];o.length>0&&(r?a.videoCodecs.splice(i,2,...o):a.videoCodecs.splice(i,1,...o))}}));const n=s.videoCodecs.filter((e=>{var t,n;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==iD("FIRST_H264_PROFILE_LEVEL_ID")}));if(n.length>0){const e=x2(n,s.videoCodecs).map((e=>e.payloadType)),t=[...n.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!Di(t).call(t,e.payloadType)))}iD("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,n;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==iD("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:s,sendrecv:a}}return{send:o,recv:s,sendrecv:a}}(e,t,i);try{n.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function L2(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=g2(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"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(k2(e,t,"videoExtensions",n,i,r),k2(e,t,"videoCodecs",n,i,r),k2(e,t,"audioExtensions",n,i,r),k2(e,t,"audioCodecs",n,i,r),iD("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){UD.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&(i.videoCodecs=i.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}function k2(e,t,n,i,r,o){if("videoExtensions"===n||"audioExtensions"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}if("videoCodecs"===n||"audioCodecs"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}}function M2(e){const{send:t,recv:n,sendrecv:i}=e;if(!i){if(!t||!n)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:n}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...i.audioCodecs],r.videoCodecs=[...t.videoCodecs,...i.videoCodecs],r.audioExtensions=[...t.audioExtensions,...i.audioExtensions],r.videoExtensions=[...t.videoExtensions,...i.videoExtensions]):r=GO(i),n?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...n.audioCodecs,...i.audioCodecs],o.videoCodecs=[...n.videoCodecs,...i.videoCodecs],o.audioExtensions=[...n.audioExtensions,...i.audioExtensions],o.videoExtensions=[...n.videoExtensions,...i.videoExtensions]):o=GO(i),{send:r,recv:o}}function U2(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 V2(e,t,n,i){let r=[];if(e===fx.VIDEO){if(iD("H264_PROFILE_LEVEL_ID")&&"h264"===i&&(r=t.videoCodecs.filter((e=>{var t;return Di(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===iD("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(n.videoCodecs.forEach((t=>{const n=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Di(n).call(n,i)?e.push(t):Di(n).call(n,"vp9")?o.push(t):Di(n).call(n,"vp8")?s.push(t):Di(n).call(n,"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"),UD.warning("codec ".concat(i," 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&&(UD.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),iD("USE_PUB_RTX")||iD("USE_SUB_RTX")){const e=x2(r,t.videoCodecs);r=[...r,...e]}}else{r=t.audioCodecs.filter((e=>{var t;return Di(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)}));const e=t.audioCodecs.filter((e=>{var t;return Di(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")}));0===r.length&&(UD.warning("codec ".concat(i," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Di(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")}))),iD("ENABLE_AUDIO_RED")&&0!==e.length&&(r=[...e,...r])}return r}function x2(e,t){const n=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Di(n).call(n,e.fmtp&&e.fmtp.parameters.apt)))}async function F2(e,t,n){const i=t.toString(),r=G2(i,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:i});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=B2(s,n||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function B2(e,t,n){if(iD("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=_D(e),{useXR:r}=t;return i.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(n)&&!Di(n).call(n,e.attributes.mid)||("audio"===e.media.mediaType&&U2(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!iD("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())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(e),r&&Di(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"})}))))})),ED(i)}function G2(e,t,n,i){if(iD("SDP_LOGGING"))return UD.upload("exchanging ".concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{G2(e,"answer","local"===n?"remote":"local",i)}:void 0}async function j2(e,t,n){try{var i;if(!uP().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!iD("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];o.scalabilityMode=c2(n),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),UD.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){UD.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function W2(e){const t=iD("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Di(e).call(e,t)))}function K2(e,t){try{var n;return(null===(n=e.fmtp)||void 0===n?void 0:n.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}const Y2={};function H2(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&UD.debug("install service ".concat(e.name)),Y2[e.name]=e}function X2(e){const t=Y2[e];if(!t)throw new Jw(Xw.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function J2(e,t){return X2("DataStream").create(e,t)}function z2(){return X2("InterceptFrame").create()}function Z2(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}function q2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Q2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?q2(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):q2(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const $2=new Map;class e3 extends uO{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(sx.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(sx.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){UD.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var n,i,r;super(),Db(this,"store",void 0),Db(this,"joinInfo",void 0),Db(this,"key",void 0),Db(this,"ntpOffset",0),Db(this,"usingProxy",!1),Db(this,"signal",void 0),Db(this,"role",void 0),Db(this,"isPreallocation",void 0),Db(this,"isPreSub",void 0),Db(this,"inChannelInfo",{joinAt:null,duration:0}),Db(this,"spec",void 0),Db(this,"_state","DISCONNECTED"),Db(this,"_statsCollector",void 0),Db(this,"_disconnectedReason",void 0),Db(this,"isSignalRecover",!1),Db(this,"hasChangeBGPAddress",!1),Db(this,"trafficStatsInterval",void 0),Db(this,"networkQualityInterval",void 0),Db(this,"_joinGatewayStartTime",0),Db(this,"_signalTimeout",!1),Db(this,"_clientRoleOptions",void 0),Db(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?(n={spec:Q2(Q2({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(i=(r=X2("P2PChannel")).createSubmodule)||void 0===i?void 0:i.call(r,n)):this.store.useDcSignal?function(e){return X2("DataChannelSignal").create(e)}({spec:Q2(Q2({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new eF(Q2(Q2({},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,n){if(this.store.useDcSignal){let t=!1;const n=e.apResponse.addresses[0],i=n.iceUfrag||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert),r=n.icePwd||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert);"disabled"!==e.cloudProxyServer?(UD.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):Z2(i,r)?e.apResponse.addresses.some((e=>e.fingerprint))||iD("FINGERPRINT")||(UD.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0):(UD.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const i=Date.now();let r=$2.get(e.cname);if(r||(r=new Map,$2.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new dP(Xw.UID_CONFLICT);throw cP.joinGateway(e.sid,{lts:i,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=i;const s=e.proxyServer,a=this.store.useDcSignal?"datachannel":"websocket";try{UD.debug("[".concat(this.store.clientId,"] use ").concat(a," join uid ").concat(o));const t=e.gatewayAddrs.map((t=>{let{address:n}=t;const[i,r]=n.split(":"),o={host:i,port:r};return e.proxyServer&&(o.proxy=e.proxyServer),o}));let n;n=this.store.useDcSignal?await this.signal.init(e.apResponse.addresses):await this.signal.init(t),o=n.uid,UD.debug("[".concat(this.store.clientId,"] ").concat(a," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var c;if(t.code===Xw.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else cP.joinGateway(e.sid,{lts:i,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===Xw.INIT_DATACHANNEL_TIMEOUT)throw UD.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw UD.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(),UD.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{UD.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(sx.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(sx.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(sx.NETWORK_QUALITY,{uplinkNetworkQuality:t2(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:t2(this._statsCollector.trafficStats.B_dnq)}):this.emit(sx.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!==gO.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==VV.CONNECTED||await function(e,t){return t===1/0?e:Wh.race([e,qO(t)])}(this.signal.request(FV.LEAVE,void 0,!0),3e3)}catch(e){UD.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==gO.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const i={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:iD("PUB_EXTEND"),twcc:!!iD("PUBLISH_TWCC"),rtx:!!iD("USE_PUB_RTX")};try{return(await this.signal.request(FV.PUBLISH,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===UV.ERR_PUBLISH_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),i.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw i}}async publishDataChannel(e,t,n){var i;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.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!==(i=t.maxRetransmits)&&void 0!==i?i:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(FV.PUBLISH_DATASTREAM,r,!0)}catch(i){if(n&&i.data&&i.data.code===UV.ERR_PUBLISH_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),i.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw i}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(FV.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){UD.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(FV.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){UD.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!iD("SUBSCRIBE_TWCC"),rtx:!!iD("USE_SUB_RTX")||void 0,extend:iD("SUB_EXTEND"),svc:Array.isArray(iD("SVC"))&&0!==iD("SVC").length?iD("SVC"):void 0};try{return await this.signal.request(FV.PRE_SUBSCRIBE,i,!0)}catch(i){if(n&&i.data&&i.data.code===UV.ERR_SUBSCRIBE_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),i.toString()),this.presubscribe(e,t,!1);throw i}}async subscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!iD("SUBSCRIBE_TWCC"),rtx:!!iD("USE_SUB_RTX"),extend:iD("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(iD("SVC"))&&0!==iD("SVC").length?iD("SVC"):void 0};try{return(await this.signal.request(FV.SUBSCRIBE,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===UV.ERR_SUBSCRIBE_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),i.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw i}}async subscribeDataChannel(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const i={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(FV.SUBSCRIBE_DATASTREAM,i,!0)}catch(i){if(n&&i.data&&i.data.code===UV.ERR_SUBSCRIBE_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),i.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw i}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const n={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!iD("USE_SUB_RTX"),twcc:!!iD("SUBSCRIBE_TWCC"),svc:Array.isArray(iD("SVC"))&&0!==iD("SVC").length?iD("SVC"):void 0};try{return await this.signal.request(FV.SUBSCRIBE_STREAMS,n,!0)}catch(n){if(t&&n.data&&n.data.code===UV.ERR_SUBSCRIBE_REQUEST_INVALID)return UD.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),n.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw n}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,n=e.width,i=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,n||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,t||(r=!1)),r?{stream_type:0,width:n,height:i,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(FV.SET_VIDEO_PROFILE,t);UD.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(FV.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){UD.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new dP(Xw.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(FV.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){UD.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(FV.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){UD.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}=e;return{gatewayEstablishParams:await this.signal.request(FV.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(FV.GATEWAY_INFO)}async renewToken(e){await this.signal.request(FV.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),iD("CLIENT_ROLE_OPTIONS")&&(UD.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(iD("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},iD("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),iD("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},iD("CLIENT_ROLE_OPTIONS")),UD.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(iD("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let n,i=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(n=this._clientRoleOptions.delay,i=1):i=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:i=0;const r=Object.assign({},t);delete r.delay,delete r.level,await this.signal.request(FV.SET_CLIENT_ROLE,Q2(Q2({role:e,level:i,delay:n},r),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,n){await this.signal.request(FV.SET_DUAL_STREAM_MODE,{mode:e},n,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(FV.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(FV.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(FV.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(FV.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(FV.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,n){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,n)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),Q2({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(FV.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(FV.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=$2.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:ZN.username,password:ZN.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(Q2(Q2({},ZN),{},{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(FV.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&&BO((()=>{this.emit(sx.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,n;if(!this.joinInfo||!this.key)throw new dP(Xw.UNEXPECTED_ERROR,"can not generate join message, no join info");this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(sx.UPDATE_GATEWAY_CONFIG),n=this.store.clientId,Di(HU).call(HU,n)||HU.push(n);const i=function(e,t,n,i){var r,o,s,a,c;let{key:d,role:l,joinGatewayStartTime:u,hasChangeBGPAddress:h,isPreallocation:p,ortc:_,currentURLIndex:E}=i;const m=Object.assign({},t.apResponse);let f=!1;"signalResponse"in m&&m.signalResponse&&(1===e.p2pId&&(f=!0),p=!1,delete m.signalResponse);let g=iD("REPORT_APP_SCENARIO");if("string"!=typeof g)try{g=JSON.stringify(g)}catch(e){g=void 0}g&&g.length>128&&(g=void 0);const S=EP(e),T=mP(e),R=(null===(r=e.preSubOptions)||void 0===r?void 0:r.length)||0,v=R>0?null===(o=e.preSubOptions)||void 0===o?void 0:o.map((e=>e.uid)):void 0,y=B0("PRE_SUB_NUM","number")||1,C=R>y?R:y,b=G0(),I=vw(87)||fw()||Iw(117),A=(gw()||ww(18,4,!1))&&Nw(18,6,!0)&&"h264"===n.codec&&iD("ENABLE_ABSSENDTIME_AS_SENTTS"),w=!("CN"!==(null===(s=m.detail)||void 0===s?void 0:s[3])||!iD("ENABLE_QUALITY_FALLBACK"))&&iD("ENABLE_QUALITY_FALLBACK"),O=!!iD("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(a=m.detail)||void 0===a?void 0:a[5]),N={license:t.license,p2p_id:e.p2pId,session_id:t.sid,app_id:t.appId,channel_key:d,channel_name:t.cname,sdk_version:XN,browser:navigator.userAgent,process_id:iD("PROCESS_ID"),mode:e.useP2P?"p2p":n.mode,codec:n.codec,role:l,has_changed_gateway:O||h,ap_response:m,extend:iD("JOIN_EXTEND"),details:{6:t.stringUid,cservice_map:"proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0},features:F0({rejoin:!0},f?{multi_signaling:f}:{}),optionalInfo:t.optionalInfo,appScenario:g,attributes:{userAttributes:F0(F0({enableEncodedTransform:(!!iD("ENABLE_AUDIO_METADATA")||!!iD("ENABLE_AUDIO_PTS"))&&I||!!iD("ENABLE_AUDIO_TOPN")&&Cw(sw.CHROME,87,116)||void 0,enableAudioMetadata:!!iD("ENABLE_AUDIO_METADATA")&&I,enableAudioPts:!!iD("ENABLE_AUDIO_PTS")&&I,topnSmoothLevel:iD("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:iD("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:iD("TOPN_SWITCH_HOLD_MS"),topnAudioGain:iD("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:iD("ENABLE_PUBLISHED_USER_LIST"),enableUserList:iD("ENABLE_USER_LIST"),maxSubscription:iD("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:B0("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:B0("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:B0("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===iD("USE_PUB_RTX")||!0===iD("USE_SUB_RTX")||void 0,disableFEC:iD("DISABLE_FEC"),enableNTPReport:!!iD("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:T,enableFulllinkAvSync:!!iD("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:B0("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:gP(),rtm2Flag:"number"==typeof t.rtmFlag?t.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!iD("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:B0("USE_XR","boolean"),enableLossbasedBwe:B0("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:fP(),enableCCFallback:B0("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:p,preSubUid:S?v:void 0,preSubNum:S?C:void 0,enablePubTWCC:B0("PUBLISH_TWCC","boolean"),enableSubTWCC:B0("SUBSCRIBE_TWCC","boolean"),enablePubRTX:B0("USE_PUB_RTX","boolean"),enableSubRTX:B0("USE_SUB_RTX","boolean"),enableSubSVC:iD("ENABLE_SVC")?iD("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(iD("SVC"))&&0!==iD("SVC").length?iD("SVC"):void 0,enableSvcExtended:iD("ENABLE_SVC")&&Array.isArray(iD("SVC_EXTENDED"))&&0!==iD("SVC_EXTENDED").length?iD("SVC_EXTENDED"):void 0,enableVosFallback:iD("ENABLE_VOS_FALLBACK"),enableQualityFallback:w},b),{},{audioDuplicate:B0("ENABLE_AUDIO_RED","boolean")?null!==(c=B0("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!A||void 0,enableDualStreamFlag:B0("ENABLE_DUAL_STREAM_FLAG","boolean")})},join_ts:u,ortc:_||{}};return t.stringUid&&(N.string_uid=t.stringUid),t.aesmode&&t.aespassword&&(N.aes_mode=t.aesmode,iD("ENCRYPT_AES")?(N.aes_secret=t.aespassword,N.aes_encrypt=!0):N.aes_secret=t.aespassword,t.aessalt&&(N.aes_salt=t.aessalt)),m.addresses[E]&&(N.ap_response.ticket=m.addresses[E].ticket,delete m.addresses),void 0!==t.defaultVideoStream&&(N.default_video_stream=t.defaultVideoStream),N}(this.store,this.joinInfo,this.spec,{key:this.key,role:this.role,joinGatewayStartTime:this.joinGatewayStartTime,hasChangeBGPAddress:this.hasChangeBGPAddress,isPreallocation:!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),ortc:e,currentURLIndex:this.signal.currentURLIndex});return i}getRejoinMessage(){if(!this.joinInfo)throw new dP(Xw.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(xV.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(xV.WS_RECONNECTING,(e=>{this.joinInfo&&cP.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||bO.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",cP.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:2}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(xV.WS_CLOSED,(e=>{let t;switch(e){case gO.LEAVE:t=bO.LEAVE;break;case gO.UID_BANNED:case gO.IP_BANNED:case gO.CHANNEL_BANNED:case gO.SERVER_ERROR:t=bO.SERVER_ERROR;break;case gO.FALLBACK:t=bO.FALLBACK;break;case gO.LICENSE_MISSING:case gO.LICENSE_EXPIRED:case gO.LICENSE_MINUTES_EXCEEDED:case gO.LICENSE_PERIOD_INVALID:case gO.LICENSE_MULTIPLE_SDK_SERVICE:case gO.LICENSE_ILLEGAL:case gO.TOKEN_EXPIRE:t=e;break;default:t=bO.NETWORK_ERROR}UD.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+bO.NETWORK_ERROR)),this.joinInfo&&cP.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===gO.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==gO.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(xV.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=iD("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(UD.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(cP.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 UD.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));nD("EVENT_REPORT_DOMAIN",e[1]),nD("EVENT_REPORT_BACKUP_DOMAIN",e[1]),nD("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(GV.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(xV.REQUEST_RECOVER,((e,t,n)=>{if(!this.joinInfo)return n(new dP(Xw.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,wO(this,sx.REQUEST_NEW_GATEWAY_LIST).then(t).catch(n)})),this.signal.on(xV.REQUEST_JOIN_INFO,(async(e,t,n)=>{var i,r,o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage());const s=GO(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(iD("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&&iD("USE_TURN_IP")?Q2(Q2({},e),{},{turnServerURL:q1(e.turnServerURL)}):e)),t=null===(a=s.serversFromGateway)||void 0===a?void 0:a.map((e=>iD("USE_TURN_IP")?Q2(Q2({},e),{},{turnServerURL:q1(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),UD.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n))}const{iceParameters:c,dtlsParameters:d,rtpCapabilities:l}=await wO(this,sx.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer});try{e(this.getJoinMessage({iceParameters:c,dtlsParameters:d,rtpCapabilities:l,version:"2"}))}catch(e){t(e)}})),this.signal.on(xV.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE,((e,t)=>{if(this.joinInfo&&this.joinInfo.signalResponse){const t=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],n=this.joinInfo.signalResponse,i=iD("FINGERPRINT")||t.fingerprint;if(!t.iceUfrag||!t.icePwd||!i)return UD.debug("cannot get iceUfrag or icePwd or fingerprint from serverAddress"),void e(void 0);const r=Q2(Q2({},n),{},{ortc:{dtlsParameters:{role:"client",fingerprints:[{algorithm:"sha-256",fingerprint:iD("FINGERPRINT")||t.fingerprint}]},iceParameters:{candidates:[],iceUfrag:t.iceUfrag,icePwd:t.icePwd},rtpCapabilities:n.rtpCapabilities,cname:"o/i14u9pJrxRKAsu"}});this.joinInfo&&delete this.joinInfo.signalResponse,e(r)}else e(void 0)})),this.signal.on(xV.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(xV.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let n,i="";var r;e instanceof dP?(n=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,i=e.message):n=e;cP.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:n,errorMsg:i,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(xV.IS_P2P_DISCONNECTED,(e=>{e(DO(this,sx.IS_P2P_DISCONNECTED))})),this.signal.on(xV.DISCONNECT_P2P,(()=>{this.emit(sx.DISCONNECT_P2P)})),this.signal.on(xV.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(xV.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(xV.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(sx.JOIN_RESPONSE,e,t)})),this.signal.on(xV.PRE_CONNECT_PC,(async(e,t)=>{if(this.joinInfo){var n,i;this.updateTurnConfigFromSignal();const o=this.getCurrentGatewayAddress(),s=GO(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(iD("NEW_TURN_MODE")&&s&&"disabled"===(null===(i=this.joinInfo)||void 0===i?void 0:i.cloudProxyServer)){var r;let e=s.servers.map((e=>"turnServerURL"in e&&iD("USE_TURN_IP")?Q2(Q2({},e),{},{turnServerURL:q1(e.turnServerURL)}):e)),t=null===(r=s.serversFromGateway)||void 0===r?void 0:r.map((e=>iD("USE_TURN_IP")?Q2(Q2({},e),{},{turnServerURL:q1(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),UD.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n,",in pre pc"))}const a=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],c=iD("FINGERPRINT")||a.fingerprint;if(o&&c){const n=y2(o);wO(this,sx.PRE_CONNECT_PC,{candidates:n,fingerprint:c,turnServer:s,iceUfrag:a.iceUfrag,icePwd:a.icePwd}).then((t=>{null==e||e(t)})).catch(t||(()=>{}))}}})),this.signal.on(xV.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof iD("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(iD("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(xV.VOS_FALLBACK,(e=>{this.emit(sx.VOS_FALLBACK,e)})),this.signal.on(xV.DATACHANNEL_FAILBACK,(e=>{UD.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(sx.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(FV.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(FV.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw UD.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(FV.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(FV.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw UD.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(FV.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const n={action:e.find((e=>e.stream_type===ox.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(FV.CONTROL,n,!0,!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const n={action:e.find((e=>e.stream_type===ox.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(FV.CONTROL,n,!0,!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const n={action:e===fx.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(FV.CONTROL,n,!0,!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const n={action:e===fx.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(FV.CONTROL,n,!0,!0)}catch(e){throw UD.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(FV.RESTART_ICE,t,!0)}catch(e){throw UD.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||bO.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!iD("GATEWAY_WSS_ADDRESS"))return iD("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(UD.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(FV.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(gO.FALLBACK)),this.store.useDcSignal=!1,this.signal=new eF(Q2(Q2({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(sx.RESET_SIGNAL)}}let t3=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),n3=0,i3=0;function r3(e,t,n,i){return new Wh(((r,o)=>{t.timeout=t.timeout||iD("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),n3+=zO(t.data)):n&&(t.data.size?n3+=t.data.size:t.data instanceof FormData?n3+=ZO(t.data):n3+=zO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,$A.request(t).then((e=>{"string"==typeof e.data?i3+=zO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?i3+=e.data.byteLength:i3+=zO(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{$A.isCancel(e)?o(new dP(Xw.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new dP(Xw.NETWORK_TIMEOUT,e.message)):e.response?o(new dP(Xw.NETWORK_RESPONSE_ERROR,e.response.status)):o(new dP(Xw.NETWORK_ERROR,e.message))}))}))}
/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function n(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var i="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.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 n=0;n<e.length;++n){var i=e[n];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var n=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in n))break e;n=n[s]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&i(n,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:n(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,i(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var n="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(i){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(n+(i||"")+"_"+r++,i)}})),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]&&i(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(n(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,n,i){try{var r=t.call(e.g.j,n);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,i.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 g(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 n=e.g.j;return n?m(e,"return"in n?n.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 S(e,t){return t=new g(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 n=0,i=!1,r={next:function(){if(!i&&n<e.length){var r=n++;return{value:t(r,e[r]),done:!1}}return i=!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 n=0;n<e.length;n++)t(e[n])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},v=function(e,t,n){return t instanceof Blob?(n=void 0!==n?String(n+""):"string"==typeof t.name?t.name:"blob",t.name===n&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],n)),[String(e),t]):[String(e),String(t)]},y=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},C="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,b=C.FormData,I=C.XMLHttpRequest&&C.XMLHttpRequest.prototype.send,A=C.Request&&C.fetch,w=C.navigator&&C.navigator.sendBeacon,O=C.Element&&C.Element.prototype,N=C.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in C&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){C.File=function(e,t,n){return e=new Blob(e,n||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(n&&void 0!==n.lastModified?new Date(n.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 n=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];T(n,(function(n){t.append(e.name,n)}))}else"select-multiple"===e.type||"select-one"===e.type?T(e.options,(function(n){!n.disabled&&n.selected&&t.append(e.name,n.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(n="textarea"===e.type?R(e.value):e.value,t.append(e.name,n))}))};if((e=P.prototype).append=function(e,t,n){y(arguments,2),this.i.push(v(e,t,n))},e.delete=function(e){y(arguments,1);var t=[];e=String(e),T(this.i,(function(n){n[0]!==e&&t.push(n)})),this.i=t},e.entries=function e(){var t,n=this;return S(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<n.i.length?e=_(e,n.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){y(arguments,1);for(var n=c(this),i=n.next();!i.done;i=n.next()){var r=c(i.value);i=r.next().value,r=r.next().value,e.call(t,r,i,this)}},e.get=function(e){y(arguments,1);var t=this.i;e=String(e);for(var n=0;n<t.length;n++)if(t[n][0]===e)return t[n][1];return null},e.getAll=function(e){y(arguments,1);var t=[];return e=String(e),T(this.i,(function(n){n[0]===e&&t.push(n[1])})),t},e.has=function(e){y(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,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,r=c(i),_(e,r.next().value));n=t.next(),e.h=2}))},e.set=function(e,t,n){y(arguments,2),e=String(e);var i=[],r=v(e,t,n),o=!0;T(this.i,(function(t){t[0]===e?o&&(o=!i.push(r)):i.push(t)})),o&&i.push(r),this.i=i},e.values=function e(){var t,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,(r=c(i)).next(),_(e,r.next().value));n=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new b,t=c(this),n=t.next();!n.done;n=t.next()){var i=c(n.value);n=i.next().value,i=i.next().value,e.append(n,i)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],n="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,i){return"string"==typeof e?t.push(n+D(R(i))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(n+D(R(i))+'"; 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"),I){var L=C.XMLHttpRequest.prototype.setRequestHeader;C.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},C.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),I.call(this,e)):I.call(this,e)}}A&&(C.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),A.call(this,e,t)}),w&&(C.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),w.call(this,e,t)}),C.FormData=P}}();const o3=()=>{const e=iD("AREAS");0===e.length&&e.push(dx.GLOBAL);return zi(e).call(e,((e,t,n)=>{const i=s3(t);return i?0===n?i:"".concat(e,",").concat(i):e}),"")},s3=e=>e===dx.OVERSEA?"".concat(ux.ASIA,",").concat(ux.EUROPE,",").concat(ux.AFRICA,",").concat(ux.NORTH_AMERICA,",").concat(ux.SOUTH_AMERICA,",").concat(ux.OCEANIA):ux[e],a3=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 n=hx[e],i=Object.keys(n);i&&i.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(n[e]))}))})),t},c3={GLOBAL:{ASIA:[dx.CHINA,dx.JAPAN,dx.INDIA,dx.KOREA,dx.HKMC],EUROPE:[],NORTH_AMERICA:[dx.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},d3=Object.keys(c3[dx.GLOBAL]),l3=[dx.CHINA,dx.NORTH_AMERICA,dx.EUROPE,dx.ASIA,dx.JAPAN,dx.INDIA,dx.OCEANIA,dx.SOUTH_AMERICA,dx.AFRICA,dx.KOREA,dx.HKMC,dx.US],u3=function(e,t){let n=[];if(Di(e).call(e,dx.GLOBAL)){const o=[dx.GLOBAL,dx.OVERSEA],s=Object.keys(hx);if(t===dx.GLOBAL)throw new dP(Xw.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===dx.CHINA)n=[dx.OVERSEA];else if(r=t,Di(d3).call(d3,r)){const e=(i=t,c3[dx.GLOBAL][i]||[]),r=[...o,t,...e];n=s.filter((e=>!Di(r).call(r,e)))}else if(function(e){let t=!1;return d3.forEach((n=>{var i;Di(i=c3[dx.GLOBAL][n]).call(i,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return d3.forEach((n=>{var i;Di(i=c3[dx.GLOBAL][n]).call(i,e)&&(t=n)})),t}(t),i=[...o,e,t];n=s.filter((e=>!Di(i).call(i,e)))}else n=e;n=function(e){const t=[];return l3.forEach((n=>{Di(e).call(e,n)&&t.push(n)})),t.concat(e.filter((e=>!Di(l3).call(l3,e))))}(n)}else n=e;var i,r;return n};function h3(e){var t,n;if(!e&&Di(t=iD("AREAS")).call(t,dx.EXTENSIONS))return UD.debug("update area from ap : reset"),void p3(WU,!0);if(!Di(n=iD("AREAS")).call(n,dx.GLOBAL)||!e)return;let i=hx.EXTENSIONS;i&&(i={CODE:s3(dx.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")]},UD.debug("update area from ap success: ".concat(e,",config is "),i),nD("AREAS",[dx.EXTENSIONS],!0),Object.keys(i).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){nD(e,i[e][0])}else nD(e,i[e])})))}function p3(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=cP.reportApiInvoke(null,{name:_O.SET_AREA,options:e,tag:EO.TRACER});try{let i=[];if("string"==typeof e&&(i=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Di(lx).call(lx,e))throw new dP(Xw.INVALID_PARAMS,"invalid area code")})),i=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:n}=e;if(!t)throw new dP(Xw.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),i=n?u3(r,n):r}if(!t){if(oD.AREAS){const e=new dP(Xw.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return n.onError(e),void UD.warning("setArea is prohibited because of config-distribute")}if(Di(i).call(i,dx.GLOBAL)&&iD("AREAS")===dx.EXTENSIONS){const e=new dP(Xw.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return n.onError(e),void UD.warning("setArea is prohibited because of ap extensions")}}nD("AREAS",i,t);const r=a3(i);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){nD(e,r[e][0])}else nD(e,r[e])})),UD.debug("set area success:",i.join(","))}catch(e){throw n.onError(e),e}n.onSuccess()}function _3(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function E3(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_3(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_3(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let m3=1;function f3(e,t,n,i,r){m3+=1;const o={sid:n.sid,command:"convergeAllocateEdge",uid:"666",appId:n.appId,ts:Math.floor(Date.now()/1e3),seq:m3,requestId:m3,version:XN,cname:n.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return fN((async()=>{a=Date.now();const e=await r3(d,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new dP(Xw.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw UD.error(t.toString()),t}const n=JSON.parse(e.json_body);if(200!==n.code){const e=new dP(Xw.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(n.code,", reason: ").concat(n.reason),{code:n.code,responseTime:c});throw UD.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new dP(Xw.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:n.code,responseTime:c});throw UD.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(iD("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(n,t);return iD("LIVE_STREAMING_ADDRESS")&&(r.addressList=iD("LIVE_STREAMING_ADDRESS")instanceof Array?iD("LIVE_STREAMING_ADDRESS"):[iD("LIVE_STREAMING_ADDRESS")]),E3(E3({},r),{},{responseTime:c})}),((i,r)=>(cP.apworkerEvent(n.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(i.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((i,r)=>(cP.apworkerEvent(n.sid,{success:!1,sc:i.data&&i.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(i.code!==Xw.OPERATION_ABORTED&&i.code!==Xw.UNEXPECTED_RESPONSE||i.data&&i.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let g3=1;function S3(e,t,n,i,r,o,s){let{url:a,areaCode:c}=e;const d=Date.now();let l;const u=n.role,[h,p]=I3(r,n,i,c,Array.isArray(t)?t:[t]);let _=PO.networkState;return fN((async()=>{_&&PO.networkState===IO.OFFLINE&&PO.onlineWaiter&&await Wh.race([PO.onlineWaiter,QO(s&&s.maxRetryTimeout||EN.maxRetryTimeout)]),_=PO.networkState;const{data:e,headers:r}=await r3(a,{data:h,cancelToken:o,responseType:"arraybuffer",headers:{"Content-Type":"application/x-protobuf;"}},!0,!0);let c;l="1"===r.http3?1:-1,cP.reportResourceTiming(a,n.sid);const u=r["content-type"]||r["Content-Type"]||"",p=Di(u).call(u,"application/json");try{c=p?function(e){const t=iD("ENABLE_AP_COMPRESS")?kj(e,{raw:!0}):e,n=(new TextDecoder).decode(t);return JSON.parse(n)}(e):H1(n,i,e)}catch(e){throw new dP(Xw.PB_ERROR,"sdp enpoint response transformer get unknown res",{retry:!1})}v3(c,a,n,d,Array.isArray(t)?t:[t],l);const E=n2(c,Mj.CHOOSE_SERVER);let m;Array.isArray(t)&&t.length>1&&(m=n2(c,"proxy5"===n.cloudProxyServer?Mj.CLOUD_PROXY_5:"proxy3"===n.cloudProxyServer||"proxy4"===n.cloudProxyServer?Mj.CLOUD_PROXY:Mj.CLOUD_PROXY_FALLBACK));const f=performance.getEntriesByName(a),g=f[f.length-1];let S;return g&&(S={name:g.name,protocol:"nextHopProtocol"in g?g.nextHopProtocol:"",dnscost:"domainLookupEnd"in g&&"domainLookupStart"in g&&"number"==typeof g.domainLookupEnd&&"number"==typeof g.domainLookupStart?g.domainLookupEnd-g.domainLookupStart:-1,tcpTlsCost:"connectEnd"in g&&"connectStart"in g&&"number"==typeof g.connectEnd&&"number"==typeof g.connectStart?g.connectEnd-g.connectStart:-1,reqCost:"requestStart"in g&&"number"==typeof g.requestStart&&"responseEnd"in g&&"number"==typeof g.responseEnd?g.responseEnd-g.requestStart:-1,handleCost:"leave_ts"in c&&"enter_ts"in c&&"number"==typeof c.leave_ts&&"number"==typeof c.enter_ts?c.leave_ts-c.enter_ts:-1}),y3(E),Array.isArray(t)?{gatewayInfo:Q1(E,a),proxyInfo:m,url:a,resourceTimingInfo:S}:Q1(E,a)}),(e=>{const i="gatewayInfo"in e?e.gatewayInfo:e,r="proxyInfo"in e?e.proxyInfo:void 0,o="resourceTimingInfo"in e?e.resourceTimingInfo:void 0;return i&&cP.joinChooseServer(n.sid,{role:u,lts:d,succ:!0,csAddr:a,serverList:i.gatewayAddrs.map((e=>e.address)),ec:null,opid:p,cid:i.cid.toString(),uid:i.uid.toString(),csIp:i.csIp,unilbsServerIds:t.toString(),isHttp3:l,corssRegionTagReq:n.apRequestDetail,corssRegionTagRes:i.res.detail&&i.res.detail[38],vid:null==i?void 0:i.vid,resourceTimingInfo:o?JSON.stringify(o):void 0}),r&&cP.joinWebProxyAP(n.sid,{lts:d,sucess:1,apServerAddr:a,turnServerAddrList:r.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:n.cloudProxyServer,unilbsServerIds:t.toString()}),!1}),(e=>e.code!==Xw.PB_ERROR&&(e.code!==Xw.OPERATION_ABORTED&&(e.code===Xw.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(cP.joinWebProxyAP(n.sid,{lts:d,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:n.cloudProxyServer,unilbsServerIds:t.toString(),extend:JSON.stringify({networkState:_})}),UD.warning("[".concat(n.clientId,"] multi unilbs network error, retry"),e),!0)))),s)}function T3(e,t,n,i){let{url:r,areaCode:o}=e;const{clientId:s,sid:a}=t,c=Date.now();let d;const l=t.role,[u,h]=b3(t,o,[Mj.CHOOSE_SERVER]);let p=PO.networkState;return fN((async()=>{p&&PO.networkState===IO.OFFLINE&&PO.onlineWaiter&&await Wh.race([PO.onlineWaiter,QO(i&&i.maxRetryTimeout||EN.maxRetryTimeout)]),p=PO.networkState;const{data:e,headers:o}=await r3(r,{data:u,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===o.http3?1:-1,cP.reportResourceTiming(r,a),v3(e,r,t,c,[Mj.CHOOSE_SERVER],d);const s=n2(e,Mj.CHOOSE_SERVER);return y3(s),Q1(s,r)}),(e=>(e&&cP.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:[Mj.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==Xw.OPERATION_ABORTED&&(e.code===Xw.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(cP.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:h,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[Mj.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),UD.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),i)}function R3(e,t,n,i){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),d=t.role,[l,u]=b3(t,s,a);let h;return fN((async()=>{h&&PO.networkState===IO.OFFLINE&&PO.onlineWaiter&&await Wh.race([PO.onlineWaiter,QO(i&&i.maxRetryTimeout||EN.maxRetryTimeout)]),h=PO.networkState;const{data:e,headers:s}=await r3(o,{data:l,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,cP.reportResourceTiming(o,t.sid),v3(e,o,t,c,a,r);const d=n2(e,Mj.CHOOSE_SERVER),u=n2(e,"proxy5"===t.cloudProxyServer?Mj.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?Mj.CLOUD_PROXY:Mj.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}),y3(d),{gatewayInfo:Q1(d,o),proxyInfo:u,url:o,resourceTimingInfo:E}}),(e=>{var n;return e.gatewayInfo&&cP.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===(n=e.gatewayInfo)||void 0===n?void 0:n.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&cP.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!==Xw.OPERATION_ABORTED&&(e.code===Xw.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(cP.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})}),UD.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),i)}const v3=(e,t,n,i,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=n,d=[],l=a=>{4096===a.flag?cP.joinChooseServer(s,{role:n.role,lts:i,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:n.apRequestDetail}):1048576!==a.flag&&4194304!==a.flag&&4194310!==a.flag||cP.joinWebProxyAP(s,{lts:i,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:a.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const n=t.buffer.code;if(23===t.uri&&0===n&&!t.buffer.edges_services)if(4194310===t.buffer.flag)UD.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const n={error:new dP(Xw.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:iD("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(n),l(n)}if(0!==n){const i=xx(n),r={error:new dP(Xw.CAN_NOT_GET_GATEWAY_SERVER,i.desc,{desc:i.desc,retry:i.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?UD.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw UD.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 dP(Xw.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)))]})},y3=e=>{var t,n,i,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new dP(Xw.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});iD("AP_AREA")&&(null!==(i=e.detail)&&void 0!==i&&i[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?h3(e.detail[23].toLowerCase()):h3());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[19])){const t=e.detail[19],n=null==t?void 0:t.split(";");for(let t=0;t<n.length;t++){var o;const i=dS(o=n[t]).call(o),r=e.addresses[t];r&&n&&!r.fingerprint&&(e.addresses[t].fingerprint=i)}}if(iD("GATEWAY_ADDRESS")&&iD("GATEWAY_ADDRESS").length>0){UD.debug("assign gateway address to",iD("GATEWAY_ADDRESS"));const t=iD("GATEWAY_ADDRESS").map((t=>{var n,i,r,o;const s=null!==(n=null===(i=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===i?void 0:i.fingerprint)&&void 0!==n?n:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:s,iceUfrag:null===(r=e.addresses[0])||void 0===r?void 0:r.iceUfrag,icePwd:null===(o=e.addresses[0])||void 0===o?void 0:o.icePwd}}));e.addresses=t}},C3=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=xx(t.buffer.code);throw new dP(Xw.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw UD.debug("update ticket request received ap response without response body:",t),new dP(Xw.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},b3=(e,t,n)=>{const i=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:i,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:E3(E3(E3({6:e.stringUid,11:t,12:iD("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:n,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,i]},I3=(e,t,n,i,r)=>{const o=Math.floor(Math.random()*10**12);return[Y1(e,t,i,r,{opid:o,mode:e.mode,codec:e.codec,hasChangeBGPAddress:!1,ortc:n}),o]},A3=(e,t)=>{const n=Math.floor(Math.random()*10**12),i={appid:e.appId,client_ts:Date.now(),opid:n,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(i)),[r,n]};let w3=0;function O3(e){return Wh.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const N3=async e=>{let{fragementLength:t,referenceList:n,asyncMapHandler:i,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 n.slice(e,t).map(i)})();o&&o.push(...e);try{c=await O3(e)}catch(e){if(d+=a,s++,!(d>=n.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c},D3=async e=>{let{referenceList:t,asyncMapHandler:n,closeFn:i}=e;const r=t.length;let o=0;const s=async()=>{const e=n(t.shift());try{return await e}catch(e){if(o++,o>=r||null!=i&&i(e))throw e;return s()}};return s()};async function P3(){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],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,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],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,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,n,i,r,o,s];for(let t=0;t<c.length;t++){const n=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(n)}catch(e){return void a(!1)}}}(),d=setTimeout((()=>{a(!1)}),5e3)}));return a}async function L3(e,t,n,i){const r=async function(e,t,n,i){let r=null;const o=[],s=async()=>{const r=iD("WEBCS_DOMAIN").slice(0,iD("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:o3()}))),s=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:i=>(UD.debug("[".concat(e.clientId,"] Connect to choose_server:"),i.url),T3(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await QO(1e3),null!==r)return r;const s=iD("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:o3()}))),a=i.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(UD.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),i.url),T3(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await O3([s(),a()]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,n,i);return{gatewayInfo:await r}}async function k3(e,t,n,i,r){const o=e.cloudProxyServer;if("disabled"===o){if(!i)return;if(e.useLocalAccessPoint)return await L3(e,t,n,r);if(iD("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:i,proxyInfo:o}=await B3(e,t,n,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:i};const a=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ZN.tcpport,udpport:e.udpport||ZN.udpport,username:e.username||ZN.username,password:e.password||ZN.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:i.uid,n="glb:".concat(t.toString()),r=await lO(n),c=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ZN.tcpport,udpport:e.udpport||ZN.udpport,username:n,password:r,forceturn:!1,security:!0})));a.push(...c)}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:i}}return await L3(e,t,n,r)}const{proxyInfo:a,gatewayInfo:c}=await B3(e,t,n,r),d={gatewayInfo:c},l=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:ZN.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:ZN.udpport,username:e.username||ZN.username,password:e.password||ZN.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,n="glb:".concat(t.toString()),i=await lO(n),r=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||ZN.tcpport,udpport:"proxy4"===o?void 0:e.udpport||ZN.udpport,username:n,password:i,forceturn:"proxy4"!==o,security:"proxy5"===o})));l.push(...r)}return e.turnServer={mode:"manual",servers:l},UD.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),d}async function M3(e,t,n,i,r){const o=e.cloudProxyServer;if("disabled"===o){if(e.useLocalAccessPoint)return await L3(e,t,n,i);if(iD("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:o,proxyInfo:s}=await B3(e,t,n,i,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:o};const a=s.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ZN.tcpport,udpport:e.udpport||ZN.udpport,username:e.username||ZN.username,password:e.password||ZN.password,forceturn:!1,security:!0})));return e.turnServer={mode:"manual",servers:a},{gatewayInfo:o}}{const o=async function(e,t,n,i,r){let o=null;const s=[],a=async()=>{const o=iD("SDP_ENDPOINT_DOMAIN").slice(0,iD("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:o3()}))),a=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),c=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(UD.debug("[".concat(e.clientId,"] Connect to choose_server:"),o.url),S3(o,Mj.CHOOSE_SERVER,e,t,r,n,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:s});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c},c=async()=>{if(await QO(1e3),null!==o)return o;const a=iD("SDP_ENDPOINT_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:o3()}))),c=r.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:a.map((e=>e.url))}),d=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:o=>(UD.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),o.url),S3(o,Mj.CHOOSE_SERVER,e,t,r,n,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:s});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};try{return o=await O3([a(),c()]),s.length&&s.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),o}catch(e){throw e[0]}}(e,r,t,n,i);return{gatewayInfo:await o}}}const{proxyInfo:s,gatewayInfo:a}=await B3(e,t,n,i),c={gatewayInfo:a},d=s.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:ZN.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:ZN.udpport,username:e.username||ZN.username,password:e.password||ZN.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));return e.turnServer={mode:"manual",servers:d},UD.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),c}async function U3(e,t,n,i,r){const o=iD("ACCOUNT_REGISTER").slice(0,iD("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,n,i,r){const o=Date.now(),s={sid:n.sid,opid:10,appid:n.appId,string_uid:t};let a=e[0];const c=await fN((()=>r3(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((n,i)=>{if(0===n.code){if(n.uid<=0||n.uid>=Math.pow(2,32))throw UD.error("Invalid Uint Uid ".concat(t," => ").concat(n.uid),n),cP.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:Xw.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new dP(Xw.INVALID_UINT_UID_FROM_STRING_UID);return cP.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:null,extend:s}),!1}const r=xx(n.code);return r.retry&&(a=e[(i+1)%e.length]),cP.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:r.desc,extend:s}),r.retry}),((t,n)=>t.code!==Xw.OPERATION_ABORTED&&(cP.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(n+1)%e.length],!0)),r);if(0!==c.code){const e=xx(c.code);throw new dP(Xw.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,n,i);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 V3(e,t,n){const i=iD("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?i.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):i.map((e=>"https://".concat(e,"/api/v1")));try{const i=await D3({referenceList:r,asyncMapHandler:i=>async function(e,t,n,i){const r=Date.now(),o={sid:n.sid,opid:10,appid:n.appId,string_uid:t};try{const t=await r3(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=xx(t.code);throw new dP(Xw.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new dP(Xw.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:r,url:e,req:o,uid:t.uid,elapse:Date.now()-r}}catch(e){throw e}}(i,e,t,n),closeFn:e=>e.code===Xw.OPERATION_ABORTED||e.code===Xw.UNEXPECTED_RESPONSE&&!e.data.retry});return i}catch(e){throw e}}async function x3(e,t,n){const i=iD("CDS_AP").slice(0,iD("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=i.map((i=>function(e,t,n,i){const r=lw(),o={flag:64,cipher_method:0,features:E3(E3(E3(E3(E3({install_id:HN(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:XN,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:t3.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 fN((()=>r3(e,{data:o,timeout:1e3,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==Xw.OPERATION_ABORTED),i)}(i,e,t,n)));let o=null,s=null,a={};try{o=await O3(r)}catch(e){if(e.code===Xw.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(cP.reportApiInvoke(e.sid,{name:_O.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,n=Object.keys(t),i={};return n.forEach((e=>{var n;const r=dS(n=e.slice(4)).call(n),o=JSON.parse(t[e]),s=o[1];i[r]={tag:o[0]||"",value:s}})),i}(o)}catch(e){}return a}async function F3(e,t){const n=iD("WEBCS_DOMAIN").concat(iD("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:o3(),serviceIds:[Mj.CHOOSE_SERVER,Mj.CLOUD_PROXY_FALLBACK]})));try{const i=await D3({referenceList:n,asyncMapHandler:n=>async function(e,t,n){let i,{url:r,areaCode:o,serviceIds:s}=e;const a=Date.now(),[c,d]=b3(t,o,s);let l=PO.networkState;try{l&&PO.networkState===IO.OFFLINE&&PO.onlineWaiter&&await Wh.race([PO.onlineWaiter,QO(EN.maxRetryTimeout)]),l=PO.networkState;const{data:e,headers:t}=await r3(r,{data:c,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);i="1"===t.http3?1:-1;const o=e=>{const t=[];if(e.response_body.forEach((n=>{const i=n.buffer.code;if(23===n.uri&&0===i&&!n.buffer.edges_services)if(4194310===n.buffer.flag)n.buffer.edges_services=[];else{const i={error:new dP(Xw.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:iD("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:n.buffer.flag};t.push(i)}if(0!==i){const r=xx(i),o={error:new dP(Xw.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:n.buffer.flag};4194310===n.buffer.flag?UD.warning(o.error.toString()):t.push(o)}})),t.length)throw new dP(Xw.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=n2(e,Mj.CHOOSE_SERVER),u=n2(e,Mj.CLOUD_PROXY_FALLBACK);return y3(s),{gatewayInfo:Q1(s,r),proxyInfo:u,opid:d,requestTime:a,url:r,isHttp3:i,elapse:Date.now()-a}}catch(e){throw e}}(n,e,t),closeFn:e=>e.code===Xw.OPERATION_ABORTED||e.code===Xw.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return i}catch(e){throw e}}async function B3(e,t,n,i,r){const o=iD("PROXY_SERVER_TYPE3"),s=(e,t,n)=>{let i=n||o;return Array.isArray(i)&&(i=t%2==0&&o[1]||o[0]),"https://".concat(i,"/ap/?url=").concat(e)};let a=null;const c=[],d=async()=>{const o=iD(r?"SDP_ENDPOINT_DOMAIN":"WEBCS_DOMAIN").slice(0,iD("AJAX_REQUEST_CONCURRENT")).map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:o3(),serviceIds:[Mj.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Mj.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Mj.CLOUD_PROXY:Mj.CLOUD_PROXY_FALLBACK]}})),a=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),d=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(UD.debug("[".concat(e.clientId,"] Connect to choose_server:"),o.url),r?S3(o,o.serviceIds,e,r,i,t,n):R3(o,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:c});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),d},l=async()=>{if(await QO(1e3),null!==a)return a;const o=iD(iD(r?"SDP_ENDPOINT_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN_BACKUP_LIST")).map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:o3(),serviceIds:[Mj.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Mj.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Mj.CLOUD_PROXY:Mj.CLOUD_PROXY_FALLBACK]}})),d=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),l=await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(UD.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),o.url),r?S3(o,o.serviceIds,e,r,i,t,n):R3(o,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},d),e[0]},promisesCollector:c});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},d),l};let u,h,p;try{({gatewayInfo:u,proxyInfo:h,url:p}=await O3([d(),l()]))}catch(e){throw e[0]}if(c.length&&c.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!u||!h)throw new dP(Xw.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=p,"disabled"!==e.cloudProxyServer&&Array.isArray(o)&&p){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(p)[1];Di(o).call(o,t)&&(e.proxyServer=t,UD.setProxyServer(t),cP.setProxyServer(t))}return a={gatewayInfo:u,proxyInfo:await i2(h,u.uid)},a}async function G3(e,t,n){const i=iD("UAP_AP").slice(0,iD("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=i.map((i=>function(e,t,n,i){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:XN,cname:t.cname,uid:t.uid.toString(),requestId:g3,seq:g3};g3+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return fN((async()=>{const t=await r3(e,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new dP(Xw.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw UD.error(e.toString()),e}const i=JSON.parse(t.json_body);if(200!==i.code){const e=new dP(Xw.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(i.code,", reason: ").concat(i.reason));throw UD.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new dP(Xw.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw UD.error(e.toString()),e}return{vid:i.vid,workerToken:i.workerToken,addressList:(iD("CHANNEL_MEDIA_RELAY_SERVERS")||i.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(iD("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==Xw.OPERATION_ABORTED&&e.code!==Xw.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),i)}(i,e,t,n)));try{const e=await O3(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function j3(e,t,n){let i=null;const r=[],o=async o=>{const s=iD(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 QO(1e3),null!==i)?i:await N3({fragementLength:iD("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(UD.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),i),function(e,t,n,i){const[r]=A3(t,[Mj.CHOOSE_SERVER]);let o=PO.networkState;return fN((async()=>{o&&PO.networkState===IO.OFFLINE&&PO.onlineWaiter&&await Wh.race([PO.onlineWaiter,QO(i&&i.maxRetryTimeout||EN.maxRetryTimeout)]),o=PO.networkState;const t=await r3(e,{data:r,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0);return C3(t,e)}),(()=>!1),(e=>e.code!==Xw.OPERATION_ABORTED&&(e.code===Xw.UPDATE_TICKET_FAILED?e.data.retry:(UD.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),i)}(i,e,t,n)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return i=await O3([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),i}catch(e){throw e[0]}}function W3(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function K3(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?W3(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):W3(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Y3 extends uO{get isSuccess(){return!!this.configs}constructor(e,t){super(),Db(this,"configs",void 0),Db(this,"store",void 0),Db(this,"joinInfo",void 0),Db(this,"cancelToken",void 0),Db(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),Db(this,"interval",void 0),Db(this,"mutex",void 0),Db(this,"mutableParamsRead",!1),Db(this,"configCache",{}),Db(this,"limit_bitrate",void 0),this.mutex=new pN("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),iD("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),iD("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;cP.reportApiInvoke(null,{options:void 0,name:_O.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:EO.TRACER}).onSuccess(JSON.stringify(oD))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void UD.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await x3(this.joinInfo,this.cancelToken,this.retryConfig),UD.debug("[config-distribute] get config distribute",JSON.stringify(e));const n=function(e){var t;const n=Jp(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<n.length;t++)for(let i=n.length-1;i>t;i--){const t=n[i],r=e[t].value;if("number"==typeof r.__priority){const o=r.__priority,s=n[i-1],a=e[s].value;if("number"==typeof a.__priority){if(!(o>a.__priority))continue;{const e=t;n[i]=n[i-1],n[i-1]=e}}else{const e=t;n[i]=n[i-1],n[i-1]=e}}}const i=Date.now(),r={};return n.forEach((t=>{const n=e[t].value.__expires;n&&n<=i||(r[t]=e[t])})),r}(e);this.cacheGlobalParameterConfig(n),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=n}catch(e){const t=new dP(Xw.NETWORK_RESPONSE_ERROR,e);UD.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){_x(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(px.UPDATE_BITRATE_LIMIT,e):this.emit(px.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&K3({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},n=Object.keys(e),i=[];n.forEach((n=>{const r=e[n].value;t[n]=r;const o=r.__id;if(o&&this.configCache[n]&&this.configCache[n].__id===o)return;const s=r.__type,a=e[n].value,c=e[n].tag;let d=0;s?s===rD.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(eD,e)||!JU()&&Object.prototype.hasOwnProperty.call(qN,e)?(d=1,!0):void 0)),i.push({tag:c,isApplied:d,feature:n,params:JSON.stringify(r)})})),i.forEach((e=>{let{tag:t,feature:n,params:i,isApplied:r}=e;this.store.sessionId&&cP.abTest(this.store.sessionId,{intSucc:1,isApplied:r,tag:t,feature:n,params:i,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){UD.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((n=>{const i=e[n].value,r=i.__expires,o=i.__type;Object.keys(i).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=K3(K3({value:i[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var n;const i=null===(n=t.LIMIT_BITRATE)||void 0===n?void 0:n.value;if(delete t.LIMIT_BITRATE,i&&_x(i)&&this.handleBitrateLimit(i),this.limit_bitrate=i,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((n=>{const{value:i,type:r,expires:o}=e[n];o&&o<=t||((r===rD.REALTIME||Object.prototype.hasOwnProperty.call(eD,n))&&(oD[n]=i,tD[n]=i,UD.debug("Update realtime parameters from config distribute",n,i)),r||JU()||!Object.prototype.hasOwnProperty.call(qN,n)||(oD[n]=i,tD[n]=i,UD.debug("Update gateway parameters from config distribute",n,i)))}))}catch(t){UD.error("Error update config immediately: ".concat(e),t.message)}}(t),function(e){try{var t;if(!iD("ENABLE_CONFIG_RESTORE"))return!1;const n=QD(e),i=window.localStorage.getItem(XD);if(!i)return!1;const r=JSON.parse(i),o=iD("BLOCKED_CONFIG_MAX_TIME");return Date.now()-r.timestamp>o?(sP(),!1):Di(t=r.configHashes).call(t,n)}catch(e){return UD.debug("[error] ".concat(YD," error checking blocked config:"),e),!1}}(t))return UD.debug("[warning] [config-distribute] blocked config detected and skipped"),void cP.reportAlarm(this.store.sessionId||null,{type:BD.CONFIG_DISTRIBUTE,status:FD.RECOVER,message:"Blocked config detected and skipped"});!function(e){try{const t=QD(e),n=$D();if(n.currentConfigHash&&n.currentConfigHash===t)return eP({currentConfigHash:t,configVerified:!0}),iP(),sP(),void UD.debug("".concat(YD," config verified as safe, skip further checks"));eP({currentConfigHash:t,configVerified:!1}),iP(),sP()}catch(e){UD.debug("[error] ".concat(YD," error on config applied:"),e)}}(t);const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),UD.debug("Caching global parameters ".concat(r))}catch(e){UD.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((n=>{switch(n){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(tD,n)){const{value:i,expires:r}=e[n];if(r&&r<=t)return;cN(tD[n],i)||(oD[n]=i,tD[n]=i,this.emit(px.UPDATE_CLIENT_ROLE_OPTIONS,i),UD.debug("Updating client role options: ".concat(JSON.stringify(i))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(tD,n)){var i;const{value:r,expires:o}=e[n];if(o&&o<=t)return;"number"==typeof r&&Di(i=[0,1,4,5,6,7,8,9]).call(i,r)&&(oD[n]={value:r},tD[n]=r,this.emit(px.UPDATE_REMOTE_VIDEO_STREAM_TYPE,r),UD.debug("Updating client remote stream type: ".concat(JSON.stringify(r))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(tD,n)){const{value:i,expires:r}=e[n];if(r&&r<=t)return;cN(tD[n],i)||(oD[n]=i,tD[n]=i,this.emit(px.FALLBACK_TO_HLS,i),UD.debug("Updating enable force hls: ".concat(JSON.stringify(i))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(tD,n)){const{value:i,expires:r}=e[n];if(r&&r<=t)return;cN(tD[n],i)||(oD[n]=i,tD[n]=i,this.emit(px.UPDATE_VOS_CONFIGURE,i),UD.debug("Updating vos configure: ".concat(JSON.stringify(i))))}}}))}catch(e){UD.error("Error handling global parameter config:",e.message)}}}class H3 extends uO{constructor(){super(...arguments),Db(this,"resultStorage",new Map)}setLocalAudioStats(e,t,n){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(n,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(n,t))}setLocalVideoStats(e,t,n){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(n,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(n,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(n)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(n))}setRemoteAudioStats(e,t){const n=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",n,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const n=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",n,this.checkVideoDecode(t))}record(e,t,n){if(iD("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const i=this.resultStorage.get(e);if(!i)return;i.result.push(n);const r="VIDEO_ENCODE_FAILED"===e?iD("ENCODE_EXCEPTION_TIMES"):5;if(i.result.length>=r){var o;const n=Di(o=i.result).call(o,!0);i.isPrevNormal&&!n&&this.emit("exception",X3[e],e,t),!i.isPrevNormal&&n&&this.emit("exception",X3[e]+2e3,e+"_RECOVER",t),i.isPrevNormal=n,i.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof Kk&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let n=null;t._encoderConfig&&t._encoderConfig.frameRate&&(n=$1(t._encoderConfig.frameRate));const i=e.captureFrameRate;return!n||!i||!(n>10&&i<5||n<10&&n>=5&&i<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){var t;return!(!e.codecType||Di(t=iD("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 Kk&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const X3={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 J3=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 n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function z3(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Z3(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?z3(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z3(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class q3{constructor(e){Db(this,"store",void 0),Db(this,"onStatsException",void 0),Db(this,"onUploadPublishDuration",void 0),Db(this,"onStatsChanged",void 0),Db(this,"onVideoCodecChanged",void 0),Db(this,"localStats",new Map),Db(this,"remoteStats",new Map),Db(this,"updateStatsInterval",void 0),Db(this,"trafficStats",void 0),Db(this,"trafficStatsPeerList",[]),Db(this,"uplinkStats",void 0),Db(this,"exceptionMonitor",void 0),Db(this,"p2pChannel",void 0),Db(this,"scalabilityMode",VN.L1T1),Db(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new H3,this.exceptionMonitor.on("exception",((e,t,n)=>{this.onStatsException&&this.onStatsException(e,t,n)}))}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(Rx.LocalAudioTrack)||Z3({},XP)}getLocalVideoTrackStats(){return this.localStats.get(Rx.LocalVideoTrack)||Z3({},JP)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.audioStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{audioStats:r}]=e;r&&(n[i]=t(i,r))}));return n}getRemoteNetworkQualityStats(e){const t={};if(e){var n;const i=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.networkStats;i&&(t[e]=i)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{networkStats:i}]=e;i&&(t[n]=i)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=t2(this.trafficStats.B_unq),t=t2(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.videoStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{videoStats:r}]=e;r&&(n[i]=t(i,r))}));return n}getRTCStats(){let e=0,t=0,n=0,i=0;const r=this.localStats.get(Rx.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(Rx.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(Rx.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(n+=t.receiveBytes,i+=t.receiveBitrate),r&&(n+=r.receiveBytes,i+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:n,RecvBitrate:i,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 n=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),i=null!=n&&n.videoSSRC?J3.measureFromSubscribeStart(this.store.clientId,n.videoSSRC):0,r=null!=n&&n.audioSSRC?J3.measureFromSubscribeStart(this.store.clientId,n.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,i>r?i:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&UD.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,n){if(!e)return!1;const i=!!n&&t.framesDecodeFreezeTime>n.framesDecodeFreezeTime,r=!n||t.framesDecodeCount>n.framesDecodeCount;return i||!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[n,i]=t;switch(n){case Rx.LocalVideoTrack:case Rx.LocalVideoLowTrack:{const t=i,s=Z3({},JP),a=e.getStats(),c=e.getLocalMedia(n);if(a){const n=a.videoSend.find((e=>e.ssrc===(null==c?void 0:c.ssrcs[0].ssrcId)));if(n){const i=e.getLocalVideoSize(),o=e.getEncoderConfig(Rx.LocalVideoTrack);var r;if("H264"===n.codec||"H265"===n.codec||"VP8"===n.codec||"VP9"===n.codec||"AV1X"===n.codec||"AV1"===n.codec)if(s.codecType=n.codec,(null==t?void 0:t.codecType)!==n.codec)null===(r=this.onVideoCodecChanged)||void 0===r||r.call(this,n.codec.toLocaleLowerCase());s.sendBytes=n.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,n.inputFrame?(s.captureFrameRate=n.inputFrame.frameRate,s.captureResolutionHeight=n.inputFrame.height,s.captureResolutionWidth=n.inputFrame.width):i&&(s.captureResolutionWidth=i.width,s.captureResolutionHeight=i.height),n.sentFrame?(s.sendFrameRate=n.sentFrame.frameRate,s.sendResolutionHeight=n.sentFrame.height,s.sendResolutionWidth=n.sentFrame.width):i&&(s.sendResolutionWidth=i.width,s.sendResolutionHeight=i.height),n.avgEncodeMs&&(s.encodeDelay=n.avgEncodeMs),o&&o.bitrateMax?s.targetSendBitrate=1e3*o.bitrateMax:n.targetBitrate&&(s.targetSendBitrate=n.targetBitrate),s.sendPackets=n.packets,s.sendPacketsLost=n.packetsLost,s.sendJitterMs=n.jitterMs,s.sendRttMs=n.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(n)&&(s.totalFreezeTime+=1),n.scalabilityMode&&this.scalabilityMode!==n.scalabilityMode&&(UD.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(n.scalabilityMode)),this.scalabilityMode=n.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var o;if(this.localStats.set(n,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 Rx.LocalAudioTrack:{const t=i,r=Z3({},XP),o=e.getStats(),s=e.getLocalMedia(n);if(o){const n=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(n){if("opus"!==n.codec&&"aac"!==n.codec&&"PCMU"!==n.codec&&"PCMA"!==n.codec&&"G722"!==n.codec||(r.codecType=n.codec),n.inputLevel)r.sendVolumeLevel=Math.round(32767*n.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=n.bytes,r.sendPackets=n.packets,r.sendPacketsLost=n.packetsLost,r.sendJitterMs=n.jitterMs,r.sendRttMs=n.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(Rx.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var n,i;let[r,{videoStats:o,audioStats:s,videoPcStats:a}]=t;const c=s,d=o,l=a,u=Z3({},zP),h=Z3({},qP),p=Z3({},ZP),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let g;g=this.store.useP2P?e.getStats(!0):e.getStats();const S=null===(n=g)||void 0===n?void 0:n.audioRecv.find((e=>e.ssrc===m)),T=null===(i=g)||void 0===i?void 0:i.videoRecv.find((e=>e.ssrc===f)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(S&&("opus"!==S.codec&&"aac"!==S.codec&&"PCMU"!==S.codec&&"PCMA"!==S.codec&&"G722"!==S.codec||(u.codecType=S.codec),S.outputLevel?u.receiveLevel=Math.round(32767*S.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=S.bytes,u.receivePackets=S.packets,u.receivePacketsLost=S.packetsLost,u.receivePacketsDiscarded=S.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=S.jitterBufferMs,u.totalDuration>10&&q3.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),T){"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),h.receiveDelay=T.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f),n=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;var v;if(h.totalDuration=d?d.totalDuration+1:1,1===iD("REMOTE_VIDEO_FREEZE_TIME_VERSION"))E&&t&&E._player&&(h.totalFreezeTime=E._player.totalFreezeTime/1e3);else h.totalFreezeTime=null!==(v=T.totalFreezesDuration)&&void 0!==v?v:n||0,void 0===T.totalFreezesDuration&&E&&t&&q3.isRemoteVideoFreeze(E,T,l)&&(h.totalFreezeTime+=1);h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-n)/(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 Q3{constructor(){Db(this,"destChannelMediaInfos",new Map),Db(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){ex(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){ex(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){KV(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function $3(e){if(!(e instanceof Q3)){return new dP(Xw.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfo();if(!t){return new dP(Xw.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===n.size){return new dP(Xw.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class e5{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){Db(this,"uid",void 0),Db(this,"_uintid",void 0),Db(this,"_trust_in_room_",!0),Db(this,"_trust_audio_enabled_state_",!0),Db(this,"_trust_video_enabled_state_",!0),Db(this,"_trust_audio_mute_state_",!0),Db(this,"_trust_video_mute_state_",!0),Db(this,"_audio_muted_",!1),Db(this,"_video_muted_",!1),Db(this,"_audio_enabled_",!0),Db(this,"_video_enabled_",!0),Db(this,"_audio_added_",!1),Db(this,"_video_added_",!1),Db(this,"_is_pre_created",!1),Db(this,"_video_pre_subscribed",!1),Db(this,"_audio_pre_subscribed",!1),Db(this,"_trust_video_stream_added_state_",!0),Db(this,"_trust_audio_stream_added_state_",!0),Db(this,"_audioTrack",void 0),Db(this,"_videoTrack",void 0),Db(this,"_dataChannels",[]),Db(this,"_audioSSRC",void 0),Db(this,"_videoSSRC",void 0),Db(this,"_audioOrtc",void 0),Db(this,"_videoOrtc",void 0),Db(this,"_cname",void 0),Db(this,"_rtxSsrcId",void 0),Db(this,"_videoMid",void 0),Db(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function t5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function n5(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?t5(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t5(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const i5=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"),r5="9",o5=2e4,s5=4e4;let a5=class{get localCapabilities(){return GO(this._localCapabilities)}get rtpCapabilities(){return GO(this._rtpCapabilities)}get candidates(){return GO(this._candidates)}get iceParameters(){return GO(this._iceParameters)}get dtlsParameters(){return GO(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];Db(this,"sessionDesc",void 0),Db(this,"_localCapabilities",void 0),Db(this,"_rtpCapabilities",void 0),Db(this,"_candidates",void 0),Db(this,"_originCandidates",void 0),Db(this,"_iceParameters",void 0),Db(this,"_isUseExtmapAllowMixed",void 0),Db(this,"_isUseLocalCodecs",void 0),Db(this,"_isUseDataChannel",void 0),Db(this,"_dtlsParameters",void 0),Db(this,"setup",void 0),Db(this,"currentMidIndex",void 0),Db(this,"cname",void 0),Db(this,"useLocalCodecsMids",[]),Db(this,"preloadSsrcs",[]),Db(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=n,this._isUseDataChannel=i,e=GO(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=GO(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 Di(t=this.preloadSsrcs).call(t,e)}))}preloadRemoteMedia(e){let t=0;const n=[],i=[];for(;e>0;){const r=[n5({ssrcId:s5+t},iD("USE_SUB_RTX")?{rtx:s5+t+1}:{})],o="".concat(s5+t,"_").concat(o5+t),{ssrcs:s,ssrcGroups:a}=C2(r,this.cname,iD("SYNC_GROUP")?o:void 0),c=this.preCreateOrRecycleSendMedia("video",s,a,void 0),d=[{ssrcId:o5+t}],l="".concat(s5+t,"_").concat(o5+t),{ssrcs:u,ssrcGroups:h}=C2(d,this.cname,iD("SYNC_GROUP")?l:void 0),p=this.preCreateOrRecycleSendMedia("audio",u,h,void 0);e--,t+=2,n.push(c,p),i.push(s[0].ssrcId,u[0].ssrcId)}return this.useLocalCodecsMids.push(...n),this.preloadSsrcs=i,{mids:n,preSSRCs:i,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,n,i){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;UD.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===fx.VIDEO?o.videoCodecs:o.audioCodecs,a=e===fx.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:r5,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:n,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,i),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return ED(this.sessionDesc)}send(e,t,n,i){const{ssrcs:r,ssrcGroups:o}=C2(t,this.cname,iD("SYNC_GROUP")?n:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Tw()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),i&&(i.twcc||i.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,i),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let n;return-1===t||1===t&&(mw()||function(){const e=lw();return!(e.name!==sw.CHROME||!e.osVersion)&&Number(e.version)<=90}()||vw(143)||bw(143)||iD("RESERVE_MID_1_MLINE")||iD("ENABLE_ENCODED_TRANSFORM")&&Ew())||0===t&&!function(e){const t=lw();return!(t.name!==sw.FIREFOX||!t.osVersion)&&Number(t.version)===e}(138)&&iD("USE_SUB_RTX")||Pw()?(n=this.createOrRecycleSendMedia(e,r,o,"sendonly",i),this.updateBundleMids()):(n=GO(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=r,n.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,i)),Tw()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,n.attributes.mid),{mid:n.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:n,mslabel:i}=e;return this.send(t,n,i)})),n=[];let i=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(i=!0),n.push(t)})),{mids:n,needExchangeSDP:i}}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||Tw()||Pw()?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=>Di(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=>Di(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,n,i){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,n,i[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||_D((n=this._isUseExtmapAllowMixed,this._isUseDataChannel?i5(n):"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(n?"\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 n;this._rtpCapabilities=e;let i=!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||!Di(u=this.useLocalCodecsMids).call(u,e.attributes.mid)){if(i=!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||Di(h=this.useLocalCodecsMids).call(h,t)||this.useLocalCodecsMids.push(t)}else if(0===r.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Di(n=t.encodingName.toLowerCase()).call(n,"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||Di(p=this.useLocalCodecsMids).call(p,t)||this.useLocalCodecsMids.push(t)}else if(0===r.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Di(n=t.encodingName.toLowerCase()).call(n,"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,U2(e)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,i]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(n5(n5({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case gx.TCP_RELAY:this._candidates=n;break;case gx.UDP_TCP_RELAY:case gx.RELAY:this._candidates=[...t,...n];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=GO(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((n=>{n.attributes.iceUfrag===e.iceUfrag&&n.attributes.icePwd===e.icePwd||(t=!0),n.attributes.iceUfrag=e.iceUfrag,n.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const i=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(Tw()){if(i){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 i}))}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:r5,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,n,i,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=V2(s,a,this.localCapabilities.send,s===fx.VIDEO?i:r),d=s===fx.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:r5,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:n,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))),n=new Set(e.map((e=>e.fingerprint)));let i=!1;t.size!==n.size&&(i=!0);for(const e of t)n.has(e)||(i=!0);return i}updateRemoteCodec(e,t,n){const i=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Di(t=Object.keys(aD)).call(t,e)})))],r=new Set(t);if(i.every((e=>r.has(e))))return UD.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 n;return Di(n=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(n,t)}))));if(0===o.length)return UD.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(i," codecs: ").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let a;if(UD.debug("updateRemoteCodec, from ".concat(i," 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&&Di(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return UD.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(iD("USE_PUB_RTX")||iD("USE_SUB_RTX")){const e=x2(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=V2(fx.VIDEO,d,c,n);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));UD.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),UD.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,n,i,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===fx.VIDEO?s.videoCodecs:s.audioCodecs,c=e===fx.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:r5,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:n,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.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,n){const i=GO(e);return I2(i),b2(i,t),A2(i,t),w2(i),O2(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=GO(e);return n.attributes&&n.attributes.payloads&&Array.isArray(n.attributes.payloads)&&n.attributes.payloads.length>0&&n.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&iD("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),O2(n,t,this.localCapabilities.recv),U2(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Tw()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}};function c5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function d5(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c5(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c5(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var l5=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(l5||{});const u5=new Map;function h5(e,t,n,i){let{scale:r}=e;if(0===r&&i===l5.UP||r>=t.length-1&&i===l5.DOWN)return e;let o=d5(d5({},e),{},{scale:i===l5.DOWN?++r:--r});switch(n){case"maintain-framerate":o=d5(d5({},o),t[r].motion);break;case"maintain-resolution":o=d5(d5({},o),t[r].detail);break;case"balanced":o=d5(d5({},o),t[r].balanced)}return o}function p5(e,t){if(t){const n={overUse:0,underUse:0,adaptationList:_5(t)};u5.set(e,n)}else u5.delete(e)}function _5(e){const t=d5({},e),{bitrateMax:n,frameRate:i,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:g,MOTION_BITRATE_FACTOR:S,DETAIL_FRAMERATE_FACTOR:T,DETAIL_BITRATE_FACTOR:R}=QN,v=Math.min(t.frameRate,a),y=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(p,1)*v),fps_up:i},balanced:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(u,e)*n),bwe_down:Math.round(Math.pow(h,e+1)*n),fps_up:Math.round(Math.pow(_,e)*v),fps_down:Math.round(Math.pow(p,e+1)*v)},a={scaleResolutionDownBy:r/Math.pow(f,e),frameRate:Math.max(Math.round(Math.pow(m,e)*i),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:r/Math.pow(g,e),frameRate:i,bitrateMax:Math.max(Math.round(Math.pow(S,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(S,e)*o),d)},C={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(T,e)*i),s),bitrateMax:Math.max(Math.round(Math.pow(R,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};y.push({scale:e,threshold:t,balanced:a,motion:c,detail:C})}return y}function E5(e,t,n,i,r,o){const s=u5.get(e)||{overUse:0,underUse:0,adaptationList:_5(r)},{adaptationList:a}=s;u5.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=QN,{scale:l}=i;let u,h;return"number"==typeof t&&t>0&&function(e,t,n,i){if(t>=n.length)return!1;let{threshold:{fps_down:r}}=n[t];return iD("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[0].threshold.fps_down),e<r}(t,l,a,o)&&(s.overUse++,h=UN.CPU,s.overUse>c)||"number"==typeof n&&n>0&&function(e,t,n){if(t>=n.length)return!1;const{threshold:{bwe_down:i}}=n[t];return e<i}(n,l,a)&&(s.overUse++,h=UN.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=h5(i,a,o,l5.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof n&&n>0&&function(e,t,n,i){if(0===t)return;let{threshold:{fps_up:r}}=n[t];return iD("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,n){if(0===t)return;const{threshold:{bwe_up:i}}=n[t];return e>i}(n,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=h5(i,a,o,l5.UP),0===u.scale&&(h=UN.NONE))),[u,h])}function m5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function f5(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?m5(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m5(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function g5(e){var t;return!!iD("ENABLE_AG_ADAPTATION")&&(!!(e instanceof UM||Di(t=e._hints).call(t,xP.CUSTOM_TRACK))&&(!!iD("FORCE_SUPPORT_AG_ADAPTATION")||!!(ww(14,0,!1)&&Ow(17,4,!0)||Aw(14)&&Nw(17,4,!0))))}const S5=new Map;function T5(e,t,n,i,r,o){if(R5(e,n),r(t),"balanced"!==i&&"maintain-framerate"!==i&&"maintain-resolution"!==i)return;let s=-1;p5(e,t);const a=window.setInterval((()=>{const a=S5.get(e);if(!iD("ENABLE_AG_ADAPTATION")||!a)return R5(e,n),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]=E5(e,o,d,a.adaptationConfig,t,i);u&&(n.qualityLimitationReason=u),l&&a.adaptationConfig.scale!==l.scale&&(UD.debug("[".concat(e,"] applyAdaptation: ").concat(n.qualityLimitationReason,"\n           sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(l.scale," ")),a.adaptationConfig=f5(f5({},a.adaptationConfig),l),r(l))}}),iD("CHECK_LOCAL_STATS_INTERVAL")),c=f5({},t);S5.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),UD.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(i))}function R5(e,t){const n=S5.get(e);if(n){const{timer:t}=n;window.clearTimeout(t),S5.delete(e)}t.qualityLimitationReason=UN.NONE,p5(e)}function v5(e,t){var n;let i;switch(t){case Rx.LocalAudioTrack:i=ox.Audio;break;case Rx.LocalVideoTrack:i=Di(n=e._hints).call(n,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:i=ox.Low}return i}function y5(e){const t=uP();if(e.some((e=>e._bypassWebAudio)))throw new Jw(Xw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new Jw(Xw.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function C5(e,t){y5(e);const n=t||new Kk;return e.forEach((e=>n.addAudioTrack(e))),n}const b5=!uP().supportUnifiedPlan||iD("CHROME_FORCE_PLAN_B")&&Bw();function I5(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return n={spec:t,store:e},X2("DataChannelConnection").create(n);var n;const i=b5?function(e){return X2("PlanBConnection").create(e)}({spec:t,store:e}):new P5(t,e);return i}function A5(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function w5(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(SO(e.turnServer.servers))return!1;if(iD("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var O5;function N5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function D5(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?N5(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N5(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let P5=(O5=class e extends mx{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 Di(t=Object.keys(aD)).call(t,e)})))]}constructor(t,n){super(t,n),Db(this,"id",$O(5,"connection-")),Db(this,"store",void 0),Db(this,"peerConnection",void 0),Db(this,"forceTurn",!1),Db(this,"remoteSDP",void 0),Db(this,"initialOffer",void 0),Db(this,"transportEventReceiver",void 0),Db(this,"statsFilter",void 0),Db(this,"extension",{useXR:iD("USE_XR")}),Db(this,"localCapabilities",void 0),Db(this,"remoteCodecs",void 0),Db(this,"localCandidateCount",0),Db(this,"allCandidatesReceived",!1),Db(this,"isPreallocation",!1),Db(this,"isPreRender",!1),Db(this,"preMediaMap",new Map),Db(this,"dataStreamChannelMap",new Map),Db(this,"establishPromise",void 0),Db(this,"recoveredDataChannelIds",[]),Db(this,"currentDataChannelId",1),Db(this,"supportAV1RtpSpec",!1),Db(this,"mutex",void 0),Db(this,"qualityLimitationReason",UN.NONE),Db(this,"isFirstConnected",!1),this.store=n,this.forceTurn=w5(t),this.mutex=new pN("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=KN(this.peerConnection,iD("STATS_UPDATE_INTERVAL"),void 0,Tw()?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 UD.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 n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else UD.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 n=S2(t.sdp),i=await P2({filterRTX:!iD("USE_PUB_RTX")&&!iD("USE_SUB_RTX"),filterVideoFec:iD("FILTER_VIDEO_FEC"),filterAudioFec:iD("FILTER_AUDIO_FEC"),filterVideoCodec:iD("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:iD("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:iD("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=M2(i),this.initialOffer=t,iD("ENABLE_SVC")&&"av1"==this.store.codec){const t=await D2();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&W2(t.sdp)&&(r=GO(i),l2(r)),D5(D5({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new Jw(Xw.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&W2(this.initialOffer.sdp)&&u2(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new a5(D5(D5({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!iD("ENABLE_PRE_SUB_WITH_PRE_PC")||!iD("PRE_USE_LOCAL_CODECS"))&&EP(this.store)),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),_P()&&EP(this.store)){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=iD("PRE_SUB_NUM")||1,i=e>n?e:n,{mids:r,preSSRCs:o}=this.remoteSDP.preloadRemoteMedia(i),s=B2(this.initialOffer.sdp,this.extension),a=this.logSDPExchange(s||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:s}),null==a||a(s),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const c=await this.peerConnection.createOffer(),d=this.logSDPExchange(c.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(c);const l=this.remoteSDP.toString();null==d||d(l),await this.peerConnection.setRemoteDescription({type:"answer",sdp:l}),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(o)),this.presetMedia(r,o);const u=this.peerConnection.getTransceivers()[0];null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver)}else{const t=this.remoteSDP.toString(),i=B2(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),EP(this.store))if(e.preallocation&&iD("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=iD("PRE_SUB_NUM")||1,i=e>t?e:t,{mids:r,preSSRCs:o}=this.remoteSDP.preloadRemoteMedia(i);await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(o)),this.presetMedia(r,o)}else{const{preSSRCs:t=[]}=e,n=t.map((e=>e.ssrcMsg[0].ssrcId));if(0===t.length)return;const{mids:i}=this.remoteSDP.batchSend(t.map((e=>Object.assign({},e))));await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(i,n)}}}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const s=i.receiver.track;if(iD("PRE_PLAYOUT_DELAY_HINT")){const e=i.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=iD("PRE_PLAYOUT_DELAY_HINT"),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(iD("PRE_PLAYOUT_DELAY_HINT"))))}let a;if("video"===s.kind&&iD("ENABLE_PRE_RENDER")){var r,o;let e=null===(r=this.store.preSubOptions)||void 0===r||null===(r=r[n])||void 0===r?void 0:r.element;const i=(null===(o=this.store.preSubOptions)||void 0===o||null===(o=o[n])||void 0===o?void 0:o.config)||{};UD.debug("try to play pre sub video","string"==typeof e?e:"element","config: ".concat(JSON.stringify(i))),"string"==typeof e&&(e=document.getElementById(e)||void 0),a=e instanceof HTMLVideoElement?new Jk(D5({trackId:"track-".concat(s.kind,"-unknown-").concat(this.store.clientId,"_").concat($O(5,"")),element:e},i)):new Zk(D5({trackId:"track-".concat(s.kind,"-unknown-").concat(this.store.clientId,"_").concat($O(5,"")),element:e},i),!e),a.updateVideoTrack(s),a.onFirstVideoFrameRender=()=>{var e;a&&(a.onFirstVideoFrameRender=void 0);const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},a.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},a.play(this.store.sessionId||void 0),this.isPreRender=!0}this.preMediaMap.set(t[n],{mid:e,track:s,player:a,transceiver:i})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1;const{rtpCapabilities:n}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(n),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const{preSSRCs:i=[]}=e,r=i.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(r)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((n=>{let[i,{mid:r,player:o,track:s}]=n;return e.push(r),t.push(i),this.preMediaMap.delete(i),o&&o.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await F2(this.peerConnection,this.remoteSDP,this.extension),UD.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),cP.reportApiInvoke(this.store.sessionId,{name:_O.PRELOAD_MEDIA_FAILED,options:[i,t],tag:EO.TRACER}).onSuccess()),i.length>0){const{mids:e}=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e))));await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(r)),this.presetMedia(e,r)}}t?(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):UD.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return EA((function*(){const r=yield mA(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=c2();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,D5({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),Tw()&&!0===iD("SIMULCAST")&&(yield mA(i.applySimulcastForFirefox(o,e)));const a=yield mA(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=_D(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 T2(t,iD("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield mA(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(i.applySimulcastEncodings(o,e)),yield mA(i.applySendEncodings(o,e)),null==_||_(p),yield mA(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof Jw?e:new Jw(Xw.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 n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)UD.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");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:iD("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const{needExchangeSDP:i}=this.remoteSDP.sendDataChannel();if(i){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),UD.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else UD.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof Jw?e:new Jw(Xw.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(Xw.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=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;R5(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),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(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){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,n,i);o&&(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.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.");if(iD("PRE_PLAYOUT_DELAY_HINT")){const t=s.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=iD("PRE_PLAYOUT_DELAY_HINT"),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(iD("PRE_PLAYOUT_DELAY_HINT"))))}return{track:s.receiver.track,id:r,transceiver:s}}catch(e){throw new Jw(Xw.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:n}=this.remoteSDP.batchSend(e);return n&&(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.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.");if(iD("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=iD("PRE_PLAYOUT_DELAY_HINT"),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(iD("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new Jw(Xw.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[n,{mid:i,player:r}]=t;if(i===e)return this.preMediaMap.delete(n),r&&r.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.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(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.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(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),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==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return EA((function*(){const n=yield mA(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=uP().supportPCSetConfiguration,r=iD("FORCE_TURN_TCP")||t.forceTurn;if(e===gx.RELAY&&!i)return;if(i&&!r){const n=e===gx.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(UD.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield mA(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=S2(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 mA(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield mA(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){UD.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(gx.TCP_RELAY),await F2(this.peerConnection,this.remoteSDP,this.extension)}catch(e){UD.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{R5(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 D5(D5({},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 n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?Tw()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.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:n,remote:i}=t.getSelectedCandidatePair();return{local:D5(D5({},wN),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:D5(D5({},wN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.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 n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=s2(e.url||"");UD.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&UD.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,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),iD("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 n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(SO(t.turnServer.servers)?n.iceServers=t.turnServer.servers:iD("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(iD("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),iD("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),iD("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),iD("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),iD("ENABLE_ENCODED_TRANSFORM")&&uP().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}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(Z1(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!iD("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 n=iD("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Z1(e.turnServerURL),":443?transport=tcp")}):4===n&&(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(Z1(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 n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const{local:e,remote:t}=n.getSelectedCandidatePair()||{};if(e&&t){const n=e.address+":"+e.port,i=t.address+":"+t.port;UD.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(s2(n)),", remote ").concat(JSON.stringify(s2(i))))}}}))}}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 n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return UD.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return UD.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!uP().supportSetRtpSenderParameters)return UD.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=a2(this.peerConnection,e._mediaStreamTrack),a=qL(e);if(g5(e)&&s&&t&&a&&this.getLocalVideoStats&&Di(n=["vp8","vp9"]).call(n,this.store.codec)){var c;const n=r.degradationPreference||(Di(c=e._hints).call(c,xP.CUSTOM_TRACK)?iD("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");T5(this.id+s.mid,a,this,n,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const{bitrateMax:t,frameRate:n,scaleResolutionDownBy:i}=e._encoderConfig;t&&(o.maxBitrate=1e3*t),(Di(d=e._hints).call(d,xP.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(o.maxFramerate=$1(n)),i&&i>=1&&(o.scaleResolutionDownBy=i))}const{maxFramerate:l}=iD("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),iD("DSCP_TYPE")&&Bw()){var u;const e=iD("DSCP_TYPE");Di(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(i=h.encodings)||void 0===i?void 0:i[0];Tw()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),UD.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await j2(this.store.codec,t,iD("SVC_MODE"))}async updateAdaptation(e,t){var n,i;if(!e)return UD.debug("[updateAdaptation] no rtpSender found");if(!uP().supportSetRtpSenderParameters)return UD.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=$1(s)),a&&a>=1&&Di(n=["vp8","vp9"]).call(n,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),UD.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?UD.debug("[updateAdaptation] peerConnection not connected}"):UD.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):UD.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!uP().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof MM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){UD.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){if(iD("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=_D(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(b2(o,e),N2(o,e,this.store.codec))})),ED(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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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 n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof MM&&!Di(n=d._hints).call(n,xP.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.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 n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!Tw()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof MM&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._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,n,i,r,o;return!!(e instanceof MM&&iD("SIMULCAST")&&"vp8"===this.store.codec&&!Di(t=e._hints).call(t,xP.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.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,n,i){if(iD("SDP_LOGGING"))return UD.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}: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(uP().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},DV(O5.prototype,"updateRemoteRTPCapabilities",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"updateRemoteRTPCapabilities"),O5.prototype),DV(O5.prototype,"connect",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"connect"),O5.prototype),DV(O5.prototype,"updateRemoteConnect",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"updateRemoteConnect"),O5.prototype),DV(O5.prototype,"createDataChannels",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"createDataChannels"),O5.prototype),DV(O5.prototype,"receive",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"receive"),O5.prototype),DV(O5.prototype,"batchReceive",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"batchReceive"),O5.prototype),DV(O5.prototype,"stopReceiving",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"stopReceiving"),O5.prototype),DV(O5.prototype,"muteRemote",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"muteRemote"),O5.prototype),DV(O5.prototype,"unmuteRemote",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"unmuteRemote"),O5.prototype),DV(O5.prototype,"muteLocal",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"muteLocal"),O5.prototype),DV(O5.prototype,"unmuteLocal",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"unmuteLocal"),O5.prototype),DV(O5.prototype,"close",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"close"),O5.prototype),DV(O5.prototype,"updateEncoderConfig",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"updateEncoderConfig"),O5.prototype),DV(O5.prototype,"updateSendParameters",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"updateSendParameters"),O5.prototype),DV(O5.prototype,"replaceTrack",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"replaceTrack"),O5.prototype),DV(O5.prototype,"updateAdaptation",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"updateAdaptation"),O5.prototype),DV(O5.prototype,"getRemoteSSRC",[L5],Object.getOwnPropertyDescriptor(O5.prototype,"getRemoteSSRC"),O5.prototype),O5);function L5(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}function k5(e,t){let n=document.createElement("video"),i=document.createElement("canvas");n.setAttribute("style","display:none"),i.setAttribute("style","display:none"),n.setAttribute("muted",""),n.muted=!0,n.setAttribute("autoplay",""),n.autoplay=!0,n.setAttribute("playsinline",""),i.width=$1(t.width),i.height=$1(t.height);const r=$1(t.framerate||15);document.body.append(n),document.body.append(i);let o=e._mediaStreamTrack;n.srcObject=new MediaStream([o]),n.play().catch(tN);const s=i.getContext("2d");if(!s)throw new dP(Xw.UNEXPECTED_ERROR,"can not get canvas context");const a=uP(),c=i.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=i),i.startCapture=()=>{if(!n)return i.stopCapture&&i.stopCapture();if(n.paused&&n.play(),n.videoHeight>2&&n.videoWidth>2){const e=n.videoWidth,t=n.videoHeight/e,r=i.width*t;Math.abs(r-i.height)>=2&&(UD.debug("adjust low stream resolution","".concat(i.width,"x").concat(i.height," -> ").concat(i.width,"x").concat(r)),i.height=r)}s.drawImage(n,0,0,i.width,i.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,n.srcObject=new MediaStream([o]))},i.stopCapture=SL((()=>i.startCapture&&i.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),n&&(n.remove(),n.srcObject=null,n=null),i&&(i.width=0,i.remove(),i.stopCapture&&i.stopCapture(),i.startCapture=void 0,i.stopCapture=void 0,i=null),UD.debug("clean low stream renderer")},c}var M5=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(M5||{}),U5=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_Send_Codec=2240]="Video_Send_Codec",e[e.Video_Send_Power_Efficient_Encoder=2241]="Video_Send_Power_Efficient_Encoder",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Recv_Codec=2242]="Video_Recv_Codec",e[e.Video_Recv_Power_Efficient_Decoder=2243]="Video_Recv_Power_Efficient_Decoder",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}(U5||{}),V5=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}(V5||{}),x5=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}(x5||{}),F5=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}(F5||{}),B5=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(B5||{}),G5=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(G5||{});const j5=1e3,W5=6,K5=3,Y5=Math.max(W5,K5,60);function H5(e){return e=e.toLowerCase(),Di(e).call(e,"vp8")?1:Di(e).call(e,"h264")?2:Di(e).call(e,"vp9")?3:Di(e).call(e,"av1")?4:Di(e).call(e,"h265")?5:0}function X5(e,t,n){null!=n&&Number.isFinite(n)&&(e[t]=Math.round(Math.max(0,n)))}function J5(e){const t={[F5.CONN_TYPE]:0,[F5.RTT]:e.rtt,[F5.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const n=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===n&&(t[F5.CONN_TYPE]=1),"tcp"===n&&(t[F5.CONN_TYPE]=3),"tls"===n&&(t[F5.CONN_TYPE]=4);break}case"srflx":t[F5.CONN_TYPE]=2;break;case"unknown":t[F5.CONN_TYPE]=5;break;default:t[F5.CONN_TYPE]=0}return t}function z5(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 Z5 extends uO{constructor(e){super(),Db(this,"store",void 0),Db(this,"uploadWRTCStatsTimer",void 0),Db(this,"uploadOutboundDenoiserStatsTimer",void 0),Db(this,"uploadExtStatsTimer",void 0),Db(this,"uploadExtUsageStatsTimer",void 0),Db(this,"uploadInboundExtStatsTimer",void 0),Db(this,"requestStats",void 0),Db(this,"requestTransportStats",void 0),Db(this,"requestLocalMedia",void 0),Db(this,"requestRemoteMedia",void 0),Db(this,"requestAllTracks",void 0),Db(this,"requestVideoIsReady",void 0),Db(this,"requestUploadStats",void 0),Db(this,"requestUpload",void 0),Db(this,"uploadOutboundStarted",!1),Db(this,"uploadInboundStarted",!1),Db(this,"uploadTransportStarted",!1),Db(this,"uploadBaseStatsStarted",!1),Db(this,"uploadExtensionUsageStarted",!1),Db(this,"lastRecvStats",void 0),Db(this,"lastSendStats",void 0),Db(this,"lastRefRecvStats",void 0),Db(this,"lastRefSendStats",void 0),Db(this,"lastNormalRecvStats",void 0),Db(this,"lastNormalSendStats",void 0),Db(this,"lastExtendStats",{}),Db(this,"needUploadStats",{}),Db(this,"needUploadRenderFreezeTime",!0),Db(this,"lastUploadCompensateTime",-1),Db(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%K5==0,n=e%W5==0,i=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,n?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,i);e&&(a.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const i=this.getInboundStats(o,n?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);i&&(a.inbound=i)}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[B5.RTC_PEER_CONNECTION_STATE]=xN[c]):a.misc=[{addition:{[B5.RTC_PEER_CONNECTION_STATE]:xN[c]}}]),tU.needUploadStats.length>0||n){const e=tU.needUploadStats.shift()||("visible"===tU.visibility?1:0);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[B5.PAGE_VISIBILITY]=e):a.misc=[{addition:{[B5.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[M5.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,n&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,tU.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,n;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(n=this.requestUploadStats)||void 0===n||n.call(this,{misc:[{addition:{[B5.RTC_PEER_CONNECTION_STATE]:xN[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Y5+1&&(e=1)}),j5)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%K5==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const n=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=n,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const i=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*i;const r=this.requestStats(!0);new Array(i).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&r){const t=this.requestRemoteMedia()||[],n=[];t.forEach((e=>{let[t,i]=e;const o={peer:t.uid};if((t._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(t._videoSSRC)||!1)&&i.has(fx.VIDEO)&&t.videoTrack){const e=function(e,t,n){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const i={};if(n&&n._player){const e=n._player,{renderFreezeAccTime2:t,videoElementStatus:r}=e;if("visible"===tU.visibility&&r===nL.PLAYING&&uP().supportRequestVideoFrameCallback){const n=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-n),X5(i,U5.Video_Render_Freeze_Time_Render2,n),iD("USE_NEW_RENDER_FREEZE_TIME")&&X5(i,U5.Video_Render_Freeze_Time_Render,n)}}return i}(t._videoSSRC,r,t.videoTrack);e&&(o.video=e)}o.video&&n.push(o)})),n.length>0&&(e.inbound=n,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,n,i){if(!this.requestStats)return;if(!i)return null==e.rtt?void 0:{addition:{[F5.RTT]:e.rtt,[F5.CONN_TYPE]:void 0,[F5.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=J5(e);if(this.store.useP2P){if(n){const e=J5(n);r[F5.CONN_TYPE]&&e[F5.CONN_TYPE]&&(r[F5.CONN_TYPE]+=e[F5.CONN_TYPE]<<3)}r[F5.CONN_TYPE]?r[F5.CONN_TYPE]+=110:r[F5.CONN_TYPE]=110}else{r[F5.CONN_TYPE]?r[F5.CONN_TYPE]+=100:r[F5.CONN_TYPE]=100;const n=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[G5.Transport_Send_Bitrate]=n[0],r[G5.Transport_Recv_Bitrate]=n[1]}return{addition:r}}getOutboundStats(e,t,n,i,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||0===o.length)return;let s,a,c;return o.forEach((i=>{let[o,{track:d,ssrcs:l}]=i;switch(o){case Rx.LocalVideoLowTrack:case Rx.LocalVideoTrack:if(o===Rx.LocalVideoTrack){var u;const i=function(e,t,n,i,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},{sentFrame:c,inputFrame:d}=s;if(i&&(X5(a,U5.Video_Send_Qp_Sum,s.qpSumPerFrame),s.codec&&X5(a,U5.Video_Send_Codec,H5(s.codec)),"number"==typeof s.powerEfficientEncoder&&X5(a,U5.Video_Send_Power_Efficient_Encoder,s.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;a[U5.Video_Send_Freeze]=function(e,t){let n=!0;return n=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),n}(e,t)?1:0}if(r){switch(c&&(X5(a,V5.Video_Send_Height,c.height),X5(a,V5.Video_Send_Width,c.width),X5(a,V5.Video_Send_Frame_Rate,c.frameRate)),a[V5.Video_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[V5.Video_Send_Adaptation]=0;break;case"cpu":a[V5.Video_Send_Adaptation]=1;break;case"bandwidth":a[V5.Video_Send_Adaptation]=2;break;case"other":a[V5.Video_Send_Adaptation]=3}let i=0;s.adaptionChangeReason&&(i+=z5(s.adaptionChangeReason)),t.qualityLimitationReason&&(i+=z5(t.qualityLimitationReason)<<3),a[V5.Video_Send_Adaptation]=i,a[V5.Video_Send_Player_Status]=rL[n._player?n._player.videoElementStatus:"uninit"],X5(a,V5.Video_Send_Nacks,s.nacksCount),X5(a,V5.Video_Send_Plis,s.plisCount),X5(a,V5.Video_Send_Firs,s.firsCount),X5(a,V5.Video_Send_Avg_Encode,s.avgEncodeMs),X5(a,V5.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),X5(a,V5.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),X5(a,V5.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),X5(a,V5.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const o=r.videoSend.find((t=>t.ssrc===e));if(o){let e=j5*K5;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.packets&&null!=s.packets&&X5(a,V5.Video_Send_Package_Rate,1e3*(s.packets-o.packets)/e),null!=s.packetsLost&&null!=o.packetsLost&&X5(a,V5.Video_Send_Package_Lost,s.packetsLost-o.packetsLost),null!=o.bytes&&null!=s.bytes&&X5(a,V5.Video_Send_Bitrate,8*(s.bytes-o.bytes)/e)}}return a}(l[0].ssrcId,e,d,t,n),o="CameraVideoTrack"===d.__className__?3:Di(u=d._hints).call(u,xP.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||r)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o);const s=d&&function(e,t,n,i){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(i){const e=r.inputFrame,t=e&&e.height||n.videoHeight||0,i=e&&e.width||n.videoWidth||0,s=e&&e.frameRate||0;X5(o,V5.Video_Capture_Height,t),X5(o,V5.Video_Capture_Width,i),X5(o,V5.Video_Capture_Frame_Rate,s)}return o}(l[0].ssrcId,e,d,!!n),c=function(e,t){const n={};return t&&(X5(n,V5.Video_Send_Retransmit,e.bitrate.retransmit),X5(n,V5.Video_Send_Target_Encoded,e.bitrate.targetEncoded),X5(n,V5.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),X5(n,V5.Video_Send_Transmit,e.bitrate.transmit),X5(n,V5.Video_Send_Bandwidth,e.sendBandwidth)),n}(e,!!n);a=Object.assign({},i,s,c)}else c=function(e,t,n,i,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(i){const t=o.sentFrame;t&&(X5(s,V5.Video_Send_Low_Height,t.height),X5(s,V5.Video_Send_Low_Width,t.width),X5(s,V5.Video_Send_Low_Frame_Rate,t.frameRate));const n=i.videoSend.find((t=>t.ssrc===e));if(n){let e=j5*W5;n.timestamp&&o.timestamp&&(e=o.timestamp-n.timestamp),null!=n.packets&&null!=o.packets&&X5(s,V5.Video_Send_Low_Package_Rate,1e3*(o.packets-n.packets)/e),null!=o.packetsLost&&null!=n.packetsLost&&X5(s,V5.Video_Send_Low_Package_Lost,o.packetsLost-n.packetsLost),null!=n.bytes&&null!=o.bytes&&X5(s,V5.Video_Send_Low_Bitrate,8*(o.bytes-n.bytes)/e)}}return s}(l[0].ssrcId,e,0,n);break;case Rx.LocalAudioTrack:s=d&&function(e,t,n,i,r,o){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(r){a[V5.Audio_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const t=100*n._source.getAccurateVolumeLevel(),i=s.inputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));X5(a,V5.Audio_Send_Level,e)}X5(a,V5.Audio_Capture_PCM_Level,t),X5(a,V5.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),X5(a,V5.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),X5(a,V5.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),X5(a,V5.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),a[V5.Audio_Send_Freeze]=0;const o=r.audioSend.find((t=>t.ssrc===e));if(o){let e=j5*W5;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.bytes&&null!=s.bytes&&X5(a,V5.Audio_Send_Bitrate,8*(s.bytes-o.bytes)/e),null!=o.packets&&null!=s.packets&&X5(a,V5.Audio_Send_Package_Rate,1e3*(s.packets-o.packets)/e)}}return a}(l[0].ssrcId,e,d,0,n)}})),{high:a,low:c,audio:s}}getInboundStats(e,t,n,i){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(fx.VIDEO)&&s.videoTrack){const r=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,o=s.videoTrack?function(e,t,n,i,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;X5(d,x5.Video_Render_Frame_Rate_Decode,h),c.framesRateFirefox&&X5(d,x5.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&X5(d,x5.Video_Recv_Frame_Rate,l.frameRate),X5(d,x5.Video_Recv_Frame_Dropped,c.framesDroppedCount),X5(d,x5.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),X5(d,x5.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),X5(d,x5.Video_Recv_Packages_Discarded,c.packetsDiscarded),X5(d,x5.Video_Recv_Avg_Decode,c.avgDecodeMs),X5(d,x5.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),X5(d,x5.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),X5(d,x5.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),X5(d,x5.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||j5;null!=c.packetsLost&&null!=p.packetsLost&&X5(d,x5.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&X5(d,x5.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&X5(d,x5.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}const _=o&&o.videoRecv.find((t=>t.ssrc===e));if(_&&(X5(d,U5.Video_Recv_Qp_Sum,c.qpSumPerFrame),c.codec&&X5(d,U5.Video_Recv_Codec,H5(c.codec)),"number"==typeof c.powerEfficientDecoder&&X5(d,U5.Video_Recv_Power_Efficient_Decoder,c.powerEfficientDecoder),d[U5.Video_Recv_Freeze]=i&&q3.isRemoteVideoFreeze(n,c,_)?1:0),s){var E;const t=s.videoRecv.find((t=>t.ssrc===e));l?(X5(d,V5.Video_Recv_Height,l.height),X5(d,V5.Video_Recv_Width,l.width)):n&&(X5(d,V5.Video_Recv_Height,n._videoHeight||0),X5(d,V5.Video_Recv_Width,n._videoWidth||0)),u&&X5(d,V5.Video_Recv_Frame_Rate_Output,u.frameRate);const i=null===(E=n._player)||void 0===E?void 0:E.rendFrameRate.toFixed(0);if(i&&X5(d,V5.Video_Render_Frame_Rate_Render,+i),X5(d,V5.Video_Recv_Jitter_Buffer,c.jitterBufferMs),X5(d,V5.Video_Recv_Current_Delay,c.currentDelayMs),X5(d,V5.Video_Recv_Firs,c.firsCount),X5(d,V5.Video_Recv_Nacks,c.nacksCount),X5(d,V5.Video_Recv_Plis,c.plisCount),n){d[V5.Video_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:n,renderFreezeAccTime:i,renderFreezeAccTime2:o,videoElementStatus:s}=e;if(n&&n.length>0&&X5(d,U5.Video_Render_Freeze_Time,n.splice(0,1)[0]),r&&"visible"===tU.visibility&&s===nL.PLAYING&&uP().supportRequestVideoFrameCallback){const t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),X5(d,U5.Video_Render_Freeze_Time_Render2,t);const n=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-n),X5(d,U5.Video_Render_Freeze_Time_Render,iD("USE_NEW_RENDER_FREEZE_TIME")?t:n)}if("number"==typeof c.totalFreezesDuration){const e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;X5(d,V5.Video_Render_Freeze_Duration,1e3*e)}}}if(d[V5.Video_Recv_Player_Status]=rL[n._player?n._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,n=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,i=c.framesDecodeCount-t.framesDecodeCount,r=e/i*1e3,o=Math.round(1e3*Math.sqrt((n-Math.pow(e,2)/i)/i));!isNaN(o)&&r+o>Math.max(3*r,r+150)&&(d[V5.Video_Recv_I_Frame_Delay]=o)}}return d}(s._videoSSRC,e,s.videoTrack,!0===r,this.needUploadRenderFreezeTime,t,n,i):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(fx.AUDIO)&&s.audioTrack){const r=!s.hasAudio,o=s.audioTrack?function(e,t,n,i,r,o){let s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];const a=t.audioRecv.find((t=>t.ssrc===e));if(!a)return;const c={};X5(c,x5.Audio_Recv_Jitter,a.jitterMs),X5(c,x5.Audio_Recv_Bytes_Retransmit,a.retransmittedBytesReceived),X5(c,x5.Audio_Recv_Packages_Retransmit,a.retransmittedPacketsReceived),X5(c,x5.Audio_Recv_Packages_Discarded,a.packetsDiscarded),X5(c,x5.Audio_Recv_Avg_Processing_Delay,a.avgProcessingDelayMs);const d=o&&o.audioRecv.find((t=>t.ssrc===e));if(d){const e=j5;null!=a.packets&&null!=d.packets&&X5(c,x5.Audio_Recv_Package_Rate,1e3*(a.packets-d.packets)/e),null!=a.packetsLost&&null!=d.packetsLost&&X5(c,x5.Audio_Recv_Package_Lost,a.packetsLost-d.packetsLost)}if(i){const{receivedFrames:e,droppedFrames:t}=a;null!=e&&null!=t&&(c[U5.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(r){const t=100*n._source.getAccurateVolumeLevel(),i=a.outputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));X5(c,V5.Audio_Render_Level,e)}X5(c,V5.Audio_Recv_PCM_Level,t),n&&(c[V5.Audio_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),X5(c,V5.Audio_Recv_Jitter_Buffer,a.jitterBufferMs),X5(c,V5.Audio_Recv_Current_Delay,a.jitterBufferMs),c[V5.Audio_Recv_Player_Status]=rL[FL.getPlayerState(n.getTrackId())];const o=r.audioRecv.find((t=>t.ssrc===e));if(o&&(null!=o.bytes&&null!=a.bytes&&X5(c,V5.Audio_Recv_Bitrate,8*(a.bytes-o.bytes)/(j5*K5)),!s)){const e=a.concealedSamples-o.concealedSamples;e>0&&X5(c,V5.Audio_Recv_Concealed_Samples,e);const t=a.totalSamplesReceived-o.totalSamplesReceived;t>0&&X5(c,V5.Audio_Recv_Total_Samples_Received,t);const n=a.freezeSamples80-o.freezeSamples80;n>0&&X5(c,V5.Audio_Render_Freeze_Samples_80ms,n);const i=a.freezeSamples200-o.freezeSamples200;i>0&&X5(c,V5.Audio_Render_Freeze_Samples_200ms,i);const r=a.freezeMs80-o.freezeMs80;X5(c,V5.Audio_Render_Freeze_Time_80ms,r<0?0:r);const s=a.freezeMs200-o.freezeMs200;X5(c,V5.Audio_Render_Freeze_Time_200ms,s<0?0:s)}}return c}(s._audioSSRC,e,s.audioTrack,t,n,i,r):void 0;if(o&&(c.audio=o),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[x5.Audio_Recv_AV_Sync_TIME]=e:c.audio={[x5.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 jk));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(BV.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,n]=e;if(n.has(fx.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(n.has(fx.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(),n={connectionInterval:iD("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let i=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(i=i.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of o)t.has(fx.VIDEO)&&e.videoTrack&&(i=i.concat(await e.videoTrack.getProcessorUsage())),t.has(fx.AUDIO)&&e.audioTrack&&(i=i.concat(await e.audioTrack.getProcessorUsage()));if(0===i.length)return;n.details=function(e,t){const n={};for(const{id:s,value:a,level:c,direction:d}of e){var i;const e=null!==(i=t.get(s))&&void 0!==i?i:0,l=2===a?e+iD("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,o;t.set(s,l),n[s]?(2===a&&(n[s].value=a),c>n[s].level&&(n[s].level=c),"remote"===d&&(n[s].remoteUidCount+=1),n[s].totalTs=null!==(r=t.get(s))&&void 0!==r?r:0):n[s]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(s))&&void 0!==o?o:0}}return Object.keys(n).map((e=>{const{level:t,value:i,totalTs:r}=n[e];return{id:e,level:t,value:i,totalTs:r}}))}(i,e);const s=Date.now(),a=s>t?s:t+1;this.requestUpload&&this.requestUpload(BV.EXTENSION_USAGE_STATS,{usageStats:n,sendTs:a})}),iD("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,tU.stopCollectStats()}}const q5=iD("ICE_RESTART_INTERVAL");let Q5=new Map,$5=new Map,e4=[gx.UDP_TCP_RELAY,gx.TCP_RELAY,gx.RELAY],t4=iD("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&uP().supportPCSetConfiguration;function n4(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=Q5.get(e.id);n&&(window.clearTimeout(n),Q5.delete(e.id));const i=$5.get(e.id);t&&i&&i.index===e4.length-1&&(UD.debug("[".concat(e.id,"] reset ICE restart policy")),$5.delete(e.id))}function i4(e,t,n){if(0===Q5.size&&0===$5.size&&(Array.isArray(iD("RESTART_SEQUENCE"))&&iD("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n];if(e.filter((e=>e===i)).length!==t.filter((e=>e===i)).length)return!1}return!0}(e4,iD("RESTART_SEQUENCE"))&&(e4=iD("RESTART_SEQUENCE").filter((e=>{var t;if(Di(t=Object.values(gx)).call(t,e))return!0})),UD.debug("use reconnection policy from config distribution, queues: ".concat(e4.join(" => ")))),t4=iD("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&uP().supportPCSetConfiguration),0===e4.length)return void n();let i,{index:r=0,type:o}=$5.get(e.id)||{};if(t4&&o===gx.RELAY)return void n();let s=o&&r>=e4.length-1;if(t4)o=gx.RELAY;else{if(s)return void n();o?(r++,o=e4[r]):(o=e4[0],r=0)}UD.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(o,", index: ").concat(r)),t(o),$5.set(e.id,{index:r,type:o}),i=window.setTimeout((()=>i4(e,t,n)),q5),Q5.set(e.id,i)}var r4;function o4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function s4(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o4(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o4(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a4(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=gA,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new c4(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function c4(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 c4=function(e){this.s=e,this.n=e.next},c4.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Wh.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Wh.reject(e):t(n.apply(this.s,arguments))}},new c4(e)}let d4=(r4=class extends uO{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(yx.StateChange,t,this._state)}constructor(e,t){super(),Db(this,"isPlanB",void 0),Db(this,"store",void 0),Db(this,"statsUploader",void 0),Db(this,"connection",void 0),Db(this,"localTrackMap",new Map),Db(this,"remoteUserMap",new Map),Db(this,"localDataChannels",[]),Db(this,"remoteDataChannelMap",new Map),Db(this,"pendingLocalTracks",[]),Db(this,"pendingRemoteTracks",[]),Db(this,"pendingLocalDataChannels",[]),Db(this,"pendingRemoteDataChannels",[]),Db(this,"statsCollector",void 0),Db(this,"shouldForwardP2PCreation",void 0),Db(this,"iceFailedCount",0),Db(this,"dtlsFailedCount",0),Db(this,"mutex",void 0),Db(this,"_state",vx.Disconnected),Db(this,"_p2pBySDPEndPoint",!1),Db(this,"_pcStatsUploadType",iD("NEW_ICE_RESTART")?Sx.FIRST_CONNECTION:Sx.OLD_FIRST_CONNECTION),Db(this,"_isStartRestartIce",!1),Db(this,"_restartTimer",void 0),Db(this,"_isTryConnecting",!1),Db(this,"_iceError",null),Db(this,"_forceTurn",!1),Db(this,"_isWaitPcToRePub",!1),Db(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==vx.Connected)return void n(new Jw(Xw.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,UD.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?UD.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 OO(this,yx.RequestMuteLocal,s),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==vx.Connected)return void n(new Jw(Xw.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,UD.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding){const n=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}else{const n=k5(e,DO(this,yx.RequestLowStreamParameter));t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}await new Wh(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}this.store.enableInstantMuteRestore?UD.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r);await OO(this,yx.RequestUnmuteLocal,s),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;i||(r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(Rx.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==vx.Connected)return void t();const{id:i,track:s}=n;await this.connection.updateSendParameters(i,s),await this.connection.updateEncoderConfig(i,s),this.emit(yx.UpdateVideoEncoder,s),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),Db(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(Rx.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==vx.Connected)return void t();const{id:r,track:o}=n;await this.connection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleReplaceMixingTrack",(async(e,t,n,i)=>{if(!this.connection||this.state!==vx.Connected)return void t();const r=C5([e]);let o;UD.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof i&&i||(o=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t()}catch(e){n(e)}finally{var s;null===(s=o)||void 0===s||s()}})),Db(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;UD.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(!this.connection||!n||this.state!==vx.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),this.isPlanB){const t=n[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(n[0],t)}if(n[0]===Rx.LocalVideoTrack&&!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding){const t=this.localTrackMap.get(Rx.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new Wh(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),Db(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),Db(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),Db(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),Db(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),Db(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Z5(this.store),this.bindStatsUploaderEvents(),this.mutex=new pN("P2PChannel-mutex",this.store.clientId),this.isPlanB=!uP().supportUnifiedPlan||iD("CHROME_FORCE_PLAN_B")&&Bw(),this.shouldForwardP2PCreation=iD("FORWARD_P2P_CREATION")&&uP().supportPCSetConfiguration&&Fw(),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var n;this.state=vx.New,this._forceTurn=w5(e),UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&"closed"===(null===(n=this.connection)||void 0===n?void 0:n.peerConnectionState);if((!this.shouldForwardP2PCreation||i||t)&&((i||t)&&this.connection&&(UD.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=iD("NEW_ICE_RESTART")?Sx.FIRST_CONNECTION:Sx.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}updateConnectionConfiguration(e){var t;null===(t=this.connection)||void 0===t||t.setConfiguration(e),this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==vx.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=vx.Connected,t}if(this.connection instanceof P5||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),n=Z2(e.iceParameters.iceUfrag,e.iceParameters.icePwd);n||UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const i=this.connection.checkIceParameters(e.iceParameters),r=t||!n||i&&!(this.connection instanceof P5);if(r||i){UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(r?"try next":"restart ICE"));cP.reportApiInvoke(this.store.sessionId,{name:t?_O.MISMATCH_DTLS_PARAMETERS:_O.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:EO.TRACER}).onSuccess(),setTimeout((()=>{r?this.emit(yx.RequestReconnect):i&&this.emit(yx.RequestRestartICE,gx.UDP_RELAY)}))}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[n]=e;return Di(t=[Rx.LocalVideoLowTrack,Rx.LocalVideoTrack]).call(t,n)})),n=t.map((e=>{let[,{id:t}]=e;return t})),i=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof P5||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(cP.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(i),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Di(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Di(e).call(e,t)));t&&(this.store.codec=t,UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(n,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof P5&&"closed"!==this.connection.peerConnectionState&&Di(e=[vx.New,vx.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==vx.Connected){if(this.state===vx.Disconnected)throw new Jw(Xw.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Di(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,n){var i=this;return EA((function*(){const r=yield mA(i.mutex.lock("From P2PChannel.publish"));try{var o;const s=i.connection&&Di(o=["disconnected","failed"]).call(o,i.connection.peerConnectionState);if(!i.connection||i.state!==vx.Connected||s){if(i.state===vx.Disconnected)throw new Jw(Xw.UNEXPECTED_ERROR,"PeerConnection already disconnected.");i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return i.pendingLocalTracks=i.pendingLocalTracks.concat(t),void(s&&(i._isWaitPcToRePub=!0))}i.store.pubId=i.store.pubId+1,J3.markPublishStart(i.store.clientId,i.store.pubId);const a=i.filterTobePublishedTracks(e,t,n);if(0===a.length)return void(yield mA(i.tryToUnmuteAudio(e)));yield*fA(a4(i.doPublish(i.connection,a)))}finally{r()}}))()}doPublish(e,t){var n=this;return EA((function*(){t.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===Rx.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(t);const i=t.map((e=>{let{track:t}=e;return t})),r=yield mA(e.send(i,n.store.codec,n.store.audioCodec)),o=(yield mA(r.next())).value,s=n.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===Xw.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(t),e}const c=n.mapPubResToRemoteConfig(s,a,i),d=(yield mA(r.next(c))).value;if(n.state===vx.Disconnected)throw new Jw(Xw.UNEXPECTED_ERROR,"PeerConnection already disconnected.");iD("ENABLE_VIDEO_SEI");const l=iD("ENABLE_ENCODED_TRANSFORM"),u=iD("ENABLE_AUDIO_METADATA");i.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const{interceptLocalVideoFrame:n,interceptLocalAudioFrame:i}=z2();e.trackMediaType===fx.VIDEO?await n(t.sender,e):e.trackMediaType===fx.AUDIO&&await i(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let{type:t}=e;n.statsCollector.addLocalStats(t)})),n.assignLocalTracks(t,d),n.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===Rx.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const n=this.localTrackMap.get(t);if(!n||!this.connection)return;if(!(n.track instanceof MM))return UD.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:i}=n,r=function(e,t){const n={};return e.height&&e.width&&(n.scaleResolutionDownBy=r2(e,t)),n.maxFramerate=e.framerate?$1(e.framerate):void 0,n.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,n}(e,i);if(i._encoderConfig||(i._encoderConfig={}),t!==Rx.LocalVideoLowTrack||!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(i._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=i._originMediaStreamTrack;if(!t.canvas)return UD.warn("[".concat(i.getTrackId(),"] no canvas on track"));!function(e,t){const n=e.canvas;t.width&&(n.width=$1(t.width)),t.height&&(n.height=$1(t.height)),t.framerate&&(n.stopCapture&&n.stopCapture(),n.stopCapture=SL((()=>{!n.startCapture&&n.stopCapture&&n.stopCapture(),n.startCapture&&n.startCapture()}),$1(t.framerate)))}(t,e)}null!=r.maxBitrate&&(i._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(i._encoderConfig.frameRate&&"object"==typeof i._encoderConfig.frameRate?i._encoderConfig.frameRate.max=r.maxFramerate:i._encoderConfig.frameRate={max:r.maxFramerate}),UD.debug("[".concat(i.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(i._encoderConfig))),await this.connection.updateRtpSenderEncodings(i)}publishLowStream(e){var t=this;return EA((function*(){if(!t.connection||t.state!==vx.Connected)return;const n=yield mA(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(Rx.LocalVideoTrack);if(!r)throw new Jw(Xw.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(Rx.LocalVideoLowTrack))throw new Jw(Xw.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:Rx.LocalVideoLowTrack}];if(yield*fA(a4(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var i;const e=null===(i=t.localTrackMap.get(Rx.LocalVideoLowTrack))||void 0===i?void 0:i.id;void 0!==e&&(yield mA(t.connection.muteLocal([e])))}}finally{n()}}))()}async republish(){this.pendingLocalTracks.length>0&&(UD.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await wO(this,yx.RequestRePublish,this.pendingLocalTracks),this.emit(yx.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(UD.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await wO(this,yx.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:n}=this.pendingRemoteTracks[e];(n!==fx.AUDIO||t._audio_added_&&t._audioSSRC)&&(n!==fx.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await wO(this,yx.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===fx.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(yx.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==vx.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 n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==vx.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==vx.Connected)return;const e=this.localTrackMap.get(Rx.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[Rx.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const n=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:n}]=e;return{type:t,track:n}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),n}async subscribeDataChannel(e,t){if(!this.connection||this.state!==vx.Connected)throw new Jw(Xw.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const n=t.filter((t=>{var n;return!(null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.get(t.id))}));if(0!==n.length)return await this.connection.createDataChannels(e.uid,n),n.forEach((t=>{var n;this.remoteDataChannelMap.has(e)?null===(n=this.remoteDataChannelMap.get(e))||void 0===n||n.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const i=this.pendingRemoteDataChannels.findIndex((n=>{let{user:i,id:r}=n;return i.uid===e.uid&&r===t.id}));-1!==i&&this.pendingRemoteDataChannels.splice(i,1)})),n.map((e=>e.id))}async subscribe(e,t,n,i,r){var o;if(!this.connection||this.state!==vx.Connected)throw new Jw(Xw.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;const l=this.connection.getPreMedia(n);if(l)UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(n,", no need to send sub to gateway.")),c=l.transceiver,s=l.track,a=l.mid,d=l.player,l.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:l.firstVideoRender});else if(r){const n=r.find((e=>{let{stream_type:n}=e;return n===t}));if(!n)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const i=await this.connection.receive(t,n.ssrcs,String(e._uintid),n.attributes);(this.connection instanceof P5||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=i.transceiver),s=i.track,a=i.id}else{const r=await this.connection.receive(t,[{ssrcId:n,rtx:i}],String(e._uintid),void 0);(this.connection instanceof P5||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),s=r.track,a=r.id}if(t===fx.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new eU(s,e.uid,e._uintid,this.store),UD.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 $M(s,e.uid,e._uintid,this.store,d),UD.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(KP.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(KP.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(KP.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(KP.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&&iD("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:n,interceptRemoteAudioFrame:i}=z2();t==fx.VIDEO?await n(c.receiver,{onSei:iD("ENABLE_VIDEO_SEI")&&(t=>{var n;return null===(n=e._videoTrack)||void 0===n?void 0:n._onSei(t)}),onFirstFrame:e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==fx.AUDIO&&await i(c.receiver,{enableTopn:!!iD("ENABLE_AUDIO_TOPN"),enableMetadata:!!iD("ENABLE_AUDIO_METADATA"),enablePts:!!iD("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(yx.AudioMetadata,e)},onPts:e=>{this.safeEmit(yx.AudioPts,e)}})}const u=this.remoteUserMap.get(e);u?u.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex((n=>{let{user:i,kind:r}=n;return i.uid===e.uid&&t===r}));-1!==h&&(this.pendingRemoteTracks.splice(h,1),this.emit(yx.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==vx.Connected)throw new Jw(Xw.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let{user:n,mediaType:i}=e;return!(null!==(t=this.remoteUserMap.get(n))&&void 0!==t&&t.has(i))}));const t=[],n=new Map;e.forEach((e=>{if(!this.connection)return;const i=this.connection.getPreMedia(e.ssrcId);if(i){const{track:t,mid:r,transceiver:o,player:s}=i;n.set(e.ssrcId,{track:t,id:r,transceiver:o,player:s})}else t.push(e)}));const i=await this.connection.batchReceive(t.map((e=>{let{user:t,mediaType:n,ssrcId:i,rtxSsrcId:r}=e;return{kind:n,ssrcMsg:[{ssrcId:i,rtx:r}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{n.set(e.ssrcId,i[t])}));for(const{user:t,mediaType:i,ssrcId:r}of e){const e=n.get(r);if(!e)return void UD.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(t.uid," subscribe data,").concat(i,", ").concat(r));const{track:o,id:s,transceiver:a,player:c}=e;if(a&&iD("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:n}=z2();i==fx.VIDEO?await e(a.receiver,{onSei:iD("ENABLE_VIDEO_SEI")&&(e=>{var n;return null===(n=t._videoTrack)||void 0===n?void 0:n._onSei(e)}),onFirstFrame:e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==fx.AUDIO&&await n(a.receiver,{enableTopn:!!iD("ENABLE_AUDIO_TOPN"),enableMetadata:!!iD("ENABLE_AUDIO_METADATA"),enablePts:!!iD("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(yx.AudioMetadata,e)},onPts:e=>{this.safeEmit(yx.AudioPts,e)}})}if(i===fx.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(o):(t._audioTrack=new eU(o,t.uid,t._uintid,this.store),UD.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 $M(o,t.uid,t._uintid,this.store,c),UD.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)),iD("ENABLE_VIDEO_SEI")&&a){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:n}=z2();i==fx.VIDEO?await e(a.receiver,{onSei:e=>{var n;null===(n=t._videoTrack)||void 0===n||n._onSei(e)},onFirstFrame:e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==fx.AUDIO&&await n(a.receiver)}const d=this.remoteUserMap.get(t);d?d.set(i,s):this.remoteUserMap.set(t,new Map([[i,s]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex((e=>{let{user:n,kind:r}=e;return n.uid===t.uid&&i===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(yx.MediaReconnectEnd,t.uid))}}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let{user:i,kind:r}=n;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===vx.Connected||n||i.forEach((t=>{let{kind:n}=t;var i;if(n===fx.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===fx.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==vx.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:i}]=e;var r,o;i===fx.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===fx.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),n||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(i===fx.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!n)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 n=this.filterTobeUnSubscribedDataChannels(e,t);if(0===n.length)return;t.forEach((e=>{e._close()}));const i=this.remoteDataChannelMap.get(e);return n.forEach((e=>{i&&i.delete(e.id)})),i&&0===i.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),n.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:n,mediaType:i}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==i?t.uid===n.uid&&i===r:t.uid===n.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==vx.Connected)return void t.forEach((e=>{let{user:t,kind:n}=e;var i;if(n===fx.AUDIO)null===(i=t._audioTrack)||void 0===i||i._destroy(),t._audioTrack=void 0;else if(n===fx.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const n=zi(e).call(e,((e,t)=>{let{user:n,mediaType:i}=t;const r=this.filterTobeUnSubscribedTracks(n,i);return e.concat(r)}),[]);if(0===n.length)return;await this.connection.stopReceiving(n.map((e=>{let[,{id:t}]=e;return t})));const i=this.createUnsubscribeAllMessage(n);return this.withdrawRemoteTracks(n),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),n.forEach((e=>{let[t,{kind:n}]=e;var i,r;n===fx.VIDEO&&t._videoSSRC&&(null===(i=this.connection)||void 0===i||i.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===fx.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(n===fx.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),i}isPreSubScribe(e){if(!this.connection||this.state!==vx.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void UD.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void UD.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===fx.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.connection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void UD.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||UD.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(Rx.LocalAudioTrack),n=t&&t.track;n&&n.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(Rx.LocalAudioTrack);if((null==t?void 0:t.track)instanceof Kk){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==Rx.LocalAudioTrack})).filter((t=>{let[n]=t;return!(e&&n===Rx.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[n]=t;return!(e&&n===Rx.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(Rx.LocalAudioTrack),o=i?this.localTrackMap.get(Rx.LocalVideoLowTrack):this.localTrackMap.get(Rx.LocalVideoTrack);cP.publish(this.store.sessionId,{eventElapse:J3.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(xP.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof Gk)),a=i?null===(o=this.localTrackMap.get(Rx.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof MM));cP.publish(this.store.sessionId,{eventElapse:J3.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(xP.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===fx.VIDEO?n._videoSSRC:n._audioSSRC;r&&cP.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===fx.VIDEO,audio:i===fx.AUDIO,peerid:n.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:J3.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){UD.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new pN("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&this.recreateConnection(),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(Rx.LocalAudioTrack);if((null==e?void 0:e.track)instanceof Kk){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=vx.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(Rx.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(Rx.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 MM||t&&t.track instanceof Gk?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 n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._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(Rx.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Jp(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(UD.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=vx.Reconnecting,iD("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[n,{track:i}]=e;switch(n){case Rx.LocalVideoTrack:Di(t=i._hints).call(t,xP.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case Rx.LocalAudioTrack:i instanceof Kk?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case Rx.LocalVideoLowTrack:}})),this.emit(yx.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,n]=e;Array.from(CD(n).call(n)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(yx.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,n]=e;Array.from(CD(n).call(n)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),UD.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const n of this.pendingRemoteDataChannels){const{user:i,id:r}=n;if((e instanceof e5?e.uid:e)===i.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 n of this.pendingRemoteTracks){const{user:i,kind:r}=n;if((e instanceof e5?e.uid:e)===i.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 EA((function*(){if(!t.connection||t.state!==vx.Connected)return;const n=yield mA(t.mutex.lock("From P2PChannel.restartICE"));let i;try{i=yield mA(t.connection.restartICE(e));const r=yield mA(i.next());if(r.done)return;const o=r.value,s=yield o;switch(A5(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case gx.UDP_TCP_RELAY:t._pcStatsUploadType=Sx.UDP_TCP_RESTART;break;case gx.TCP_RELAY:t._pcStatsUploadType=Sx.TCP_RESTART;break;case gx.RELAY:t._pcStatsUploadType=Sx.RELAY_RESTART;break;default:t._pcStatsUploadType=Sx.OLD_RESTART}t._isTryConnecting=!0,i.next(s)}catch(e){var r;null===(r=i)||void 0===r||r.throw(e)}finally{n()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(Rx.LocalVideoTrack),n=this.localTrackMap.get(Rx.LocalAudioTrack),i=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==n?void 0:n.ssrcs[0].ssrcId)));if(!i||!r)return 1;const o=NO(this,yx.NeedSignalRTT),s=i?i.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(xP.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return KU[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((n=>{let[i]=n;const r=i._audioSSRC,o=i._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=NO(this,yx.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,n)=>{this.handleMuteLocalTrack(e,t,n)}))}async replaceTrack(e,t){var n;if(UD.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==vx.Connected)return;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(!i)return;const r=i[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),i[1].track=t),await(null===(n=this.connection)||void 0===n?void 0:n.replaceTrack(t,i[1].id)),this.isPlanB){const e=i[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===Rx.LocalVideoTrack&&!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding){const t=this.localTrackMap.get(Rx.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new Wh(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}}filterTobePublishedTracks(e,t,n){const i=[],r=this.getAllTracks();e=FO(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(Rx.LocalAudioTrack);for(const r of e){if(r instanceof MM&&(this.localTrackMap.has(Rx.LocalVideoTrack)||s?new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:r,type:Rx.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,n);i.push({track:e,type:Rx.LocalVideoLowTrack})}if(r instanceof Gk)if(a){const e=a.track;if(e instanceof Kk)y5([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=C5([e,r]);UD.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 Kk)y5([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&uP().webAudioMediaStreamDest&&!r._bypassWebAudio){o=C5(o?[r,o]:[r])}else o=r}return o&&(UD.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),i.push({track:o,type:Rx.LocalAudioTrack})),i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=FO(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof Gk){const e=this.localTrackMap.get(Rx.LocalAudioTrack);if(!e)continue;e.track instanceof Kk?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([Rx.LocalAudioTrack,e]),e.track.close())):t.push([Rx.LocalAudioTrack,e])}if(n instanceof MM){const e=this.localTrackMap.get(Rx.LocalVideoTrack);if(!e)continue;t.push([Rx.LocalVideoTrack,e]);const n=this.localTrackMap.get(Rx.LocalVideoLowTrack);n&&t.push([Rx.LocalVideoLowTrack,n])}}return t}filterTobePublishedDataChannels(e){return e=(e=FO(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=FO(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:n}=e;switch(n){case Rx.LocalVideoTrack:t.addListener(VP.GET_STATS,this.handleGetLocalVideoStats),t.addListener(VP.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(VP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(VP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Rx.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case Rx.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof Kk?e.trackList.forEach((e=>{e.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(VP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(VP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(VP.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:n}]=e;return{track:n,type:t}}))),e.forEach((e=>{let{track:t,type:n}=e;switch(n){case Rx.LocalVideoTrack:t.off(VP.GET_STATS,this.handleGetLocalVideoStats),t.off(VP.GET_RTC_STATS,this.handleGetRTCStats),t.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(VP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(VP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Rx.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case Rx.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof Kk?e.trackList.forEach((e=>{e.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(VP.GET_STATS,this.handleGetLocalAudioStats),e.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(VP.GET_STATS,this.handleGetLocalAudioStats),e.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(VP.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof $M&&t.addListener(VP.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof eU&&t.addListener(VP.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(VP.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,n]=e;n.has(fx.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),n.has(fx.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,o,{track:s,type:a}=e;switch(a){case Rx.LocalAudioTrack:r=ox.Audio,o={dtx:s instanceof jk&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case Rx.LocalVideoTrack:r=Di(i=s._hints).call(i,xP.SCREEN_TRACK)?ox.Screen:ox.High,o=s4(s4({},e2(s)),{},{codec:this.store.codec,svc_mode:c2()});break;case Rx.LocalVideoLowTrack:r=ox.Low,o=s4(s4({},e2(s)),{},{codec:this.store.codec,svc_mode:c2()})}return{stream_type:r,attributes:o,ssrcs:t[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let{track:i,type:r}=e;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(yx.PeerConnectionStateChange,t),"connecting"===t&&e instanceof P5&&!Tw()&&iD("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),iD("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 P5&&n4(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=Sx.DISCONNECTED_OR_FAILED;if("CONNECTED"===NO(this,yx.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));cP.reportApiInvoke(this.store.sessionId,{name:_O.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:EO.TRACER}).onSuccess(),this.republish()}}if(iD("NEW_ICE_RESTART")&&e instanceof P5&&!Tw()&&!this._forceTurn&&!this.store.useDcSignal){if(Di(Tx).call(Tx,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(A5(e)){UD.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===NO(this,yx.QueryClientConnectionState)&&this.emit(yx.RequestRestartICE,t)}},n=()=>{A5(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),UD.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(yx.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{i4(e,t,n)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&iD("ICE_RESTART")){"CONNECTED"===NO(this,yx.QueryClientConnectionState)&&this.emit(yx.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(UD.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(yx.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(UD.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(yx.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),cP.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:EO.TRACER}).onSuccess(),this.emit(yx.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(KP.FIRST_FRAME_DECODED),cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_AUDIO_DECODE,WD.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_AUDIO_RECEIVED,WD.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{var i;const r=Array.from(CD(i=this.remoteUserMap).call(i)).find((t=>t._videoSSRC===e));r&&this.store.firstVideoFrameDecoded(r.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoRender=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(n),this.emit(yx.FirstVideoPreRender,n.uid,e))},e.onFirstVideoReceived=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstReceived:Date.now()}),cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_VIDEO_RECEIVED,WD.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&this.emit(yx.FirstVideoBufferReady,n.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(yx.ConnectionTypeChange,n),UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(o2(t))," -> ").concat(JSON.stringify(o2(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(o2(t))," -> ").concat(JSON.stringify(o2(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return s4(s4({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){UD.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===vx.Connected?(UD.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.recreateConnection())}resetConnection(e){e instanceof P5&&function(e){$5.delete(e.id),n4(e)}(e),e.close(),this.emit(yx.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}recreateConnection(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._p2pBySDPEndPoint=!1,this.connection=I5(this.store,e),this.emit(yx.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(Rx.LocalAudioTrack);if(e instanceof Gk&&(null==n?void 0:n.track)instanceof Kk)return n.track.isActive||t.push([Rx.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(i&&(t.push(i),i[0]===Rx.LocalVideoTrack)){const e=this.localTrackMap.get(Rx.LocalVideoLowTrack);e&&t.push([Rx.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(Rx.LocalAudioTrack);if(e instanceof Gk&&(null==n?void 0:n.track)instanceof Kk)return n.track.isActive&&t.push([Rx.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(i)if(i[0]===Rx.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(Rx.LocalVideoLowTrack);e&&t.push([Rx.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let[i,r]=t;n.push([e,{kind:i,id:r}])}));return n}filterTobeUnSubscribedDataChannels(e,t){const n=[];return t.forEach((t=>{var i;null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.has(t.id)&&n.push(t)})),n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[n,{kind:i,id:r}]=e;switch(i){case fx.VIDEO:return void(n._videoSSRC&&t.push({stream_type:fx.VIDEO,ssrcId:n._videoSSRC}));case fx.AUDIO:return void(n._audioSSRC&&t.push({stream_type:fx.AUDIO,ssrcId:n._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[n,{kind:i}]=e;if(t.has(n)){let e=t.get(n);i===fx.VIDEO?e|=cx.Video:e|=cx.Audio,t.set(n,e)}else i===fx.VIDEO?t.set(n,cx.Video):t.set(n,cx.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,n]=e;return{stream_id:t.uid,stream_type:n}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:n}]=e;const i=this.remoteUserMap.get(t);i&&(i.delete(n),0===Array.from(i.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(Rx.LocalVideoTrack),n=this.localTrackMap.get(Rx.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(n.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 P5&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof P5)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof P5&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,n){return e.map(((e,i)=>{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&&iD("DISABLE_SCREEN_SHARE_REMB")){const e=n[i]._hints;(Di(e).call(e,xP.SCREEN_TRACK)||Di(e).call(e,xP.SCREEN_LOW_TRACK))&&(s.remb=!1,UD.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof Gk){var t;const i=this.filterTobeUnmutedTracks(e[n]);if(0===i.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(i.map((e=>{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(i);return void await OO(this,yx.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(yx.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(yx.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 QO(mN(this.dtlsFailedCount,EN)),this.emit(yx.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await wO(this,yx.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(yx.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(Rx.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof MM))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof MM)).length>1)throw new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof Gk)).length>1&&(e.some((e=>e instanceof Gk&&e._bypassWebAudio))||!uP().webAudioMediaStreamDest))throw new Jw(Xw.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 MM&&this.pendingLocalTracks.some((e=>e instanceof MM)))throw new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof Gk&&this.pendingLocalTracks.some((e=>e instanceof Gk))&&(!uP().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof Gk&&e._bypassWebAudio))))throw new Jw(Xw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var n;const i=!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding,r=s4(s4({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=i?e._mediaStreamTrack.clone():k5(e,r);const s=$O(8,"track-low-"),a=new MM(o,s4(s4({},i&&{scaleResolutionDownBy:r2(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(jP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,FP.LOW_STREAM)})),a._hints.push(xP.LOW_STREAM),Di(n=e._hints).call(n,xP.SCREEN_TRACK)&&a._hints.push(xP.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(VP.NEED_CLOSE,(()=>{a.close()})),a}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof P5){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();cP.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:this._iceError||i||"",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:n,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,n=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!n)return;const{isInternalUpload:i,isExternalUpload:r}=n;if(i&&r)return;const{subscribeEnd:o,firstPreRender:s,peerPublishDuration:a,peerPubStatusMs:c}=n;let{firstRender:d=0}=n;if(o&&(d||s)&&a&&c){n.isInternalUpload=!0;const{playEnd:i}=n;i&&(n.isExternalUpload=!0);const{firstPreRender:r=0}=n;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:n.userJoinNotify||0,videoAddNotify:n.videoAddNotify||0,subscribeStart:n.subscribeStart||0,subscribeEnd:n.subscribeEnd||0,firstReceived:n.firstReceived||0,firstDecoded:n.firstDecoded||0,firstPreRender:r||0,firstRender:i?Math.max(d,i):Math.max(d,o),playStart:n.playStart||0,playEnd:n.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:mP(this.store),firstReceivedEncodedFrame:n.firstReceivedEncodedFrame||0,frameType:n.frameType||"",rtpTimestamp:n.rtpTimestamp||0,framePayloadType:n.framePayloadType||0,frameDataLength:n.frameDataLength||0,mimeType:n.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};cP.firstXLAPeerFirstVideoFrame(this.store.sessionId,l)}}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(CD(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||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));cP.firstRemoteVideoDecode(this.store.sessionId,jD.FIRST_VIDEO_DECODE,WD.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:J3.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:i?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.connection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==n}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:n}]=e;t===Rx.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,FP.LOW_STREAM):n._updateRtpTransceiver(void 0)}))}},DV(r4.prototype,"startP2PConnection",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"startP2PConnection"),r4.prototype),DV(r4.prototype,"connect",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"connect"),r4.prototype),DV(r4.prototype,"updateRemoteRTPCapabilities",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"updateRemoteRTPCapabilities"),r4.prototype),DV(r4.prototype,"publishDataChannel",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"publishDataChannel"),r4.prototype),DV(r4.prototype,"unpublish",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unpublish"),r4.prototype),DV(r4.prototype,"unpublishDataChannel",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unpublishDataChannel"),r4.prototype),DV(r4.prototype,"unpublishLowStream",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unpublishLowStream"),r4.prototype),DV(r4.prototype,"subscribeDataChannel",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"subscribeDataChannel"),r4.prototype),DV(r4.prototype,"subscribe",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"subscribe"),r4.prototype),DV(r4.prototype,"massSubscribe",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"massSubscribe"),r4.prototype),DV(r4.prototype,"unsubscribe",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unsubscribe"),r4.prototype),DV(r4.prototype,"unsubscribeDataChannel",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unsubscribeDataChannel"),r4.prototype),DV(r4.prototype,"massUnsubscribe",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"massUnsubscribe"),r4.prototype),DV(r4.prototype,"muteRemote",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"muteRemote"),r4.prototype),DV(r4.prototype,"unmuteRemote",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"unmuteRemote"),r4.prototype),DV(r4.prototype,"hasRemoteMediaWithLock",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"hasRemoteMediaWithLock"),r4.prototype),DV(r4.prototype,"disconnectForReconnect",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"disconnectForReconnect"),r4.prototype),DV(r4.prototype,"updateBitrateLimit",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"updateBitrateLimit"),r4.prototype),DV(r4.prototype,"remoteMediaSsrcChanged",[l4],Object.getOwnPropertyDescriptor(r4.prototype,"remoteMediaSsrcChanged"),r4.prototype),r4);function l4(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}function u4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function h4(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u4(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u4(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const p4=Date.now(),_4=20,E4=new Map,m4=new Map;async function f4(e){const t=E4.get(e),n=Array.isArray(t)&&t[t.length-1],i=m4.get(e);if(!n)return void(i.isSyncing=!1);const r={uid:n.uid,payload:n.payload};0===i.firstRecvTs&&(i.firstRecvTs=n.recvTs,i.firstSendTs=n.sendTs);const o=n.sendTs-i.firstSendTs,s=o-(Date.now()-i.firstRecvTs);s>0&&(i.firstRecvTs=Date.now()-o);let a=n.mediaDelay+s;a<=0?(t.pop(),g4(n.context,r),a=0):a=Math.min(a,_4),setTimeout((()=>t.length&&f4(e)),a)}function g4(e,t){e.safeEmit(yO.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function S4(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return g4(n,{uid:e.uid,payload:e.payload});const i="".concat(n.id,"-").concat(e.uid),r=E4.get(i)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=h4(h4({},e),{},{context:n,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),E4.set(i,r);let a=!1;var c;m4.has(i)?a=!(null===(c=m4.get(i))||void 0===c||!c.isSyncing):m4.set(i,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||f4(i)}const T4=lw().name;function R4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function v4(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?R4(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):R4(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const y4="websdk_ng_cache_parameter",C4=iD("MAX_PRELOAD_ASYNC_LENGTH"),b4=1e4,I4=new Map,A4=[];let w4=null,O4=0,N4=0;const D4=new Map,P4=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),L4=function(e,t){const n=[];let i=0;const r=async()=>{const e=n.shift();e&&await e(),n.length>0&&i<t?r():i--};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)=>{n.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),i<t&&(i++,r())}))}}(U4,C4),k4=$A.CancelToken.source();class M4{constructor(){Db(this,"_audioContext",null)}createMuteAudioTrack(){this._audioContext=new AudioContext;const e=this._audioContext.sampleRate,t=10*e,n=this._audioContext.createBuffer(2,t,e),i=this._audioContext.createBufferSource();i.buffer=n;const r=this._audioContext.createMediaStreamDestination();i.connect(r),i.start();return r.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function U4(e,t,n,i,r,o,s){try{if(!iD("ENABLE_PRELOAD"))return;if(!uP().supportWebCrypto)return void KO((()=>{UD.warn("Your browser does not support preloading, this feature  be run in a secure environment")}),"preload_webcrypto_not_supported");if(!n&&null!==n)throw new Jw(Xw.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));n&&$w(n,"token",1,2047),$w(e,"appid",1,2047),KV(t),i&&YV(i);const a=eN();UD.debug("preload channel ".concat(t,", uid is ").concat(i));const c={appId:e,cname:t,token:n||e,uid:"string"!=typeof i?i:null,sid:a,proxyServer:r,role:s};let d,l;"string"==typeof i?(c.stringUid=i,[l,d]=await Wh.all([V3(i,{sid:a,appId:e},k4.token),F3(v4(v4({},c),{},{token:n||e,uid:0}),k4.token)]),c.uid=l.uid,d.gatewayInfo.uid=c.uid,d.gatewayInfo.res.uid=c.uid):(o&&(c.stringUid=o),d=await F3(c,k4.token));const u={sid:a,appId:e,cname:t,token:n||e,uid:c.stringUid||i,intUid:c.uid||d.gatewayInfo.uid,stringUid:c.stringUid,ts:Date.now(),sua:l,ap:d};await F4(u),O4++}catch(e){throw N4++,function(e){w4||(w4=window.setTimeout((()=>{let t="";D4.forEach(((e,n)=>{t+="".concat(n,": ").concat(e," ;")})),cP.reportApiInvoke(null,{name:_O.PRELOAD,options:{success:O4,failed:N4,err:t}}).onError(e),O4=0,N4=0,D4.clear(),w4=null}),b4));const t=D4.get(e.code)||0;D4.set(e.code,t+1)}(e),e}}async function V4(e){try{if(iD("AP_REQUEST_DETAIL")||iD("ENABLE_ROLE_SELECT_EDGE")||iD("ENABLE_JOIN_V4"))return;const t=x4(e);if(!t||"disabled"!==e.cloudProxyServer)return;const n=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",XO(t),"AES-GCM",!1,["decrypt"]),i=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:P4},n,YO(e));return JSON.parse(window.atob(HO(new Uint8Array(i))))}catch(e){return}}(t,e.token||e.appId);if(!n)return;if(!function(e,t){const n=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!n)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(n,e))return;if(n&&Date.now()-n.ts<iD("AP_CACHE_LIFETIME"))return n}catch(e){UD.warn("Error get preloadInfo",e.message)}}function x4(e){let t;try{if(t=W4(y4),!t)return;const n=JSON.parse(t),i=Y4(e),r=function(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}(n,(e=>i in e));if(-1===r)return;const o=n.splice(r,1)[0];return K4(y4,JSON.stringify(n)),o[i]}catch(e){UD.warn("Error delete preload info: ".concat(t),e.message),K4(y4,"")}}async function F4(e){let t;try{e.uid&&x4({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const n=Y4(e),i=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",XO(t),"AES-GCM",!1,["encrypt"]),i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:P4},n,YO(window.btoa(JSON.stringify(e))));return HO(new Uint8Array(i))}catch(e){return}}(e,e.token||e.appId);if(!i)return;t=W4(y4);const r=t?JSON.parse(t):[];r.push({[n]:i}),r.length>iD("AP_CACHE_NUM")&&r.shift(),K4(y4,JSON.stringify(r))}catch(e){UD.warn("Error caching server parameters:",e.message),K4(y4,"")}}function B4(e){if(e){let t=I4.get(e);t&&(window.clearTimeout(t),t=null,I4.delete(e)),Di(A4).call(A4,e)||"disabled"!==e.cloudProxyServer||A4.push(e)}if(I4.size<iD("AP_CACHE_NUM")&&A4.length>0){const e=A4.shift();I4.set(e,window.setTimeout((async()=>{const{appId:t,cname:n,token:i,stringUid:r,uid:o,proxyServer:s,role:a}=e;try{await L4(t,n,i,o,s,r,a),I4.has(e)&&B4(e)}catch(t){UD.warn("update preload failed",t.message),G4(e)}}),iD("AP_UPDATE_INTERVAL")))}}function G4(e){const t=A4.indexOf(e);-1!==t&&A4.splice(t,1);let n=I4.get(e);n&&(window.clearTimeout(n),n=null,I4.delete(e),B4())}function j4(e,t){const n=e.sua,i=e.ap;t&&n&&cP.reqUserAccount(e.sid,{lts:n.requestTime,elapse:n.elapse,success:!0,serverAddr:n.url,stringUid:t,uid:e.intUid,errorCode:null,extend:n.req}),cP.reportResourceTiming(e.ap.url,e.sid),cP.joinWebProxyAP(e.sid,{lts:i.requestTime,elapse:i.elapse,sucess:1,apServerAddr:i.url,turnServerAddrList:i.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[Mj.CHOOSE_SERVER,Mj.CLOUD_PROXY_FALLBACK].toString()}),cP.joinChooseServer(e.sid,{lts:i.requestTime,elapse:i.elapse,succ:!0,csAddr:i.url,opid:i.opid,serverList:i.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:i.gatewayInfo.cid.toString(),uid:i.gatewayInfo.uid.toString(),csIp:i.gatewayInfo.csIp,unilbsServerIds:[Mj.CHOOSE_SERVER].toString(),isHttp3:i.isHttp3})}function W4(e){return window.atob(window.localStorage.getItem(e)||"")}function K4(e,t){window.localStorage.setItem(e,window.btoa(t))}function Y4(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)),lN(t)}function H4(e){let t=function(){const e=Z4.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(a6(t,10),i6(t,n));let i=e.cid;void 0!==i&&(a6(t,16),a6(t,i));let r=e.cname;void 0!==r&&(a6(t,26),i6(t,r));let o=e.deviceId;void 0!==o&&(a6(t,34),i6(t,o));let s=e.elapse;void 0!==s&&(a6(t,40),d6(t,s));let a=e.fileSize;void 0!==a&&(a6(t,48),d6(t,z4(a)));let c=e.height;void 0!==c&&(a6(t,56),d6(t,z4(c)));let d=e.jpg;void 0!==d&&(a6(t,66),a6(t,d.length),t6(t,d));let l=e.networkType;void 0!==l&&(a6(t,72),d6(t,z4(l)));let u=e.osType;void 0!==u&&(a6(t,80),d6(t,z4(u)));let h=e.requestId;void 0!==h&&(a6(t,90),i6(t,h));let p=e.sdkVersion;void 0!==p&&(a6(t,98),i6(t,p));let _=e.sequence;void 0!==_&&(a6(t,104),d6(t,z4(_)));let E=e.sid;void 0!==E&&(a6(t,114),i6(t,E));let m=e.timestamp;void 0!==m&&(a6(t,120),d6(t,m));let f=e.uid;void 0!==f&&(a6(t,128),a6(t,f));let g=e.vid;void 0!==g&&(a6(t,136),a6(t,g));let S=e.width;void 0!==S&&(a6(t,144),d6(t,z4(S)));let T=e.service;void 0!==T&&(a6(t,152),a6(t,T));let R=e.callbackData;void 0!==R&&(a6(t,162),a6(t,R.length),t6(t,R));let v=e.ticket;void 0!==v&&(a6(t,170),i6(t,v));let y=e.vendorConfigs;void 0!==y&&(a6(t,178),i6(t,y))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function X4(e){return function(e){let t={};e:for(;!Q4(e);){let n=s6(e);switch(n>>>3){case 0:break e;case 1:t.code=s6(e);break;case 2:t.msg=n6(e,s6(e));break;case 3:t.requestId=n6(e,s6(e));break;case 4:t.timestamp=c6(e,!1);break;default:J4(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function J4(e,t){switch(t){case 0:for(;128&r6(e););break;case 2:q4(e,s6(e));break;case 5:q4(e,4);break;case 1:q4(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function z4(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Z4=[];function q4(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Q4(e){return e.offset>=e.limit}function $4(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function e6(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function t6(e,t){let n=$4(e,t.length);e.bytes.set(t,n)}function n6(e,t){let n=e6(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+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+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+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+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function i6(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}a6(e,i);let r=$4(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function r6(e){return e.bytes[e6(e,1)]}function o6(e,t){let n=$4(e,1);e.bytes[n]=t}function s6(e){let t,n=0,i=0;do{t=r6(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function a6(e,t){for(t>>>=0;t>=128;)o6(e,127&t|128),t>>>=7;o6(e,t)}function c6(e,t){let n,i=0,r=0,o=0;return n=r6(e),i=127&n,128&n&&(n=r6(e),i|=(127&n)<<7,128&n&&(n=r6(e),i|=(127&n)<<14,128&n&&(n=r6(e),i|=(127&n)<<21,128&n&&(n=r6(e),r=127&n,128&n&&(n=r6(e),r|=(127&n)<<7,128&n&&(n=r6(e),r|=(127&n)<<14,128&n&&(n=r6(e),r|=(127&n)<<21,128&n&&(n=r6(e),o=127&n,128&n&&(n=r6(e),o|=(127&n)<<7))))))))),{low:i|r<<28,high:r>>>4|o<<24,unsigned:t}}function d6(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=$4(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?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}const l6={},u6={},h6=4294967296,p6=h6*h6,_6=p6/2,E6=T6(0,!0),m6=T6(0),f6=R6(0,-2147483648,!1),g6=R6(-1,2147483647,!1),S6=R6(-1,-1,!0);function T6(e,t){let n,i,r;return t?(r=0<=(e>>>=0)&&e<256)&&(i=u6[e],i)?i:(n=R6(e,0,!0),r&&(u6[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(i=l6[e],i)?i:(n=R6(e,e<0?-1:0,!1),r&&(l6[e]=n),n)}function R6(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function v6(e,t){if(isNaN(e))return t?E6:m6;if(t){if(e<0)return E6;if(e>=p6)return S6}else{if(e<=-_6)return f6;if(e+1>=_6)return g6}return e<0?t?E6:m6:R6(e%h6|0,e/h6|0,t)}function y6(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class C6 extends uO{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Dx.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(),Db(this,"name","AgoraRTCImageModeration"),Db(this,"_connectionState",Nx.CONNECTING),Db(this,"_sequence",0),Db(this,"_moderationStartTime",void 0),Db(this,"_workerConnection",void 0),Db(this,"_workerMessageLengthLimit",void 0),Db(this,"_qualityRatio",void 0),Db(this,"_connectInfo",void 0),Db(this,"_cancelTokenSource",$A.CancelToken.source()),Db(this,"_retryConfig",void 0),Db(this,"_moderationInterval",void 0),Db(this,"_moderationTimer",null),Db(this,"_moderationMode",1),Db(this,"_quality",1),Db(this,"_qualityTimer",null),Db(this,"_ticket",void 0),Db(this,"_moderationIntervalMinimum",void 0),Db(this,"_uploadFailedNum",0),Db(this,"_uploadNum",0),Db(this,"_uploadTimer",null),Db(this,"_extraInfo",void 0),Db(this,"_vendor",""),Db(this,"_encoder",new TextEncoder),Db(this,"_moderationId",void 0),Db(this,"inspectImage",(()=>{if(this.connectionState!==Nx.CONNECTED)throw new dP(Xw.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===Nx.CONNECTED?this.requestToInspectImage():UD.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()})),this._moderationId=$O(5,"image-moderation-"),this._workerMessageLengthLimit=iD("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=iD("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=iD("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new $x("worker-"+this._moderationId,EN),this.on(Dx.STATE_CHANGE,((e,t)=>{UD.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Px[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(Dx.STATE_CHANGE,Px.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((i,r)=>{this.on(Dx.CONNECTION_STATE_CHANGE,((e,t)=>{e===Nx.CONNECTED&&i()})),this.requestAP(e,n,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),UD.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===Nx.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const i=iD("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;w3++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:w3,seq:w3,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fN((async()=>{h=Date.now();const e=await r3(_,{data:u,cancelToken:n,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 dP(Xw.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw UD.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new dP(Xw.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw UD.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new dP(Xw.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw UD.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new dP(Xw.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw UD.error(e.toString()),e}const i=iD("IMAGE_MODERATION_WORKER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=iD("IMAGE_MODERATION_WORKER_HOST"),o=t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(n,"/moderation")})).filter((e=>!!e));return{addressList:o,workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,n)=>(cP.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(cP.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==Xw.OPERATION_ABORTED&&t.code!==Xw.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(Dx.STATE_CHANGE,Px.AP_CONNECTED);const{addressList:o,ticket:s}=r;return this._ticket=s,o}async connectWorker(e){this.emit(Dx.STATE_CHANGE,Px.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(WV.CONNECTED,(async()=>{this.emit(Dx.STATE_CHANGE,Px.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Nx.CONNECTED})),this._workerConnection.on(WV.CLOSED,(()=>{this.connectionState=Nx.CLOSED})),this._workerConnection.on(WV.FAILED,(()=>{this.connectionState=Nx.CLOSED})),this._workerConnection.on(WV.RECONNECTING,(()=>{this.connectionState=this.connectionState===Nx.CONNECTED?Nx.RECONNECTING:Nx.CONNECTING})),this._workerConnection.on(WV.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=X4(new Uint8Array(e.data));iD("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&UD.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++,UD.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{cP.reportApiInvoke(this._connectInfo.sid||null,{name:_O.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:EO.TRACER}).onError(new dP(Xw.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),iD("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else UD.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(WV.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(WV.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=NO(this,Dx.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(iD("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&UD.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else iD("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&UD.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await QL(d,n,i),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+$O(12,""),h={appId:n,cid:r,cname:i,deviceId:"",elapse:C6.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.3",sequence:this._sequence,sid:s,timestamp:v6(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=H4(h);if(p.byteLength<this._workerMessageLengthLimit){if(iD("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?y6(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y6(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,UD.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:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=$A.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=Nx.CLOSED,this.emit(Dx.STATE_CHANGE,Px.CLOSED)}}function b6(e){if(qw(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new dP(Xw.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new dP(Xw.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const I6={name:"ImageModeration",create:function(e){let{config:t}=e;return b6(t),new C6(t)}};var A6,w6,O6,N6,D6,P6,L6,k6,M6,U6,V6,x6,F6,B6,G6,j6,W6,K6,Y6,H6,X6,J6,z6,Z6,q6,Q6,$6,e8,t8,n8,i8,r8,o8,s8,a8,c8,d8,l8,u8,h8,p8,_8,E8;function m8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function f8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?m8(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}pN.setLogger(UD);let g8=(A6=aP(),w6=aP({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof uL))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),O6=aP({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==YP.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),N6=aP({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),D6=aP({argsMap:(e,t,n)=>[t,n]}),P6=aP({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:n}=e;return[null==t?void 0:t.uid,n]}))}),L6=aP({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),k6=aP({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:n}=e;return{uid:null==t?void 0:t.uid,mediaType:n}}))}),M6=aP(),U6=aP(),V6=aP(),x6=aP(),F6=aP(),B6=aP(),G6=aP(),j6=aP(),W6=aP(),K6=aP(),Y6=aP(),H6=aP(),X6=aP(),J6=aP(),z6=aP(),Z6=aP(),q6=aP({argsMap:(e,t)=>[t]}),Q6=aP(),$6=aP(),e8=aP(),t8=aP(),n8=aP(),i8=aP(),r8=aP(),o8=aP(),s8=aP({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),a8=aP(),c8=aP(),d8=aP(),l8=aP(),u8=aP(),h8=aP(),p8=aP({reportResult:!0}),_8=aP(),E8=class extends uO{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 n;if(super(),Db(this,"store",void 0),Db(this,"_uid",void 0),Db(this,"_channelName",void 0),Db(this,"_uintUid",void 0),Db(this,"_users",[]),Db(this,"_config",void 0),Db(this,"_clientId",void 0),Db(this,"_appId",void 0),Db(this,"_sessionId",null),Db(this,"_key",void 0),Db(this,"_rtmConfig",{}),Db(this,"_joinInfo",void 0),Db(this,"_gateway",void 0),Db(this,"_statsCollector",void 0),Db(this,"_configDistribute",void 0),Db(this,"_leaveMutex",void 0),Db(this,"_publishMutex",void 0),Db(this,"_renewTokenMutex",void 0),Db(this,"_subscribeMutex",void 0),Db(this,"_encryptionMode","none"),Db(this,"_encryptionSecret",null),Db(this,"_encryptionSalt",null),Db(this,"_encryptDataStream",!1),Db(this,"_encryptDataStreamKey",null),Db(this,"_encryptDataStreamIv",null),Db(this,"_proxyServer",void 0),Db(this,"_turnServer",{servers:[],mode:"auto"}),Db(this,"_cloudProxyServerMode","disabled"),Db(this,"_isDualStreamEnabled",!1),Db(this,"_defaultStreamFallbackType",void 0),Db(this,"_lowStreamParameter",void 0),Db(this,"_streamFallbackTypeCacheMap",new Map),Db(this,"_remoteStreamTypeCacheMap",new Map),Db(this,"_axiosCancelSource",$A.CancelToken.source()),Db(this,"_audioVolumeIndicationInterval",void 0),Db(this,"_networkQualityInterval",void 0),Db(this,"_userOfflineTimeout",void 0),Db(this,"_streamRemovedTimeout",void 0),Db(this,"_rteDetailInterval",void 0),Db(this,"_liveTranscodeStreamingClient",void 0),Db(this,"_liveRawStreamingClient",void 0),Db(this,"_channelMediaRelayClient",void 0),Db(this,"_networkQualitySensitivity","normal"),Db(this,"_p2pChannel",void 0),Db(this,"_useLocalAccessPoint",!1),Db(this,"_setLocalAPVersion",void 0),Db(this,"_joinAndNotLeaveYet",!1),Db(this,"_numberOfJoinCount",0),Db(this,"_joinResponse",null),Db(this,"_remoteDefaultVideoStreamType",void 0),Db(this,"_inspect",void 0),Db(this,"_moderation",void 0),Db(this,"_license",void 0),Db(this,"_pendingPublishedUsers",[]),Db(this,"ntpAlignErrorCount",0),Db(this,"remoteInboundOffset",0),Db(this,"_peerConnectionState",void 0),Db(this,"_pendingRtpCapabilityChange",void 0),Db(this,"_fallbackServerInfo",void 0),Db(this,"_dualStreamMode",void 0),Db(this,"_handleLocalTrackEnable",((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),Db(this,"_handleLocalTrackDisable",((e,t,n)=>{this.unpublish(e).then(t).catch(n)})),Db(this,"_handleUserOnline",(e=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(e.uid,this.channelName))return void UD.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&UD.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(yO.USER_JOINED,t));else{const t=new e5(e.uid,e.uint_id||e.uid);this._users.push(t),UD.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(yO.USER_JOINED,t)}})),Db(this,"_handleUserOffline",(e=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(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:xO(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),UD.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(yO.USER_LEAVED,t,e.reason))})),Db(this,"_handleAddAudioOrVideoStream",((e,t,n,i,r,o,s,a)=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void UD.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));UD.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!==n&&(c._audioSSRC=n),void 0!==i&&(c._cname=i),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==n&&(c._videoSSRC=n),void 0!==i&&(c._cname=i),void 0!==a&&(c._rtxSsrcId=a),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(UD.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(yO.USER_PUBLISHED,c,e)),"video"===e?cP.onGatewayStream(this._sessionId,jD.ON_ADD_VIDEO_STREAM,WD.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):cP.onGatewayStream(this._sessionId,jD.ON_ADD_AUDIO_STREAM,WD.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,n).then((t=>{if(t&&(UD.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof d4))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{UD.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(UD.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{UD.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(r);"video"===e&&("unknown"===l?this.safeEmit(yO.AV1_DECODABLE_RESULT,!1):mw()||Rw()||(null==l?void 0:l.toLocaleLowerCase())!==aD.av1||P3().then((e=>{iD("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(yO.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))})),Db(this,"_handleRemoveStream",(e=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void UD.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));UD.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let n=()=>{};t.hasAudio&&t.hasVideo?n=()=>{UD.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(yO.USER_UNPUBLISHED,t,"audio"),UD.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(yO.USER_UNPUBLISHED,t,"video")}:t.hasVideo?n=()=>{UD.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(yO.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(n=()=>{UD.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(yO.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 d4&&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),cP.onGatewayStream(this._sessionId,jD.ON_REMOVE_STREAM,WD.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),n()})),Db(this,"_handleSetStreamLocalEnable",((e,t,n)=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(t,this.channelName))return;const i=this._users.find((e=>e.uid===t));if(!i)return void UD.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));UD.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(n?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?i.hasAudio:i.hasVideo;if("audio"===e){i._trust_audio_enabled_state_=!0;const e=i._audio_enabled_;if(i._audio_enabled_=n,i._audio_enabled_===e)return;{const e=i._audio_enabled_?"enable-local-audio":"disable-local-audio";UD.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(yO.USER_INFO_UPDATED,t,e)}}else{i._trust_video_enabled_state_=!0;const e=i._video_enabled_;if(i._video_enabled_=n,i._video_enabled_===e)return;{const e=i._video_enabled_?"enable-local-video":"disable-local-video";UD.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(yO.USER_INFO_UPDATED,t,e)}}const o="audio"===e?i.hasAudio:i.hasVideo;return r!==o?!r&&o?(UD.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(yO.USER_PUBLISHED,i,e)):("video"===e&&i._videoTrack&&i._videoTrack._destroy(),"audio"===e&&i._audioTrack,this._p2pChannel.muteRemote(i,e),UD.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(yO.USER_UNPUBLISHED,i,e)):void 0})),Db(this,"_handleMuteStream",((e,t,n)=>{if(iD("BLOCK_LOCAL_CLIENT")&&XU(e,this.channelName))return;UD.debug("[".concat(this._clientId,"] receive mute message"),e,t,n);const i=this._users.find((t=>t.uid===e));if(!i)return void UD.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?i.hasAudio:i.hasVideo;if("audio"===t){i._trust_audio_mute_state_=!0;const t=i._audio_muted_;if(i._audio_muted_=n,i._audio_muted_===t)return;{const t=i._audio_muted_?"mute-audio":"unmute-audio";UD.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(yO.USER_INFO_UPDATED,e,t)}}else{i._trust_video_mute_state_=!0;const t=i._video_muted_;if(i._video_muted_=n,i._video_muted_===t)return;{const t=i._video_muted_?"mute-video":"unmute-video";UD.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(yO.USER_INFO_UPDATED,e,t)}}const o="audio"===t?i.hasAudio:i.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?i._audioSSRC:i._videoSSRC)?(UD.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(yO.USER_PUBLISHED,i,t)):void UD.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&&i._videoTrack&&!i._video_pre_subscribed&&i._videoTrack._destroy(),"audio"===t&&i._audioTrack,this._p2pChannel.muteRemote(i,t),UD.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(yO.USER_UNPUBLISHED,i,t)}})),Db(this,"_handleP2PLost",(async e=>{UD.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():UD.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),Db(this,"_handleTokenWillExpire",(()=>{UD.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(yO.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),Db(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),UD.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),Db(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(yO.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(yO.NETWORK_QUALITY,e)})),Db(this,"_handleP2PAddAudioOrVideoStream",((e,t,n,i)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void UD.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));UD.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!==n&&(r._audioSSRC=n),void 0!==i&&(r._audioMid=i)):(r._video_added_=!0,void 0!==n&&(r._videoSSRC=n),void 0!==i&&(r._videoMid=i)),("audio"===e?r.hasAudio:r.hasVideo)&&!o&&(UD.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(yO.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(UD.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{UD.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||$O(5,"client-"),this.store=new class{constructor(e,t,n,i,r){Kw(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:n,clientId:i,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:zN.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!r,preSubOptions:void 0}}dispatch(e){this.state=function(e,t){switch(t.type){case sD.SET_SESSION_ID:return Hw(Hw({},e),{},{sessionId:t.sessionId});case sD.SET_P2P_ID:return Hw(Hw({},e),{},{p2pId:t.p2pId});case sD.SET_UID:return Hw(Hw({},e),{},{uid:t.uid});case sD.SET_INT_UID:return Hw(Hw({},e),{},{intUid:t.intUid});case sD.SET_PUB_ID:return Hw(Hw({},e),{},{pubId:t.pubId});case sD.KEY_METRIC_CLIENT_CREATED:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{clientCreated:t.metric})});case sD.KEY_METRIC_JOIN_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinStart:t.metric})});case sD.KEY_METRIC_PRELOAD_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{preloadStart:t.metric})});case sD.KEY_METRIC_PRELOAD_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{preloadEnd:t.metric})});case sD.KEY_METRIC_JOIN_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinEnd:t.metric})});case sD.KEY_METRIC_REQUEST_AP_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{requestAPStart:t.metric})});case sD.KEY_METRIC_REQUEST_AP_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{requestAPEnd:t.metric})});case sD.KEY_METRIC_REQUEST_SUA_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case sD.KEY_METRIC_BEFORE_CONNECT:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{beforeConnect:t.metric})});case sD.KEY_METRIC_PEER_RECEIVER:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{peerReceiver:t.metric})});case sD.KEY_METRIC_SIGNAL_CONNECTED:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{signalConnected:t.metric})});case sD.KEY_METRIC_JOIN_REQ:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinReq:t.metric})});case sD.KEY_METRIC_JOIN_REP:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinRep:t.metric})});case sD.KEY_METRIC_JOIN_GATEWAY_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case sD.KEY_METRIC_JOIN_GATEWAY_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case sD.KEY_METRIC_PEER_CONNECTION_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case sD.KEY_METRIC_PEER_CONNECTION_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case sD.KEY_METRIC_DESCRIPTION_START:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{descriptionStart:t.metric})});case sD.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case sD.KEY_METRIC_ICE_CONNECTION_END:return Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case sD.KEY_METRIC_PUBLISH:{const n=e.keyMetrics.publish,i=n.findIndex((e=>e.trackId===t.metric.trackId));return-1!==i?(n[i]=Hw(Hw({},n[i]),t.metric),Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{publish:[...n]})})):Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case sD.KEY_METRIC_SUBSCRIBE:{const n=e.keyMetrics.subscribe,i=n.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==i?(n[i]=Hw(Hw({},n[i]),t.metric),Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{subscribe:[...n]})})):Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case sD.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const n=e.keyMetrics.firstVideoFrameDecoded,i=n.findIndex((e=>e.userId===t.metric.userId));return-1!==i?(n[i]=Hw(Hw({},n[i]),t.metric),Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{firstVideoFrameDecoded:[...n]})})):Hw(Hw({},e),{},{keyMetrics:Hw(Hw({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case sD.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case sD.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case sD.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=Hw(Hw({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case sD.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case sD.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case sD.SET_USE_P2P:return Hw(Hw({},e),{},{useP2P:t.val});case sD.SET_TRANSPORT_TYPE:return Hw(Hw({},e),{},{p2pTransport:t.val});case sD.SET_RTE_URL:return Hw(Hw({},e),{},{rteUrl:t.rteUrl});case sD.SET_RTE_SID:return Hw(Hw({},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 preSubOptions(e){this.state.preSubOptions=e}get preSubOptions(){return this.state.preSubOptions}set sessionId(e){this.dispatch({type:sD.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:sD.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:sD.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:sD.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:sD.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:sD.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:sD.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:sD.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:sD.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:sD.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:sD.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:sD.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:sD.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:sD.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:sD.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:sD.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:sD.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:sD.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:sD.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:sD.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:sD.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:sD.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:sD.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:sD.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:sD.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:sD.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:sD.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:sD.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:sD.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:Hw({userId:e},t)})}descriptionStart(){this.dispatch({type:sD.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:sD.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:sD.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,n,i){this.dispatch({type:sD.KEY_METRIC_PUBLISH,metric:Hw(Hw({trackId:e,type:t},n&&{publishStart:n}),i&&{publishEnd:i})})}subscribe(e,t,n,i,r,o,s){this.dispatch({type:sD.KEY_METRIC_SUBSCRIBE,metric:Hw(Hw(Hw(Hw(Hw({userId:e,type:t},n&&{subscribeStart:n}),i&&{subscribeEnd:i}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,n,i){e.forEach((e=>{this.dispatch({type:sD.KEY_METRIC_SUBSCRIBE,metric:Hw(Hw(Hw({userId:e.userId,type:e.type},t&&{subscribeStart:t}),n&&{subscribeEnd:n}),i&&{firstFrame:i})})}))}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:sD.RECORD_JOIN_CHANNEL_SERVICE,record:Hw(Hw({},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:sD.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:sD.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:sD.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:sD.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===iD("SIGNAL_CHANNEL")),this._leaveMutex=new pN("client-leave",this._clientId),this._publishMutex=new pN("client-publish",this._clientId),this._renewTokenMutex=new pN("client-renewtoken",this._clientId),this._subscribeMutex=new pN("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),UD.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(XN," build: ").concat($N,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{vO(e.clientRoleOptions),n=Object.assign({},e.clientRoleOptions)}catch(e){UD.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var i;this._statsCollector=new q3(this.store),this._statsCollector.onStatsException=(e,t,n)=>{UD.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(n)),e===X3.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof UM&&iD("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(yO.EXCEPTION,{code:e,msg:t,uid:n})},this._statsCollector.onUploadPublishDuration=(e,t,n,i)=>{const r=this._users.find((t=>t.uid===e));if(r){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(r.uid,{peerPublishDuration:n,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(r)),cP.peerPublishStatus(this._sessionId,{subscribeElapse:i,audioPublishDuration:t,videoPublishDuration:n,peer:r._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(iD("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof MM));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?iD("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new e3(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||EN,httpRetryConfig:e.httpRetryConfig||EN,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:n}),this._configDistribute=new Y3(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(i={store:this.store,statsCollector:this._statsCollector},X2("P2PChannel").create(i)),this._handleP2PEvents()):this._p2pChannel=new d4(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,n,i,r){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];nD("JOIN_GATEWAY_USE_443PORT_ONLY",o),nD("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof Qx&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,n){nw.get(e)||nw.set(e,[]),iw.get(e)||iw.set(e,t),rw.get(e)||rw.set(e,0);const i=nw.get(e),r=iw.get(e);if(!i||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(rw.get(e)===r){const e=tw();i.push(e),await e.promise}rw.set(e,rw.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 n(...s);return rw.set(e,rw.get(e)-1),rw.get(e)===r-1&&i.length>0&&(i[0].resolve(),i.shift()),0===rw.get(e)&&(nw.set(e,[]),iw.set(e,0),rw.set(e,0)),c}("client.join",iD("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,n,i,r)}async join(e,t,n,i,r){const o=++this._numberOfJoinCount;this.store.joinStart(),i&&(this.store.uid=i);const s="HTTPS"===(gN||gN||(gN=(window.location.protocol.split(":")[0]||"").toUpperCase(),gN)),a=CN()?window.isSecureContext:"Browser Not Support";if(!CN()&&!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";UD.warning(e)}let c;cP.setAppId(e);try{if(!n&&null!==n)throw new dP(Xw.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));if(n&&$w(n,"token",1,2047),$w(e,"appid",1,2047),KV(t),i&&YV(i),r)if("string"==typeof r)$w(r,"optionalInfo",1,256),c=r;else{if("object"!=typeof r)throw new dP(Xw.INVALID_PARAMS,"Invalid options: options is not a string or object");{const{autoSubscribe:e,enableInstantMuteRestore:t,networkQualityProbe:n,preSubOptions:i}=r;e&&(zw(e,"autoSubscribe"),UD.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),t&&(zw(t,"enableInstantMuteRestore"),UD.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),n&&(zw(n,"networkQualityProbe"),UD.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(n)),this.store.networkQualityProbe=n),Array.isArray(i)&&(eO(i,"preSubOptions"),i.forEach((e=>{YV(e.uid),function(e,t){if("string"!=typeof e&&!(e instanceof HTMLElement||e instanceof HTMLVideoElement))throw new Jw(Xw.INVALID_PARAMS,"".concat(t," should be a string or a HTML element"))}(e.element,"element")})),UD.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(i.map((e=>"".concat(e.uid,": ").concat("string"==typeof e.element?e.element:e.element.id))).join(","))),this.store.preSubOptions=i)}}}catch(r){throw cP.reportApiInvoke(eN(),{name:_O.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:EO.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){UD.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),UD.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new dP(Xw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw cP.reportApiInvoke(eN(),{name:_O.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:EO.TRACER}).onError(r),r}this._gateway.state="CONNECTING",this.store.preloadStart();const d=await V4({appId:e,cname:t,uid:i,stringUid:"string"==typeof i?i:void 0,token:n||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new dP(Xw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const l=(null==d?void 0:d.sid)||eN();UD.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=cP.reportApiInvoke(this._sessionId,{id:this._clientId,name:_O.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:EO.TRACER}),h=f8(f8(f8({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof i?i:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:n||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!d},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:iD("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(h.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof i&&(h.stringUid=i,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"),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(),n=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),i=cO(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},n,i);return function(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new dP(Xw.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=iD("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,n){const i=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:lD,hash:"SHA-256",salt:n},i,r+dD);return new Uint8Array(o).subarray(r/8)}(this._encryptionMode,t,YO(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,n){const i=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:lD,hash:"SHA-256",salt:n},i,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"])}(this._encryptionMode,t,YO(this._encryptionSalt))}else a?UD.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):UD.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,UD.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&&cP.joinChannelTimeout(this._sessionId,5)}),5e3);try{var _;let i;const r=h.cloudProxyServer;if(Di(_=["proxy3","proxy4","proxy5"]).call(_,r)){const e=iD("PROXY_SERVER_TYPE3");Array.isArray(e)?h.proxyServer=e[0]:h.proxyServer=e}if(cP.setProxyServer(h.proxyServer),UD.setProxyServer(h.proxyServer),this.store.requestAPStart(),iD("ENABLE_JOIN_V4")&&"disabled"===h.cloudProxyServer)try{h.stringUid&&!h.uid&&(h.uid=await U3(h.stringUid,h,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,this.store).finally((()=>{this.store.requestSUAEnd()})),UD.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(h.stringUid," => ").concat(h.uid))),UD.debug("[".concat(this._clientId,"] try use best first frame line"));const e=await this._p2pChannel.startP2PConnection({isPreallocation:!0});i=await M3(h,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,this.store,e),UD.debug("[".concat(this._clientId,"] get serverInfo from sdp endpoint")),iD("ENABLE_SDP_ENDPOINT_LOG")&&UD.debug("[".concat(this._clientId,"] serverInfo: "),i)}catch(e){i=void 0,UD.debug("[".concat(this._clientId,"] join channel with sdp endpoint failed, fallback to normal join ap"),e)}if(i);else if(d){if(UD.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),i={gatewayInfo:d.ap.gatewayInfo},iD("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===h.turnServer.mode)if(0===d.ap.proxyInfo.addresses.length)UD.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await i2(d.ap.proxyInfo,d.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ZN.tcpport,udpport:e.udpport||ZN.udpport,username:e.username||ZN.username,password:e.password||ZN.password,forceturn:!1,security:!0})));h.turnServer={mode:"manual",servers:e}}j4(d,h.stringUid)}else{if(h.stringUid&&!h.uid){let e;[e,i]=await Wh.all([U3(h.stringUid,h,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,this.store).finally((()=>{this.store.requestSUAEnd()})),k3(h,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),UD.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(h.stringUid," => ").concat(e)),h.uid=e,i.gatewayInfo.uid=e,i.gatewayInfo.res.uid=e}else i=await k3(h,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,!0,this.store);if(!this._joinAndNotLeaveYet)throw new dP(Xw.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(h,this._axiosCancelSource.token),this._configDistribute.on(px.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(px.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(px.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{var t;Di(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(px.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(yO.FALLBACK_TO_HLS,CO.CONFIG)})),this._configDistribute.on(px.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{UD.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=n||e;const o=i.gatewayInfo,s=h.uid?h.uid:o.uid;this._joinInfo=f8(f8({},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,signalResponse:o.res.signalResponse}),this.store.intUid=s,this.store.cid=o.cid;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new dP(Xw.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),!mw()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(mw()?"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 UD.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout((()=>{UD.startUpload()}),5e3),this.store.joinEnd(),E=this,Di(YU).call(YU,E)||YU.push(E),"disabled"===this._cloudProxyServerMode&&uP().supportWebCrypto&&iD("ENABLE_PRELOAD")&&B4(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&cP.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&cP.reportRteDetail(this._sessionId)}),iD("RTE_DETAIL_REPORT_INTERVAL")||6e4),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Xw.OPERATION_ABORTED?UD.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):UD.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==Xw.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 dP(Xw.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!iD("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===Xw.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,gO.FALLBACK),UD.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new dP(Xw.INVALID_OPERATION);return cP.reportApiInvoke(this._sessionId,{name:_O.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:EO.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){UD.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!mw()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(mw()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=YU.indexOf(e);-1!==t&&YU.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return UD.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();await this._gateway.leave("CONNECTED"!==this.connectionState,gO.LEAVE),UD.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 uL))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new dP(Xw.INVALID_PARAMS,"param list is empty");const n=e;if("audience"===this._gateway.role)throw new dP(Xw.INVALID_OPERATION,"audience can not publish stream");for(const e of n){if(!(e instanceof uL))throw new dP(Xw.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new dP(Xw.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}UD.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))));const i=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&n.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof MM&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(n),UD.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw UD.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async _publishDataChannel(e){if(null==e)throw new dP(Xw.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));qw(e.id,"id",0,65535,!0),zw(e.ordered,"ordered"),$w(e.metadata,"metadata",0,512),UD.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 dP(Xw.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 dP(Xw.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&iD("FORCE_TURN")&&!iD("TURN_ENABLE_TCP")&&!iD("TURN_ENABLE_UDP"))throw new dP(Xw.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const n=function(e){return J2(e,!1)}(e),i=await this._p2pChannel.publishDataChannel([n]);if(i.length>0){if("number"!=typeof n._originDataChannelId)throw UD.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new dP(Xw.CREATE_DATACHANNEL_ERROR);try{await Wh.all(i.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await n._waitTillOpen()}catch(e){if(e.code!==Xw.DISCONNECT_P2P)throw e}}return UD.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(n.id)),n}catch(e){throw UD.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new dP(Xw.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof uL))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);UD.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const n=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(Lx.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),UD.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw UD.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{n&&n()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),UD.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const n=await this._p2pChannel.unpublishDataChannel(e);n&&await this._gateway.unpublishDataChannel(n),UD.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw UD.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,n){if(!(e instanceof e5)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,n):this._subscribe(e,t)}async presubscribe(e,t){if(Zw(t,"mediaType",["audio","video"]),this.store.useP2P)throw new dP(Xw.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const n=t===fx.AUDIO,i=t===fx.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 dP(Xw.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new e5(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),n&&(l._audioSSRC=o,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),i&&(l._videoSSRC=o,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),null!=a&&(l._rtxSsrcId=a)),UD.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(o)),await this._p2pChannel.subscribe(l,t,o,a,s);const u=n?l._audioTrack:l._videoTrack;if(!u)throw new dP(Xw.UNEXPECTED_ERROR,"can not find remote track in user");return n&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),i&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(t){throw UD.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var n;if(qw(t,"channelId",0,65535,!0),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i)throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new dP(Xw.INVALID_REMOTE_USER,"user is not published");const r=null===(n=e._dataChannels)||void 0===n?void 0:n.find((e=>e.id===t));if(!r)throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new dP(Xw.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();UD.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Di(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new dP(Xw.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)!==Xw.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return UD.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,n){if(Zw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");throw UD.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 dP(Xw.INVALID_REMOTE_USER,"user is not published");throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!n&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const n=new dP(Xw.REMOTE_USER_IS_NOT_PUBLISHED);throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}const r=await this._subscribeMutex.lock();UD.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 n="audio"===t?e._audioSSRC:e._videoSSRC,i="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,n,i)}catch(e){throw e}UD.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=>{UD.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(!n)throw new dP(Xw.UNEXPECTED_ERROR,"can not find remote track in user object");return n}catch(t){throw UD.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,n){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(Zw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");throw UD.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 dP(Xw.INVALID_REMOTE_USER,"user is not published");throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(n||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const n=new dP(Xw.REMOTE_USER_IS_NOT_PUBLISHED);throw UD.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}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?fx.AUDIO:fx.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const c=await this._subscribeMutex.lock();UD.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 n="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==n&&n!==r&&(r=n,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?fx.AUDIO:fx.VIDEO,ssrcId:r}),J3.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(n){if((null==n?void 0:n.code)!==Xw.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),n;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(n){throw this._p2pChannel.reportSubscribeEvent(!1,null==n?void 0:n.code,e,t),n}UD.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=>{UD.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(!n)throw new dP(Xw.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)),n}catch(t){throw UD.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(eO(e,"subscribeList"),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),n=new Map,i=await this._subscribeMutex.lock();UD.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let{user:t,mediaType:n}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; ")));const r=(e=[...e]).map((e=>{let{user:t,mediaType:n}=e;return{user:t,mediaType:n}})),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const i=e[t],{user:o,mediaType:s}=i;if(Zw(s,"mediaType",["audio","video"]),!o){const e=new dP(Xw.INVALID_PARAMS,"user property does not exist in subscribeList item");throw UD.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}const a=this._users.find((e=>e===o));if(!a){const n=new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");UD.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=n,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const n=new dP(Xw.REMOTE_USER_IS_NOT_PUBLISHED);UD.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=n,e.splice(t,1);continue}const c=cx.Video|cx.LowVideo,d=n.get(o);if(d){if("video"===s?d&c:d&cx.Audio){e.splice(t,1),UD.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}n.set(o,d|("video"===s?c:cx.Audio))}else n.set(o,"video"===s?c:cx.Audio)}for(let t=e.length-1;t>=0;t--){const i=e[t],{user:r,mediaType:o}=i,s=cx.Video|cx.LowVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const i=n.get(r);n.set(r,"video"===o?i^s:i^cx.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=zi(s=Array.from(n.entries())).call(s,((e,t)=>{let[n,i]=t;if(0===i)return e;const r={stream_id:n.uid,stream_type:i};return i&cx.Audio&&(r.audio_ssrc=n._audioSSRC),i&cx.Video&&(r.video_ssrc=n._videoSSRC),e.push(r),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:n}=e;return{user:t,mediaType:n,ssrcId:n===fx.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:n===fx.VIDEO?t._rtxSsrcId:void 0}})));const n=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:i,audio_error_code:r,error_code:o}=e;(i||r||o)&&n.set(t,{video_error_code:i,audio_error_code:r,error_code:o})}))}if(Array.from(n.entries()).length>0){const e=[];Array.from(n.entries()).forEach((t=>{let[n,i]=t;const r=this.remoteUsers.find((e=>e.uid===n));if(r){let t;i.error_code||i.video_error_code&&i.audio_error_code?t=void 0:i.video_error_code?t=fx.VIDEO:i.audio_error_code&&(t=fx.AUDIO),e.push({user:r,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=n.get(e.user.uid);if(t){const n=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(n){const t=Bx(n);UD.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new dP(Xw.SUBSCRIBE_FAILED,"code ".concat(n,": ").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 n;cP.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(n=e.error)||void 0===n?void 0:n.code)||null,video:e.mediaType===fx.VIDEO,audio:e.mediaType===fx.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===fx.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)})),UD.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let{user:t,mediaType:n}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),i()}}async unsubscribe(e,t,n){if(!(e instanceof e5)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,n)}else await this._unsubscribeDataChannel(e,n);if(t&&Zw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");throw UD.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}UD.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 n=await this._p2pChannel.unsubscribe(e,t);n&&await this._gateway.unsubscribe(n,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&xO(this._users,e),UD.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===Xw.DISCONNECT_P2P)return void UD.warning("disconnecting p2p, abort unsubscribe request.");throw UD.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&qw(t,"id",0,65535,!0),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new dP(Xw.INVALID_REMOTE_USER,"user is not in the channel");throw UD.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const n=new dP(Xw.REMOTE_USER_IS_NOT_PUBLISHED);throw UD.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),n}UD.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),UD.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===Xw.DISCONNECT_P2P)return void UD.warning("disconnecting p2p, abort unsubscribe request.");throw UD.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(eO(e,"unsubscribeList"),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");UD.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let{user:t,mediaType:n}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join())),e=[...e];const t=new Map;for(let n=e.length-1;n>=0;n--){const{user:i,mediaType:r}=e[n];if(!i){const e=new dP(Xw.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw UD.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Zw(r,"mediaType",["video","audio",void 0]);const o=this._users.find((e=>e===i));if(!o){UD.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(i.uid,", user is not in the channel")),e.splice(n,1);continue}const s=cx.Video|cx.LowVideo;if(t.has(i)){const o=t.get(i);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&cx.Audio;break;default:a=o&(cx.Audio|s)}if(a){UD.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(i.uid,",mediaType:").concat(r," twice.")),e.splice(n,1);continue}r?"audio"===r?t.set(i,o|cx.Audio):"video"===r&&t.set(i,o|s):t.set(i,o|cx.Audio|s)}else r?"audio"===r?t.set(i,cx.Audio):"video"===r&&t.set(i,s):t.set(i,cx.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),UD.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let{user:t,mediaType:n}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join()))}catch(e){if(e.code===Xw.DISCONNECT_P2P)return void UD.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw UD.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new Jw(Xw.INVALID_PARAMS);tO(e.width)||Qw(e.width,"streamParameter.width"),tO(e.height)||Qw(e.height,"streamParameter.height"),tO(e.framerate)||Qw(e.framerate,"streamParameter.framerate"),tO(e.bitrate)||qw(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&UD.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),UD.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,Rx.LocalVideoLowTrack)}async setDualStreamMode(e,t){Zw(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{UD.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):UD.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case RO.AUTO_SIMULCAST_STREAM:UD.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case RO.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case RO.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw UD.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!uP().supportDualStream)throw cP.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new dP(Xw.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new dP(Xw.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw cP.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=RO.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{UD.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),cP.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),UD.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void UD.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(Rx.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw cP.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=RO.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{UD.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),cP.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),UD.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){Zw(e,"role",["audience","host"])}(e),t&&vO(t),"rtc"===this.mode||"p2p"===this.mode)throw UD.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new dP(Xw.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new dP(Xw.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new dP(Xw.INVALID_OPERATION,"can not set client role to audience when publishing stream");const n=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==n&&iD("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",bO.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),UD.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===n&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof d4){const{video_codec:e}=this._pendingRtpCapabilityChange;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>{var t;return Di(t=Object.keys(aD)).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&&vO(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{UD.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 n=t.timestamp-Date.now();return Math.abs(n)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?n:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if($w(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new dP(Xw.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,cP.setProxyServer(this._proxyServer),UD.setProxyServer(this._proxyServer),UD.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 dP(Xw.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new dP(Xw.INVALID_OPERATION,"You have already set the proxy")}if(SO(e))return this._turnServer={servers:e,mode:"original-manual"},void UD.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>TO(e))),this._turnServer={servers:e,mode:"manual"},UD.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new dP(Xw.INVALID_OPERATION,"you should set license before join channel")}if($w(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new dP(Xw.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,UD.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new dP(Xw.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let n;switch(void 0===e&&(e=3),e){case 1:case 2:throw new dP(Xw.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:n="proxy3";break;case 4:n="proxy4";break;case 5:n="proxy5";break;default:throw new dP(Xw.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=n,this.store.cloudProxyServerMode=n,UD.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"Stop proxy server after leave channel");cP.setProxyServer(),UD.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",UD.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 dP(Xw.INVALID_PARAMS,"accessPoints is required.");eO(e.accessPoints.serverList,"accessPoints.serverList"),$w(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{qw(e,t,0,65535,!0)};let n=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),n=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new dP(Xw.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");iD("CLOSE_AFB_FOR_LOCAL_AP")&&(nD("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),nD("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const i=/^((\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=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),s=o.map((e=>"".concat(e,":").concat(n)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,nD("WEBCS_DOMAIN",s),nD("WEBCS_DOMAIN_BACKUP_LIST",s),nD("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(eO(e.report.hostname,"report.hostname"),nD("EVENT_REPORT_DOMAIN",e.report.hostname[0]),nD("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(nD("EVENT_REPORT_DOMAIN",o[0]),nD("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),nD("STATS_COLLECTOR_PORT",a),e.report?nD("ENABLE_EVENT_REPORT",!0):nD("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(eO(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),nD("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(eO(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),nD("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?nD("ENABLE_CONFIG_DISTRIBUTE",!0):nD("ENABLE_CONFIG_DISTRIBUTE",!1),UD.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(eO(e,"serverList"),$w(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new dP(Xw.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const n=/^(\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=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,nD("WEBCS_DOMAIN",e),nD("WEBCS_DOMAIN_BACKUP_LIST",e),nD("GATEWAY_DOMAINS",[t]),nD("EVENT_REPORT_DOMAIN",e[0]),nD("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),nD("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),UD.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Zw(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 UD.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else UD.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Zw(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 UD.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}UD.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Zw(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw UD.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}UD.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,n,i){!function(e){Zw(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),$w(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Di(r).call(r,e)){if(!n||!(n instanceof Uint8Array&&32===n.length))throw new dP(Xw.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(n)throw new dP(Xw.INVALID_PARAMS,"current encrypt mode does not need salt");if(i){if(zw(i,"encryptDataStream"),!Di(r).call(r,e))throw new dP(Xw.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||UD.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,n&&(this._encryptionSalt=HO(n))}async renewToken(e){if($w(e,"token",1,2047),!this._key||!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const n=await this._renewTokenMutex.lock();try{if(iD("USE_NEW_TOKEN")){UD.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await j3(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||EN);UD.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else UD.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});UD.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,UD.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{n()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?UD.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(yO.VOLUME_INDICATOR,e)}),iD("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 dP(Xw.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new dP(Xw.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 dP(Xw.LIVE_STREAMING_TASK_CONFLICT);const n=t?HV.TRANSCODE:HV.RAW;return this._createLiveStreamingClient(n).startLiveStreamingTask(e,n)}setLiveTranscoding(e){return this._createLiveStreamingClient(HV.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new dP(Xw.INVALID_PARAMS,"can not find live streaming url to stop");await Wh.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){$3(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){$3(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 d4&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new dP(Xw.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 i=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Di(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(i=!0,e.payload=await async function(e,t,n){var i;const r=zi(i=Array.from(n)).call(i,((e,t)=>e+t),0),o={serverTs:0,seq:hD++,length:n.length,checkSum:r},s=new Uint8Array(sN(r,2)),a=new ArrayBuffer(uD),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-n.length%16;n=JO(n,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:cD,additionalData:s},t,n);return JO(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new dP(Xw.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(FV.DATA_STREAM,{payload:HO(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-p4},!n)}sendMetadata(e){if(!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new dP(Xw.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(FV.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:HO(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(xD),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"can not send custom report, not joined");await cP.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(iD("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((n=>{Di(t).call(t,n)||delete e[n]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){Zw(t.spatialLayer,"spatialLayer",[0,1,2,3]),Zw(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw UD.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:n}=e;if(zw(t,"apRTM"),qw(n,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=n,UD.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=n,this._gateway.setRTM2Flag(n)}_reset(){if(UD.debug("[".concat(this._clientId,"] reset client")),function(e){const t=HU.indexOf(e);-1!==t&&HU.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=$A.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&G4(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&cP.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&cP.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 pN("client-publish",this._clientId),this._subscribeMutex=new pN("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 n;const i=e||eN();e?UD.debug("[".concat(this._clientId,"] new Session ").concat(i)):UD.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i));const r=e?"":this._sessionId||"";this._sessionId=i,this.store.sessionId=i,cP.addSid(i);const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:2,stringUid:(null==t?void 0:t.stringUid)||(null===(n=this._joinInfo)||void 0===n?void 0:n.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};cP.sessionInit(this._sessionId,f8({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new dP(Xw.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&iD("FORCE_TURN")&&!iD("TURN_ENABLE_TCP")&&!iD("TURN_ENABLE_UDP"))throw new dP(Xw.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");UD.debug("[".concat(this._clientId,"] publish high stream"));try{const n=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await n.next()).value;if(e){try{await this._gateway.sendExtensionMessage(Lx.PUBLISH,e,!0)}catch(e){throw n.throw(e),e}await n.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const i=(await n.next()).value;if(i){var t;let e;try{e=await this._gateway.publish(this._uid,i,!0)}catch(e){if(e.code!==Xw.DISCONNECT_P2P)throw n.throw(e),e}await n.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof MM&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{UD.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)===Xw.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new dP(Xw.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));UD.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),n=(await e.next()).value;if(n){var t;let i;try{i=await this._gateway.publish(this._uid,n,!0)}catch(t){if(t.code!==Xw.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=i)||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)===Xw.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new dP(Xw.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},X2("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{cP.reportApiInvoke(this._sessionId,{name:_O.ON_LIVE_STREAM_ERROR,options:[e,t],tag:EO.TRACER}).onSuccess(),this.safeEmit(yO.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{cP.reportApiInvoke(this._sessionId,{name:_O.ON_LIVE_STREAM_WARNING,options:[e,t],tag:EO.TRACER}).onSuccess(),this.safeEmit(yO.LIVE_STREAMING_WARNING,e,t)},e.on(QV.REQUEST_WORKER_MANAGER_LIST,((e,t,n)=>{if(!this._joinInfo)return n(new dP(Xw.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,n,i){const r=iD("UAP_AP").slice(0,iD("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 f3(r,e,t,n,i)})(e,this._joinInfo,this._axiosCancelSource.token,EN).then(t).catch(n)})),e};return e===HV.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new dP(Xw.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const{sendResolutionWidth:t,sendResolutionHeight:n}=this.getLocalVideoStats(),i=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:n}},X2("ChannelMediaRelay").create(e));i.on("state",(e=>{e===ix.RELAY_STATE_FAILURE&&i&&i.dispose(),this.safeEmit(yO.CHANNEL_MEDIA_RELAY_STATE,e)})),i.on("event",(e=>{this.safeEmit(yO.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=i,this._statsCollector.onStatsChanged=(e,t)=>{var n;"resolution"===e&&(null===(n=this._channelMediaRelayClient)||void 0===n||n.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],n=[];this._users.forEach((i=>{const r=i._dataChannels;r.forEach((n=>{e.some((e=>e.uid===i._uintid&&e.stream_id===n.id&&e.metadata===n.metadata))||t.push({uid:i._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})})),e.filter((e=>e.uid===i._uintid)).forEach((e=>{if(!r.some((t=>i._uintid===e.uid&&t.id===e.stream_id&&t.metadata===e.metadata))){const r=t.findIndex((t=>i._uintid===t.uid&&t.stream_id===e.stream_id));-1!==r&&(n.push(e),t.splice(r,1))}}))})),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(n),this._handleDataChannelAdded(e,!0),UD.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map((e=>e.stream_id)))),this.safeEmit(yO.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){const n=[];Array.isArray(e)&&e.length>0&&(UD.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," added")),e.forEach((e=>{const{uid:i,stream_id:r,ordered:o,max_retrans_times:s,metadata:a}=e,c=this._users.find((e=>e._uintid===i));if(!c)return void UD.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));UD.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Di(n).call(n,c)||n.push(c),c._uintid||(c._uintid=i);const d=-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id));if(d){const t=c._dataChannels.find((t=>t.id===e.stream_id));null==t||t._updateDataChannelConfig(f8(f8({},null==t?void 0:t.getConfig()),{},{metadata:e.metadata}))}else{const e={id:r,ordered:!!o,maxRetransmits:s,metadata:a},n=function(e){return J2(e,!0)}(e);c._dataChannels.push(n),UD.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(yO.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(UD.debug("[".concat(this._clientId,"] resubscribe datachannel id: ").concat(e.stream_id," for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{UD.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(UD.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," updated")),e.forEach((e=>{var t;const{uid:n,stream_id:i,metadata:r}=e,o=this._users.find((e=>e._uintid===n));if(!o)return void UD.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const s=o._dataChannels.find((e=>e.id===i));UD.debug("[".concat(this._clientId,"] data_channel: ").concat(i," updated with uid ").concat(n,", last metadata: ").concat(null==s||null===(t=s._config)||void 0===t?void 0:t.metadata,", new metadata: ").concat(r)),this.safeEmit(yO.USER_UNPUBLISHED,o,"datachannel",null==s?void 0:s._config),this.safeEmit(yO.USER_PUBLISHED,o,"datachannel",{id:i,ordered:!!e.ordered,maxRetransmits:e.max_retrans_times,metadata:r})})))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(UD.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," deleted")),e.forEach((e=>{const{uid:t,stream_id:n}=e,i=this._users.find((e=>e._uintid===t));if(!i)return void UD.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=i._dataChannels.find((t=>t.id===e.stream_id));r&&(UD.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),i._dataChannels=i._dataChannels.filter((e=>e.id!==r.id)),this._p2pChannel.unsubscribeDataChannel(i,[r]).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,i.uid)})),UD.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel , id:").concat(r.id)),this.safeEmit(yO.USER_UNPUBLISHED,i,"datachannel",r._config))})))}_handleUpdateDataChannel(e){const{added:t,deleted:n}=e;this._handleDataChannelDeleted(null!=n?n:[]),this._handleDataChannelAdded(null!=t?t:[])}_getEncodingName(e){var t,n;if(!this._joinResponse)return;const i=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!i)return;for(const t of i){var r;if(t.payloadType===e)return null==t||null===(r=t.rtpMap)||void 0===r?void 0:r.encodingName}const o=null===(n=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===n?void 0:n.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){UD.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const n=()=>{UD.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(yO.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),n()}}else UD.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(sx.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void UD.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();Object.keys(t).forEach((e=>{const{value:i,type:r,expires:o}=t[e];o&&o<=n||r||JU()||!Object.prototype.hasOwnProperty.call(qN,e)||(oD[e]=i,tD[e]=i,UD.debug("Update gateway parameters from config distribute",e,i))}))}catch(e){UD.error("Error update config from local cache",e.message)}}()})),this._gateway.on(sx.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(sx.CONNECTION_STATE_CHANGE,((e,t,n)=>{var i;if(n===gO.FALLBACK)return;const r=()=>{this.safeEmit(yO.CONNECTION_STATE_CHANGE,e,t,n)};if(cP.reportApiInvoke(this._sessionId||(null===(i=this._gateway.joinInfo)||void 0===i?void 0:i.sid)||null,{name:_O.CONNECTION_STATE_CHANGE,options:[e,t,n],tag:EO.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:n})),UD.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=>{UD.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{UD.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),iD("VOS_CONFIGURE")&&Array.isArray(iD("VOS_CONFIGURE"))&&iD("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(iD("VOS_CONFIGURE")).catch((e=>{UD.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),UD.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((()=>{UD.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{UD.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{UD.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=>{UD.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_||(UD.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,fx.AUDIO,!1)),e._trust_video_mute_state_||(UD.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,fx.VIDEO,!1)),e._trust_audio_enabled_state_||(UD.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(UD.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(UD.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(UD.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(UD.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(sx.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new dP(Xw.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,cP.reportApiInvoke(this._sessionId,{name:_O.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:EO.TRACER}).onSuccess(),UD.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await V4(f8(f8({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,j4(e),this._joinInfo.preload=!0):(t=await L3(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,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,delete this._joinInfo.signalResponse);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[i,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:r}):n.push({host:i,port:r})})),e(n)}catch(e){t(e)}})),this._gateway.on(sx.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(yO.NETWORK_QUALITY,e)})),this._gateway.on(sx.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(yO.STREAM_TYPE_CHANGED,e,t);cP.reportApiInvoke(this._sessionId,{name:_O.STREAM_TYPE_CHANGE,options:[e,t],tag:EO.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(sx.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(sx.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,n)=>{try{let n=await this._p2pChannel.getEstablishParams();n&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(n=await this._p2pChannel.startP2PConnection(e)),t(n)}catch(e){n(e)}})),this._gateway.on(sx.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let n;this._joinResponse=e,e.attributes?n=e.attributes.userAttributes.preSubSsrcs:UD.debug("no attributes in joinResponse");const i=R2(e.ortc,t,n);this._p2pChannel.connect(i)})),this._gateway.on(sx.PRE_CONNECT_PC,(async(e,t,n)=>{const{candidates:i,fingerprint:r,turnServer:o}=e;if(this._joinInfo&&i.length>0&&!this._p2pChannel.isPlanB){var s,a;const{cert:d,cid:l}=this._joinInfo.apResponse,u="".concat(l,"_").concat(d),h=e.iceUfrag||u,p=e.icePwd||u;if(!Z2(h,p))return void UD.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(h.length," / ").concat(p.length));let _;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),UD.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});const E=null===(s=this._joinInfo.signalResponse)||void 0===s||null===(s=s.attributes)||void 0===s||null===(s=s.userAttributes)||void 0===s?void 0:s.preSubSsrcs;Array.isArray(E)&&E.length>0&&(_=v2(E));const m=null===(a=this._joinInfo.signalResponse)||void 0===a?void 0:a.rtpCapabilities;try{var c;t(await this._p2pChannel.connect(f8({iceParameters:{iceUfrag:h,icePwd:p},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(c=iD("FINGERPRINT"))&&void 0!==c?c:r}]},candidates:i,rtpCapabilities:m||{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},_?{preSSRCs:_}:{})))}catch(e){e.code&&e.code===Xw.EXCHANGE_SDP_FAILED&&(UD.debug("try to pre connect pc, but exchange sdp failed, reset p2p connection",e),await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)),n(e)}}})),this._gateway.on(sx.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(yO.FALLBACK_TO_HLS,CO.VOSERROR)})),this._gateway.on(sx.RESET_SIGNAL,(()=>{this._p2pChannel instanceof d4&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(sx.DATACHANNEL_FAILBACK,(()=>{cP.reportApiInvoke(this._sessionId,{name:_O.DATACHANNEL_FAILBACK,options:{},tag:EO.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(GV.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(GV.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(GV.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(GV.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(GV.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(GV.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{var t;this._handleFullDatachannel(null!==(t=e.datastreams)&&void 0!==t?t:[])})),this._gateway.signal.on(GV.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(GV.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(GV.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,fx.AUDIO,!0))),this._gateway.signal.on(GV.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,fx.AUDIO,!1))),this._gateway.signal.on(GV.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,fx.VIDEO,!0))),this._gateway.signal.on(GV.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,fx.VIDEO,!1))),this._gateway.signal.on(GV.RECEIVE_METADATA,(e=>{const t=YO(e.metadata);this.safeEmit(yO.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(GV.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let n=YO(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Di(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<uD)throw new dP(Xw.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(uD));const t=await async function(e,t,n){const i=n.subarray(0,uD),r=i.slice(8,uD),o=(r[0]<<8)+r[1],s=(i[6]<<8)+i[7],a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:cD,additionalData:new Uint8Array(sN(o,2))},t,n.subarray(uD));return new Uint8Array(a).subarray(0,s)}(this._encryptDataStreamIv,this._encryptDataStreamKey,n);n=t}let i=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));i=null==r?void 0:r.jitterBufferMs}(null==i||Number.isNaN(i))&&(i=0),S4(f8(f8({},e),{},{payload:n}),i,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(GV.ON_CRYPT_ERROR,(()=>{KO((()=>{UD.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(yO.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(GV.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(GV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{UD.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,gO.TOKEN_EXPIRE),this.safeEmit(yO.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(GV.ON_STREAM_FALLBACK_UPDATE,(e=>{UD.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(yO.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(GV.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===RO.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{UD.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(GV.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),UD.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(GV.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(GV.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(xV.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case FV.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var n,i;const r=e.some((e=>{let{stream_type:t}=e;return t===ox.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t!==ox.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===ox.Screen||t===ox.ScreenLow}));"offer"===t.state&&cP.publish(this._joinInfo.sid,{eventElapse:J3.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Xw.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(n=e.find((e=>{let{stream_type:t}=e;return t===ox.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0,videoName:o?null===(i=e.find((e=>{let{stream_type:t}=e;return t!==ox.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0})}break}case FV.SUBSCRIBE:t&&cP.subscribe(this._joinInfo.sid,{succ:!1,ec:Xw.TIMEOUT,audio:t.stream_type===fx.AUDIO,video:t.stream_type===fx.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:J3.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(GV.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(GV.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;let t=e.users;iD("BLOCK_LOCAL_CLIENT")&&(t=t.filter((e=>!XU(e.string_id||e.stream_id,this.channelName)))),this._handleUserList(t)})),this._gateway.signal.on(GV.ON_USER_LIST,(e=>{if(!e||!Array.isArray(e.users)||0===e.users.length)return;let t=e.users;t=iD("BLOCK_LOCAL_CLIENT")?t.filter((e=>!XU(e.string_id||e.stream_id,this.channelName))):t,this._handleUserList(t)})),this._gateway.signal.on(GV.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;if(this._p2pChannel instanceof d4){if("audience"===this.role&&iD("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void UD.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 Di(t=Object.keys(aD)).call(t,e)})))}})),this._gateway.signal.on(xV.VOS_FALLBACK_PROMISE,(async(e,t,n)=>{if("FALLBACKCN"===e&&iD("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return n(new dP(Xw.UNEXPECTED_ERROR,"can not recover, no join info"));UD.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const i=await L3(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||EN,this.store);if(iD("QUALITY_FALLBACK_REHEARSAL"))return cP.reportApiInvoke(this._sessionId,{name:_O.VOS_FALLBACK_CN,options:{cur:i.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:EO.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void n();this._fallbackServerInfo=i,t()}catch(e){var i;const t=null==e||null===(i=e.data)||void 0===i?void 0:i.desc;iD("QUALITY_FALLBACK_REHEARSAL")?(cP.reportApiInvoke(this._sessionId,{name:_O.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:EO.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(t)&&Di(t).call(t,"request downgrade fallback")&&this.safeEmit(yO.FALLBACK_TO_HLS,CO.AP_ERROR),n(e)}}else n()}))}_handleUserList(e){var t=this;if(0===e.length)return;const n=[],i=[],r=[],o=[],s=[],a=[],c=this.getListeners(yO.USER_LIST).length>0,d=this.getListeners(yO.PUBLISHED_USER_LIST).length>0;for(const t of e){let e=this._users.find((e=>e._uintid===t.stream_id));const c=!!e;e?e._trust_in_room_=!0:(e=new e5(t.string_id||t.stream_id,t.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}));const d=cx.Audio&t.stream_type,l=(cx.Video|cx.LowVideo)&t.stream_type,u=0!=(65280&t.stream_type),h=d&&e.hasAudio,p=l&&e.hasVideo;l&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=t.video_ssrc,e._rtxSsrcId=t.video_rtx),d&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=t.audio_ssrc),(d&&!h||l&&!p||u)&&(i.push(e),d&&!h&&r.push(e),l&&!p&&o.push(e)),c||s.push(e),l&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&a.push({user:e,mediaType:"video"}),d&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&a.push({user:e,mediaType:"audio"}),n.push(e)}a.length>0&&(UD.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(a.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(a).catch((e=>{UD.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})));const l=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];UD.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),e||s.forEach((e=>{UD.debug("[".concat(t._clientId,"] user online"),e._uintid),t.safeEmit(yO.USER_JOINED,e)})),i.length>0&&(r.forEach((e=>{UD.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published audio")),t.safeEmit(yO.USER_PUBLISHED,e,"audio")})),o.forEach((e=>{UD.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published video")),t.safeEmit(yO.USER_PUBLISHED,e,"video")})))};if(iD("ENABLE_USER_LIST"))c?(this.safeEmit(yO.USER_LIST,n),l(!0)):l();else if(d){if(i.length>0){const e=zi(i).call(i,((e,t)=>"".concat(e&&e+", ").concat(t.uid)),"");iD("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=i:(UD.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(e)),this.safeEmit(yO.PUBLISHED_USER_LIST,i))}}else l()}_handleP2PEvents(){this._gateway.signal.on(GV.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(Lx.PUBLISH,((e,t,n)=>{const{uid:i}=e;e.forEach((e=>{const{kind:r,ssrcs:o,mid:s,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,i,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===i));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(n):t(),this._handleMuteStream(i,r,!!a)}))})),this._gateway.signal.on(Lx.CALL,(async(e,t,n)=>{if(this.store.useP2P)try{var i;t(await this._p2pChannel.startP2P({turnServer:null===(i=this._joinInfo)||void 0===i?void 0:i.turnServer},e))}catch(e){n(e)}})),this._gateway.signal.on(xV.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(Lx.UNPUBLISH,(async(e,t,n)=>{if(this.store.useP2P){const{unpubMsg:i,uid:r}=e,o=this._users.find((e=>e.uid===r));if(!o)return UD.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{i.forEach((async e=>{let{stream_type:t}=e;const n=t===ox.Audio?fx.AUDIO:fx.VIDEO;await this._p2pChannel.unsubscribe(o,n),this._handleMuteStream(r,n,!0)})),t()}catch(e){n(e)}}})),this._gateway.signal.on(Lx.CONTROL,(async(e,t)=>{const{action:n}=e;switch(n){case Mx.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,fx.VIDEO,!0);break;case Mx.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,fx.AUDIO,!0);break;case Mx.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,fx.VIDEO,!1);break;case Mx.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,fx.AUDIO,!1)}})),this._gateway.signal.on(Lx.RESTART_ICE,(async(e,t,n)=>{if(this.store.useP2P)try{const{direction:n,iceParameter:i}=e;if(n!==jV.SEND_ONLY||i){t(await this._p2pChannel.restartICE(n,i))}else this._p2pChannel.handleDisconnect(n),t()}catch(e){n(e)}})),this._gateway.signal.on(Lx.CANDIDATE,(e=>{if(this.store.useP2P){const{candidate:t,direction:n}=e;this._p2pChannel.addRemoteCandidate(t,n)}})),this._p2pChannel.on(yx.RequestP2PRestartICE,(async(e,t,n)=>{try{const{direction:n}=e;t(await this._gateway.sendExtensionMessage(Lx.RESTART_ICE,e,n===jV.SEND_ONLY))}catch(e){n(e)}})),this._p2pChannel.on(yx.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(Lx.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(yx.RequestP2PMuteLocal,(async(e,t,n)=>{try{await this._gateway.sendExtensionMessage(Lx.CONTROL,e,!0),t()}catch(e){n(e)}})),this._p2pChannel.on(yx.RequestP2PUnmuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Xw.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(yx.RequestP2PMuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Xw.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(yx.StateChange,((e,t)=>{t===vx.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(yx.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(yO.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(yx.RequestMuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Xw.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(yx.RequestUnmuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Xw.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(yx.RequestRePublish,((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),this._p2pChannel.on(yx.RequestRePublishDataChannel,((e,t,n)=>{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!==Xw.DISCONNECT_P2P)throw e}}))).then(t).catch(n)})),this._p2pChannel.on(yx.RequestReSubscribe,(async(e,t,n)=>{try{for(const{user:t,kind:n}of e)n===fx.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){n(e)}})),this._p2pChannel.on(yx.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(yx.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(yx.MediaReconnectStart,(e=>{this.safeEmit(yO.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(yx.MediaReconnectEnd,(e=>{this.safeEmit(yO.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(yx.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(yx.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),n=await t.next();if(n.done)return;const i=n.value;let r;try{r=await this._gateway.restartICE({iceParameters:i})}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(yx.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(yx.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}=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:n,rtpCapabilities:i}),s=R2(r,o);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(yx.RequestUnpublishForReconnectPC,(async(e,t,n)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):n()})),this._p2pChannel.on(yx.P2PLost,(()=>{this.safeEmit(yO.P2P_LOST,this.store.uid)})),this._p2pChannel.on(yx.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(yx.ConnectionTypeChange,(e=>{this.safeEmit(yO.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(yx.FirstVideoBufferReady,((e,t)=>{this.safeEmit(yO.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(yx.FirstVideoPreRender,((e,t)=>{this.safeEmit(yO.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(yx.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(yx.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(yx.AudioMetadata,(e=>{this.safeEmit(yO.AUDIO_METADATA,e)})),this._p2pChannel.on(yx.AudioPts,(e=>{this.safeEmit(yO.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new dP(Xw.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new dP(Xw.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const n=(t={config:e},X2("ContentInspect").create(t));this._inspect=n,this.handleVideoInspectEvents(n);const{appId:i,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await n.init({appId:i,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},EN)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(Ix.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(yO.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,n),n===Cx.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(yO.CONTENT_INSPECT_ERROR,new dP(Xw.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(Ix.INSPECT_RESULT,((e,t)=>{var n;if((null==t?void 0:t.code)===Xw.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return UD.debug("Stop inspect content because that has left channel"),null==this||null===(n=this._inspect)||void 0===n||n.close(),void(this._inspect=void 0);this.safeEmit(yO.CONTENT_INSPECT_RESULT,e,t)})),e.on(Ix.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new dP(Xw.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(zw(e,"enabled"),e){if(!t)throw new dP(Xw.INVALID_PARAMS,"config is required");if(b6(t),!this._joinInfo)throw new dP(Xw.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(n={config:t},X2("ImageModeration").create(n));this._moderation=e,this.handleImageModerationEvents(e);const{appId:i,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await e.init({appId:i,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},EN)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var n;if(!this._moderation)throw new dP(Xw.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(Dx.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(yO.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,n),t===Nx.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new dP(Xw.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(Dx.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){Zw(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new dP(Xw.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,UD.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return UD.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){zw(e,"enabled"),nD("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}}},DV(E8.prototype,"leave",[A6],Object.getOwnPropertyDescriptor(E8.prototype,"leave"),E8.prototype),DV(E8.prototype,"publish",[w6],Object.getOwnPropertyDescriptor(E8.prototype,"publish"),E8.prototype),DV(E8.prototype,"unpublish",[O6],Object.getOwnPropertyDescriptor(E8.prototype,"unpublish"),E8.prototype),DV(E8.prototype,"subscribe",[N6],Object.getOwnPropertyDescriptor(E8.prototype,"subscribe"),E8.prototype),DV(E8.prototype,"presubscribe",[D6],Object.getOwnPropertyDescriptor(E8.prototype,"presubscribe"),E8.prototype),DV(E8.prototype,"massSubscribe",[P6],Object.getOwnPropertyDescriptor(E8.prototype,"massSubscribe"),E8.prototype),DV(E8.prototype,"unsubscribe",[L6],Object.getOwnPropertyDescriptor(E8.prototype,"unsubscribe"),E8.prototype),DV(E8.prototype,"massUnsubscribe",[k6],Object.getOwnPropertyDescriptor(E8.prototype,"massUnsubscribe"),E8.prototype),DV(E8.prototype,"setLowStreamParameter",[M6],Object.getOwnPropertyDescriptor(E8.prototype,"setLowStreamParameter"),E8.prototype),DV(E8.prototype,"setDualStreamMode",[U6],Object.getOwnPropertyDescriptor(E8.prototype,"setDualStreamMode"),E8.prototype),DV(E8.prototype,"enableDualStream",[V6],Object.getOwnPropertyDescriptor(E8.prototype,"enableDualStream"),E8.prototype),DV(E8.prototype,"disableDualStream",[x6],Object.getOwnPropertyDescriptor(E8.prototype,"disableDualStream"),E8.prototype),DV(E8.prototype,"setClientRole",[F6],Object.getOwnPropertyDescriptor(E8.prototype,"setClientRole"),E8.prototype),DV(E8.prototype,"_setClientRoleOptions",[B6],Object.getOwnPropertyDescriptor(E8.prototype,"_setClientRoleOptions"),E8.prototype),DV(E8.prototype,"setProxyServer",[G6],Object.getOwnPropertyDescriptor(E8.prototype,"setProxyServer"),E8.prototype),DV(E8.prototype,"setTurnServer",[j6],Object.getOwnPropertyDescriptor(E8.prototype,"setTurnServer"),E8.prototype),DV(E8.prototype,"setLicense",[W6],Object.getOwnPropertyDescriptor(E8.prototype,"setLicense"),E8.prototype),DV(E8.prototype,"startProxyServer",[K6],Object.getOwnPropertyDescriptor(E8.prototype,"startProxyServer"),E8.prototype),DV(E8.prototype,"stopProxyServer",[Y6],Object.getOwnPropertyDescriptor(E8.prototype,"stopProxyServer"),E8.prototype),DV(E8.prototype,"setLocalAccessPointsV2",[H6],Object.getOwnPropertyDescriptor(E8.prototype,"setLocalAccessPointsV2"),E8.prototype),DV(E8.prototype,"setLocalAccessPoints",[X6],Object.getOwnPropertyDescriptor(E8.prototype,"setLocalAccessPoints"),E8.prototype),DV(E8.prototype,"setRemoteDefaultVideoStreamType",[J6],Object.getOwnPropertyDescriptor(E8.prototype,"setRemoteDefaultVideoStreamType"),E8.prototype),DV(E8.prototype,"setRemoteVideoStreamType",[z6],Object.getOwnPropertyDescriptor(E8.prototype,"setRemoteVideoStreamType"),E8.prototype),DV(E8.prototype,"setStreamFallbackOption",[Z6],Object.getOwnPropertyDescriptor(E8.prototype,"setStreamFallbackOption"),E8.prototype),DV(E8.prototype,"setEncryptionConfig",[q6],Object.getOwnPropertyDescriptor(E8.prototype,"setEncryptionConfig"),E8.prototype),DV(E8.prototype,"renewToken",[Q6],Object.getOwnPropertyDescriptor(E8.prototype,"renewToken"),E8.prototype),DV(E8.prototype,"enableAudioVolumeIndicator",[$6],Object.getOwnPropertyDescriptor(E8.prototype,"enableAudioVolumeIndicator"),E8.prototype),DV(E8.prototype,"startLiveStreaming",[e8],Object.getOwnPropertyDescriptor(E8.prototype,"startLiveStreaming"),E8.prototype),DV(E8.prototype,"setLiveTranscoding",[t8],Object.getOwnPropertyDescriptor(E8.prototype,"setLiveTranscoding"),E8.prototype),DV(E8.prototype,"stopLiveStreaming",[n8],Object.getOwnPropertyDescriptor(E8.prototype,"stopLiveStreaming"),E8.prototype),DV(E8.prototype,"startChannelMediaRelay",[i8],Object.getOwnPropertyDescriptor(E8.prototype,"startChannelMediaRelay"),E8.prototype),DV(E8.prototype,"updateChannelMediaRelay",[r8],Object.getOwnPropertyDescriptor(E8.prototype,"updateChannelMediaRelay"),E8.prototype),DV(E8.prototype,"stopChannelMediaRelay",[o8],Object.getOwnPropertyDescriptor(E8.prototype,"stopChannelMediaRelay"),E8.prototype),DV(E8.prototype,"sendCustomReportMessage",[s8],Object.getOwnPropertyDescriptor(E8.prototype,"sendCustomReportMessage"),E8.prototype),DV(E8.prototype,"pickSVCLayer",[a8],Object.getOwnPropertyDescriptor(E8.prototype,"pickSVCLayer"),E8.prototype),DV(E8.prototype,"setRTMConfig",[c8],Object.getOwnPropertyDescriptor(E8.prototype,"setRTMConfig"),E8.prototype),DV(E8.prototype,"enableContentInspect",[d8],Object.getOwnPropertyDescriptor(E8.prototype,"enableContentInspect"),E8.prototype),DV(E8.prototype,"disableContentInspect",[l8],Object.getOwnPropertyDescriptor(E8.prototype,"disableContentInspect"),E8.prototype),DV(E8.prototype,"setImageModeration",[u8],Object.getOwnPropertyDescriptor(E8.prototype,"setImageModeration"),E8.prototype),DV(E8.prototype,"setP2PTransport",[h8],Object.getOwnPropertyDescriptor(E8.prototype,"setP2PTransport"),E8.prototype),DV(E8.prototype,"getJoinChannelServiceRecords",[p8],Object.getOwnPropertyDescriptor(E8.prototype,"getJoinChannelServiceRecords"),E8.prototype),DV(E8.prototype,"setPublishAudioFilterEnabled",[_8],Object.getOwnPropertyDescriptor(E8.prototype,"setPublishAudioFilterEnabled"),E8.prototype),E8);function S8(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=$O(5,"client-"),n=cP.reportApiInvoke(null,{id:t,name:_O.CREATE_CLIENT,options:[e],tag:EO.TRACER});try{var i;!function(e){Zw(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),Zw(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&Zw(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&$w(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&TO(e.turnServer),void 0!==e.httpRetryConfig&&mO(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&mO(e.websocketRetryConfig)}(e),(Ow(16,0,!0)||Nw(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",UD.debug("browser not support vp9, force use vp8")),nD("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus");const r=new g8(f8(f8({forceWaitGatewayResponse:!0},e),{},{role:Di(i=["rtc","p2p"]).call(i,e.mode)?"host":e.role||"audience"}),t);return n.onSuccess(),r}catch(e){throw n.onError(e),e}}function T8(){let e=!1;const t=lw();return(t.name===sw.CHROME&&Number(t.version)>=58&&("WebKit"!==cw.engine.name||function(){const e=lw();if(_w()){if(e.os===ow.MAC_OS)return!0;if(e.os===ow.IOS){const e=cw.os.version&&cw.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===sw.FIREFOX&&Number(t.version)>=56||t.name===sw.OPERA&&Number(t.version)>=45||t.name===sw.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(Rw()||Uw())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||Vw()||lw().name===sw.QQ)&&(e=!0),e}class R8{constructor(e,t){Db(this,"id",0),Db(this,"element",void 0),Db(this,"peerPair",void 0),Db(this,"context",void 0),Db(this,"audioPlayerElement",void 0),Db(this,"audioTrack",void 0),R8.count+=1,this.id=R8.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 n="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(n),"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 n=await e(this.peerPair[0],"offer");await t(this.peerPair[1],n);const i=await e(this.peerPair[1],"answer");await t(this.peerPair[0],i)}catch(e){throw new dP(Xw.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 dP(Xw.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new dP(Xw.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const n=t.stream.getAudioTracks()[0];return this.audioTrack=n,n}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(){UD.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 v8,y8;Db(R8,"count",0);const C8=window.AudioContext||window.webkitAudioContext;const b8=new(v8=aP({report:cP}),DV((y8=class{constructor(){Db(this,"units",[]),Db(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return UD.debug("the system does not need to process local aec"),-1;this.context||(this.context=new C8);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new R8(e,this.context),this.units.push(t)),t.startEchoCancellation(),UD.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return lw().name!==sw.SAFARI}}).prototype,"processExternalMediaAEC",[v8],Object.getOwnPropertyDescriptor(y8.prototype,"processExternalMediaAEC"),y8.prototype),y8);function I8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function A8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?I8(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):I8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const w8=window||document;function O8(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!w8)return;const n=U7._cspEventHandlerPointer;if(n&&t)return void console.error(n,t);const i=e=>{if(!(e&&e.blockedURI&&(U7.onSecurityPolicyViolation||U7.getListeners(Ox.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;iD("CSP_DETECTED_HOSTNAME_LIST").some((e=>Di(t).call(t,e)))&&(U7.onSecurityPolicyViolation&&"function"==typeof U7.onSecurityPolicyViolation&&U7.onSecurityPolicyViolation(e),U7.getListeners(Ox.SECURITY_POLICY_VIOLATION).length>0&&U7.safeEmit(Ox.SECURITY_POLICY_VIOLATION,e))};n&&w8.removeEventListener("securitypolicyviolation",n),(t||e&&"function"==typeof e||U7.getListeners(Ox.SECURITY_POLICY_VIOLATION).length>0)&&w8.addEventListener("securitypolicyviolation",i),U7._cspEventHandlerPointer=i}var N8=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(N8||{});class D8{constructor(){Db(this,"_sequence",0),Db(this,"_startTime",Date.now()),Db(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 n=new Uint8Array(4);n.set([1,0,0,0]);const i={id:0,length:4,data:n.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[i]};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;iD("SHOW_DATASTREAM2_LOG")&&UD.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const n=new ArrayBuffer(t.commonPacketHeader.length),i=new Uint8Array(n),r=new DataView(n);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);i.set(new Uint8Array(e),o),o+=e.byteLength}if(i.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return n}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let n=0;const i=t.getUint16(n,!0);n+=2;const r={length:16383&i,reserved:(16384&i)>>14,extension:(32768&i)>>15,sequence:t.getUint16(n+2,!0)<<16|t.getUint16(n,!0)};let o,s;if(n+=4,iD("SHOW_DATASTREAM2_LOG")&&UD.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(n,!0),n+=2,r.extension){s=this.deserializeExtension(e.slice(n)),n+=2+s.length,o=e.slice(n);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:n,datas:i}=e,r=new ArrayBuffer(n+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,n),i.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!==n+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(n+2));return r}deserializeExtension(e){const t=new DataView(e);let n=0;const i=t.getUint8(n);n++;const r=t.getUint8(n);n++;const o=i===N8.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,n=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&&(n=a.buffer.slice(c+2,c+2+t),c+=n.byteLength),s.push({id:e,length:t,data:n})}if(c!==r)throw Error("parse error");return{profile:i,length:r,datas:s}}decompress(e){return Lj(new Uint8Array(e))}compress(e){return Dj(new Uint8Array(e))}}const P8={name:"DataStream",create:(e,t)=>{const n=t?new iU(e):new rU(e);return n.useDataStream(new D8),n}};class L8 extends uO{constructor(e,t,n){super(),Db(this,"ws",void 0),Db(this,"requestId",1),Db(this,"heartBeatTimer",void 0),Db(this,"joinInfo",void 0),Db(this,"clientId",void 0),Db(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),Db(this,"onClose",(e=>{this.emit("close"),this.dispose()})),Db(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 $x("cross-channel-".concat(this.clientId),n),this.ws.on(WV.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(WV.CONNECTED,this.onOpen),this.ws.on(WV.ON_MESSAGE,this.onMessage),this.ws.on(WV.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,n)=>{const i=window.setTimeout((()=>{n(new dP(Xw.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(i),r.state&&0!==r.state?n(new dP(Xw.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(i),n(new dP(Xw.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new dP(Xw.WS_DISCONNECT);const t=()=>new Wh(((e,t)=>{this.ws.once(WV.CLOSED,(()=>t(new dP(Xw.WS_ABORT)))),this.ws.once(WV.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const n=this.sendMessage(e),i=new Wh(((e,t)=>{const i=()=>{t(new dP(Xw.WS_ABORT))};this.ws.once(WV.RECONNECTING,i),this.ws.once(WV.CLOSED,i),this.once("req_".concat(n),e),QO(3e3).then((()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(WV.RECONNECTING,i),this.ws.off(WV.CLOSED,i),t(new dP(Xw.TIMEOUT,"cross channel ws request timeout"))}))})),r=await i;if(!r||200!==r.code)throw new dP(Xw.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(WV.REQUEST_NEW_URLS),this.ws.on(WV.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 k8 extends uO{set state(e){e!==this._state&&(e!==ix.RELAY_STATE_FAILURE&&(this.errorCode=rx.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,n,i,r){super(),Db(this,"joinInfo",void 0),Db(this,"sid",void 0),Db(this,"clientId",void 0),Db(this,"cancelToken",$A.CancelToken.source()),Db(this,"workerToken",void 0),Db(this,"requestId",0),Db(this,"signal",void 0),Db(this,"prevChannelMediaConfig",void 0),Db(this,"httpRetryConfig",void 0),Db(this,"_resolution",void 0),Db(this,"_state",ix.RELAY_STATE_IDLE),Db(this,"errorCode",rx.RELAY_OK),Db(this,"onStatus",(e=>{UD.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",nx.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",nx.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=rx.SRC_TOKEN_EXPIRED,this.state=ix.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=rx.DEST_TOKEN_EXPIRED,this.state=ix.RELAY_STATE_FAILURE))})),Db(this,"onReconnect",(async()=>{UD.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",nx.NETWORK_DISCONNECTED),this.state=ix.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==ix.RELAY_STATE_IDLE&&(UD.error("auto restart channel media relay failed",e.toString()),this.errorCode=rx.SERVER_CONNECTION_LOST,this.state=ix.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=eN(),this.signal=new L8(this.joinInfo,this.clientId,n),this.httpRetryConfig=i,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==ix.RELAY_STATE_IDLE)throw new dP(Xw.INVALID_OPERATION);this.state=ix.RELAY_STATE_CONNECTING,await this.connect(),UD.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 dP(Xw.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new dP(Xw.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new dP(Xw.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==ix.RELAY_STATE_RUNNING)throw new dP(Xw.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==ix.RELAY_STATE_RUNNING)throw new dP(Xw.INVALID_OPERATION);const t=this.genMessage(tx.SetVideoProfile);await this.signal.request(t),UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),UD.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=ix.RELAY_STATE_IDLE,this.dispose()}dispose(){UD.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=$A.CancelToken.source(),this.state=ix.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await G3(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",nx.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(tx.SetSdkProfile,e);await this.signal.request(t),UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(tx.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",nx.PACKET_JOINED_SRC_CHANNEL),UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const i=this.genMessage(tx.SetSourceUserId,e);await this.signal.request(i),UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const r=this.genMessage(tx.SetDestChannel,e);await this.signal.request(r),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",nx.PACKET_JOINED_DEST_CHANNEL),UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(tx.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",nx.PACKET_SENT_TO_DEST_CHANNEL),this.state=ix.RELAY_STATE_RUNNING,UD.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(tx.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",nx.PACKET_UPDATE_DEST_CHANNEL),UD.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(tx.StopPacketTransfer);await this.signal.request(e),UD.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const n=[],i=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:XN,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.3"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case tx.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case tx.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new dP(Xw.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 tx.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new dP(Xw.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case tx.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new dP(Xw.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:n,uid:i,token:r},o;case tx.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case tx.Reconnect:return o.clientRequest={command:"Reconnect"},o;case tx.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case tx.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new dP(Xw.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:n,uid:i,token:r},o;case tx.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const M8={name:"ChannelMediaRelay",create:function(e){return new k8(e.joinInfo,e.clientId,e.websocketRetryConfig||EN,e.httpRetryConfig||EN,e.resolution)}};function U8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function V8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?U8(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):U8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class x8 extends uO{constructor(e,t,n,i){super(),Db(this,"spec",void 0),Db(this,"token",void 0),Db(this,"websocket",void 0),Db(this,"pingpongTimer",void 0),Db(this,"reconnectMode","retry"),Db(this,"serviceMode",void 0),Db(this,"reqId",0),Db(this,"commandReqId",0),Db(this,"handleWebSocketOpen",(()=>{this.reconnectMode="retry",this.startPingPong()})),Db(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(cP.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===HV.TRANSCODE?1:2}),this.emit(qV.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=i,this.websocket=new $x("live-streaming",n),this.websocket.on(WV.CONNECTED,this.handleWebSocketOpen),this.websocket.on(WV.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(WV.REQUEST_NEW_URLS,((e,t)=>{wO(this,qV.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(WV.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,n,i){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new dP(Xw.UNEXPECTED_ERROR);const s=V8({command:e,sdkVersion:"4.24.3"===XN?"0.0.1":XN,seq:o,requestId:o,allocate:n,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 dP(Xw.WS_DISCONNECT);const a=()=>new Wh(((e,t)=>{this.websocket.once(WV.CLOSED,(()=>t(new dP(Xw.WS_ABORT)))),this.websocket.once(WV.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Wh(((e,t)=>{const n=()=>{t(new dP(Xw.WS_ABORT))};this.websocket.once(WV.RECONNECTING,n),this.websocket.once(WV.CLOSED,n),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));i&&cP.workerEvent(this.spec.sid,V8(V8({},i),{},{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(i){if("closed"===this.websocket.state)throw i;return await a(),await this.request(e,t,n)}return i&&cP.workerEvent(this.spec.sid,V8(V8({},i),{},{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.3"===XN?"0.0.1":XN;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 $V.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void UD.warning("live stream response already exists stream");case $V.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case $V.LIVE_STREAM_RESPONSE_BAD_STREAM:case $V.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new dP(Xw.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case $V.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case $V.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new dP(Xw.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case $V.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new dP(Xw.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(qV.WARNING,t,e.serverResponse.url)}case $V.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new dP(Xw.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(qV.WARNING,t,e.serverResponse.url)}case $V.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case $V.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new dP(Xw.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case $V.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new dP(Xw.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(qV.WARNING,t,e.serverResponse.url)}case $V.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case $V.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case $V.LIVE_STREAM_RESPONSE_WORKER_LOST:case $V.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case $V.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case $V.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new dP(Xw.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(tN)}),6e3)}}function F8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function B8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?F8(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):F8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class G8 extends uO{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:EN,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:EN;super(),Db(this,"onLiveStreamWarning",void 0),Db(this,"onLiveStreamError",void 0),Db(this,"spec",void 0),Db(this,"retryTimeout",1e4),Db(this,"connection",void 0),Db(this,"httpRetryConfig",void 0),Db(this,"wsRetryConfig",void 0),Db(this,"streamingTasks",new Map),Db(this,"isStartingStreamingTask",!1),Db(this,"taskMutex",new pN("live-streaming")),Db(this,"cancelToken",$A.CancelToken.source()),Db(this,"transcodingConfig",void 0),Db(this,"uapResponse",void 0),Db(this,"lastTaskId",1),Db(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=n,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=B8(B8({},ZV),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(UD.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=>B8(B8(B8({},XV),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){tO(e.width)||qw(e.width,"config.width",0,1e4),tO(e.height)||qw(e.height,"config.height",0,1e4),tO(e.videoBitrate)||qw(e.videoBitrate,"config.videoBitrate",1,1e6),tO(e.videoFrameRate)||qw(e.videoFrameRate,"config.videoFrameRate"),tO(e.lowLatency)||zw(e.lowLatency,"config.lowLatency"),tO(e.audioSampleRate)||Zw(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),tO(e.audioBitrate)||qw(e.audioBitrate,"config.audioBitrate",1,128),tO(e.audioChannels)||Zw(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),tO(e.videoGop)||qw(e.videoGop,"config.videoGop"),tO(e.videoCodecProfile)||Zw(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),tO(e.userCount)||qw(e.userCount,"config.userCount",0,17),tO(e.backgroundColor)||qw(e.backgroundColor,"config.backgroundColor",0,16777215),tO(e.userConfigExtraInfo)||$w(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!tO(e.transcodingUsers)&&(eO(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{YV(e.uid),tO(e.x)||qw(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),tO(e.y)||qw(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),tO(e.width)||qw(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),tO(e.height)||qw(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),tO(e.zOrder)||qw(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),tO(e.alpha)||qw(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),tO(e.watermark)||zV(e.watermark,"watermark"),tO(e.backgroundImage)||zV(e.backgroundImage,"backgroundImage"),e.images&&!tO(e.images)&&(eO(e.images,"config.images"),e.images.forEach(((e,t)=>{zV(e,"images[".concat(t,"]"))})))}(t);const n=[];t.images&&n.push(...t.images.map((e=>B8(B8(B8({},JV),e),{},{zOrder:255})))),t.backgroundImage&&(n.push(B8(B8(B8({},JV),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(n.push(B8(B8(B8({},JV),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=n,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>B8({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const i=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Wh.resolve(e.uid):U3(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Wh.all(i)).forEach(((e,n)=>{t.userConfigs&&t.userConfigs[n]&&(t.userConfigs[n].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(Qh(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});UD.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=>{UD.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{UD.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{UD.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,n){if(!this.transcodingConfig&&t===HV.TRANSCODE)throw new dP(Xw.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const i={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};UD.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&n)return void r();if(this.streamingTasks.get(e)&&!n)return r(),new dP(Xw.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case HV.TRANSCODE:i.transcodingConfig=B8({},this.transcodingConfig);case HV.RAW:}this.uapResponse&&this.uapResponse.vid&&(i.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new Wh(((t,i)=>{QO(this.retryTimeout).then((()=>{if(n)return i(n);const t=this.statusError.get(e);return t?(this.statusError.delete(e),i(t)):void 0}))})),a=await Wh.race([this.connection.request("request",{clientRequest:i},!0,{url:e,command:"PublishStream",workerType:t===HV.TRANSCODE?1:2,requestByUser:!n,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,UD.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:i,mode:t,url:e,taskId:o}),r()}catch(i){if(r(),this.isStartingStreamingTask=!1,!i.data||!i.data.retry||n)throw i;return i.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,i)):await this.startLiveStreamingTask(e,t,i)}}stopLiveStreamingTask(e){return new Wh(((t,n)=>{const i=this.streamingTasks.get(e);if(!i||!this.connection)return new dP(Xw.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=i.mode;i.abortTask=()=>{UD.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:i.url}},!1,{url:e,command:"UnPublishStream",workerType:r===HV.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((n=>{UD.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(n.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(n)}))}resetAllTask(){var e;const t=Array.from(Qh(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=$A.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new dP(Xw.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await wO(this,QV.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new x8(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(qV.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(qV.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(qV.REQUEST_NEW_ADDRESS,((t,n)=>{if(!this.connection)return n(new dP(Xw.UNEXPECTED_ERROR,"can not get new live streaming address list"));wO(this,QV.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(n)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(t),i=e.reason;switch(e.code){case $V.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case $V.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const i=new dP(Xw.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return UD.error(i.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,i);if(!this.isStartingStreamingTask)return;this.statusError.set(t,i)}case $V.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new dP(Xw.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,i);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case $V.LIVE_STREAM_RESPONSE_WORKER_LOST:case $V.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(Qh(r=this.streamingTasks).call(r));for(const n of t)n.abortTask?n.abortTask():(UD.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",n.url),this.startLiveStreamingTask(n.url,n.mode,new dP(Xw.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{UD.debug("[".concat(this.spec.clientId,"] republish live stream success"),n.url)})).catch((e=>{UD.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(n.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const j8={name:"LiveStreaming",create:function(e){return new G8(e.joinInfo,e.websocketRetryConfig||EN,e.httpRetryConfig||EN)}};function W8(e){let t=e9();return function(e,t){let n=e.appId;void 0!==n&&(_9(t,10),a9(t,n));let i=e.cid;void 0!==i&&(_9(t,16),_9(t,i));let r=e.cname;void 0!==r&&(_9(t,26),a9(t,r));let o=e.deviceId;void 0!==o&&(_9(t,34),a9(t,o));let s=e.elapse;void 0!==s&&(_9(t,40),E9(t,s));let a=e.fileSize;void 0!==a&&(_9(t,48),E9(t,Q8(a)));let c=e.height;void 0!==c&&(_9(t,56),E9(t,Q8(c)));let d=e.jpg;void 0!==d&&(_9(t,66),_9(t,d.length),function(e,t){let n=r9(e,t.length);e.bytes.set(t,n)}(t,d));let l=e.networkType;void 0!==l&&(_9(t,72),E9(t,Q8(l)));let u=e.osType;void 0!==u&&(_9(t,80),E9(t,Q8(u)));let h=e.requestId;void 0!==h&&(_9(t,90),a9(t,h));let p=e.sdkVersion;void 0!==p&&(_9(t,98),a9(t,p));let _=e.sequence;void 0!==_&&(_9(t,104),E9(t,Q8(_)));let E=e.sid;void 0!==E&&(_9(t,114),a9(t,E));let m=e.timestamp;void 0!==m&&(_9(t,120),E9(t,m));let f=e.uid;void 0!==f&&(_9(t,128),_9(t,f));let g=e.vid;void 0!==g&&(_9(t,136),_9(t,g));let S=e.width;void 0!==S&&(_9(t,144),E9(t,Q8(S)));let T=e.service;void 0!==T&&(_9(t,152),_9(t,T));let R=e.callbackData;void 0!==R&&(_9(t,162),a9(t,R));let v=e.jpgEncryption;void 0!==v&&(_9(t,168),_9(t,v));let y=e.requestType;void 0!==y&&(_9(t,176),_9(t,y));let C=e.scorePorn;void 0!==C&&(_9(t,185),h9(t,C));let b=e.scoreSexy;void 0!==b&&(_9(t,193),h9(t,b));let I=e.scoreNeutral;void 0!==I&&(_9(t,201),h9(t,I));let A=e.scene;void 0!==A&&(_9(t,208),_9(t,A));let w=e.ossFilePrefix;void 0!==w&&(_9(t,218),a9(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){_9(t,226);let n=e9();H8(e,n),_9(t,n.limit),c9(t,n),t9(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function K8(e){return function(e){let t={};e:for(;!i9(e);){let n=p9(e);switch(n>>>3){case 0:break e;case 1:t.code=p9(e);break;case 2:t.msg=s9(e,p9(e));break;case 3:{let n=X8(e);t.data=Y8(e),e.limit=n;break}default:J8(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Y8(e){let t={};e:for(;!i9(e);){let n=p9(e);switch(n>>>3){case 0:break e;case 1:t.requestId=s9(e,p9(e));break;case 2:t.requestType=p9(e)>>>0;break;case 3:t.scorePorn=u9(e);break;case 4:t.scoreSexy=u9(e);break;case 5:t.scoreNeutral=u9(e);break;case 6:t.requestScene=p9(e)>>>0;break;case 7:t.scene=p9(e)>>>0;break;default:J8(e,7&n)}}return t}function H8(e,t){let n=e.service;void 0!==n&&(_9(t,8),_9(t,n));let i=e.vendor;void 0!==i&&(_9(t,16),_9(t,i));let r=e.token;void 0!==r&&(_9(t,26),a9(t,r));let o=e.callbackUrl;void 0!==o&&(_9(t,34),a9(t,o))}function X8(e){let t=p9(e),n=e.limit;return e.limit=e.offset+t,n}function J8(e,t){switch(t){case 0:for(;128&d9(e););break;case 2:n9(e,p9(e));break;case 5:n9(e,4);break;case 1:n9(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let z8=new Float32Array(1);new Uint8Array(z8.buffer);let Z8=new Float64Array(1),q8=new Uint8Array(Z8.buffer);function Q8(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let $8=[];function e9(){const e=$8.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function t9(e){$8.push(e)}function n9(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function i9(e){return e.offset>=e.limit}function r9(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function o9(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function s9(e,t){let n=o9(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+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+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+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+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function a9(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}_9(e,i);let r=r9(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function c9(e,t){let n=r9(e,t.limit),i=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e<o;e++)i[e+n]=r[e]}function d9(e){return e.bytes[o9(e,1)]}function l9(e,t){let n=r9(e,1);e.bytes[n]=t}function u9(e){let t=o9(e,8),n=e.bytes;return q8[0]=n[t++],q8[1]=n[t++],q8[2]=n[t++],q8[3]=n[t++],q8[4]=n[t++],q8[5]=n[t++],q8[6]=n[t++],q8[7]=n[t++],Z8[0]}function h9(e,t){let n=r9(e,8),i=e.bytes;Z8[0]=t,i[n++]=q8[0],i[n++]=q8[1],i[n++]=q8[2],i[n++]=q8[3],i[n++]=q8[4],i[n++]=q8[5],i[n++]=q8[6],i[n++]=q8[7]}function p9(e){let t,n=0,i=0;do{t=d9(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function _9(e,t){for(t>>>=0;t>=128;)l9(e,127&t|128),t>>>=7;l9(e,t)}function E9(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=r9(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?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}function m9(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}const f9=new Map([["moderation",1],["supervise",2]]);class g9 extends uO{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Ix.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=zi(t=e.map((e=>f9.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(),Db(this,"name","AgoraRTCVideoContentInspect"),Db(this,"_connectionState",Cx.CONNECTING),Db(this,"_innerConnectionState",void 0),Db(this,"sequence",0),Db(this,"inspectStartTime",void 0),Db(this,"workerManagerConnection",void 0),Db(this,"workerConnection",void 0),Db(this,"workerMessageLengthLimit",void 0),Db(this,"inspectIntervalMinimum",void 0),Db(this,"qualityRatio",void 0),Db(this,"_connectInfo",void 0),Db(this,"_cancelTokenSource",$A.CancelToken.source()),Db(this,"_retryConfig",void 0),Db(this,"wmSequence",0),Db(this,"inspectInterval",void 0),Db(this,"inspectTimer",null),Db(this,"ossFilePrefix",void 0),Db(this,"extraInfo",void 0),Db(this,"_inspectType",void 0),Db(this,"_inspectMode",void 0),Db(this,"_quality",1),Db(this,"qualityTimer",null),Db(this,"_inspectId",void 0),Db(this,"_needWorkUrlOnly",!1),Db(this,"inspectImage",(()=>{if(this.connectionState!==Cx.CONNECTED)throw new dP(Xw.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===Cx.CONNECTED?this.requestToInspectImage():UD.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()})),this._inspectId=$O(5,"inspect-"),this.workerMessageLengthLimit=iD("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=iD("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=iD("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 $x("worker-manager-"+this._inspectId,EN),this.on(Ix.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,UD.debug("[".concat(this._inspectId,"] Inspect operation :").concat(bx[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new $x("worker-"+this._inspectId,EN),this.handleWorkerEvents()}async init(e,t){this.emit(Ix.STATE_CHANGE,bx.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((i,r)=>{this.on(Ix.CONNECTION_STATE_CHANGE,((e,t)=>{t===Cx.CONNECTED&&i()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,n){const i=iD("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;w3++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:w3,seq:w3,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fN((async()=>{h=Date.now();const e=await r3(_,{data:u,cancelToken:n,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 dP(Xw.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw UD.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new dP(Xw.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw UD.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new dP(Xw.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw UD.error(e.toString()),e}const i=iD("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=iD("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=iD("VIDEO_INSPECT_WORKER_MANAGER_PORT"),s=t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(o||n)})).filter((e=>!!e));return{addressList:s,workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,n)=>(cP.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(cP.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==Xw.OPERATION_ABORTED&&t.code!==Xw.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(Ix.STATE_CHANGE,bx.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(Ix.STATE_CHANGE,bx.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(WV.CONNECTED,(async()=>{this.emit(Ix.STATE_CHANGE,bx.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.3",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(WV.CLOSED,(()=>{this._innerConnectionState<bx.GET_WORKER_MANAGER_RESPONSE&&UD.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(WV.FAILED,(()=>{this._innerConnectionState<bx.GET_WORKER_MANAGER_RESPONSE&&UD.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(WV.RECONNECTING,(()=>{this._innerConnectionState<bx.GET_WORKER_MANAGER_RESPONSE&&UD.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(WV.ON_MESSAGE,(async e=>{this.emit(Ix.STATE_CHANGE,bx.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw UD.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new dP(Xw.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw UD.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new dP(Xw.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=iD("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,i=t.replace(/:\d+\/?$/,":".concat(e));this.emit(Ix.STATE_CHANGE,bx.CONNECT_WORKER,i),this._needWorkUrlOnly?this.emit(Ix.REQUEST_NEW_WORKER_URL,i):await this.connectWorker(i)}})),this.workerManagerConnection.on(WV.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(WV.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(WV.CONNECTED,(async()=>{this.emit(Ix.STATE_CHANGE,bx.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=Cx.CONNECTED})),this.workerConnection.on(WV.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=K8(new Uint8Array(e.data));if(iD("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&UD.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),200===n.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(Ix.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){var t;const e={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},i=zi(t=Object.keys(e)).call(t,((t,n)=>e[t]>e[n]?t:n),"porn"),r=Object.keys(e).find((e=>e===i));this.emit(Ix.INSPECT_RESULT,r)}else this.emit(Ix.INSPECT_RESULT,void 0,new dP(Xw.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(Ix.INSPECT_RESULT,void 0,new dP(Xw.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else UD.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(Ix.INSPECT_RESULT,void 0,new dP(Xw.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(WV.CLOSED,(()=>{this.connectionState=Cx.CLOSED})),this.workerConnection.on(WV.FAILED,(()=>{this.connectionState=Cx.CLOSED})),this.workerConnection.on(WV.RECONNECTING,(()=>{this.connectionState=this.connectionState===Cx.CONNECTED?Cx.RECONNECTING:Cx.CONNECTING})),this.workerConnection.on(WV.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(WV.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(Ix.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=NO(this,Ix.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(Ix.INSPECT_RESULT,void 0,new dP(Xw.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(Ix.INSPECT_RESULT,void 0,new dP(Xw.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await QL(d,n,i),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+$O(12,""),h={appId:n,cid:r,cname:i,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.3",sequence:this.sequence,sid:s,timestamp:v6(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 _=W8(h);if(_.byteLength<this.workerMessageLengthLimit){if(iD("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?m9(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m9(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,UD.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:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=$A.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=Cx.CLOSED,this.emit(Ix.STATE_CHANGE,bx.CLOSED)}}const S9={name:"ContentInspect",create:function(e){let{config:t}=e;return function(e){if(!e)throw new dP(Xw.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new dP(Xw.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!Di(t=["supervise","moderation"]).call(t,e))throw new dP(Xw.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new dP(Xw.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new g9(t)}};var T9=n(ne.Object.getOwnPropertySymbols),R9=On,v9=Jn.indexOf,y9=Bi,C9=C([].indexOf),b9=!!C9&&1/C9([1],1,-0)<0;R9({target:"Array",proto:!0,forced:b9||!y9("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return b9?C9(this,e,t)||0:v9(this,e,t)}});var I9=qn("Array").indexOf,A9=l,w9=I9,O9=Array.prototype,N9=function(e){var t=e.indexOf;return e===O9||A9(O9,e)&&t===O9.indexOf?w9:t},D9=n(N9);function P9(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n,i,r={},o=cV(e);for(i=0;i<o.length;i++)n=o[i],D9(t).call(t,n)>=0||(r[n]=e[n]);return r}(e,t);if(T9){var o=T9(e);for(i=0;i<o.length;i++)n=o[i],D9(t).call(t,n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}let L9=class{get localCapabilities(){return GO(this._localCapabilities)}get rtpCapabilities(){return GO(this._rtpCapabilities)}get candidates(){return GO(this._candidates)}get iceParameters(){return GO(this._iceParameters)}get dtlsParameters(){return GO(this._dtlsParameters)}constructor(e){Db(this,"sessionDesc",void 0),Db(this,"_localCapabilities",void 0),Db(this,"_rtpCapabilities",void 0),Db(this,"_candidates",void 0),Db(this,"_iceParameters",void 0),Db(this,"_dtlsParameters",void 0),Db(this,"setup",void 0),Db(this,"currentMidIndex",void 0),Db(this,"cname","o/i14u9pJrxRKAsu"),Db(this,"firefoxSsrcMidMap",new Map),e=GO(e);const{remoteIceParameters:t,remoteDtlsParameters:n,candidates:i,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=s===jV.RECEIVE_ONLY?_D("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"):_D("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=i,this._iceParameters=t,this._dtlsParameters=n,this._localCapabilities=o;const u=s===jV.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=s===jV.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===jV.RECEIVE_ONLY?r.send.videoCodecs:V2(fx.VIDEO,u,h,c),_=s===jV.RECEIVE_ONLY?r.send.audioCodecs:V2(fx.AUDIO,u,h,d);for(const e of l.mediaDescriptions)e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=n.fingerprints,e.attributes.candidates=i,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,U2(e));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return ED(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,n,i,r){n=n.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=C2(t,this.cname,iD("SYNC_GROUP")?n:void 0),a=this.findPreloadMediaDesc(o);if(a){if(Tw()&&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,i);let n;return-1===t?(n=this.createOrRecycleSendMedia(e,o,s,"sendonly",i,r),this.updateBundleMids()):(n=GO(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=o,n.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,r)),Tw()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,n.attributes.mid),{needExchangeSDP:!0,mid:n.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,n){const i=[];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,n),this.updateBundleMids()):(s=GO(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction="recvonly"),i.push({mid:s.attributes.mid,needCreateTransceiver:a})})),i}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:n,address:i,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=n?n:"",priority:c?c+"":"",connectionAddress:null!=i?i:"",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,n,i,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=V2(o,s,this.localCapabilities.send,o===fx.AUDIO?r:i),c=o===fx.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:n,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=>Di(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=>Di(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,n){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const r=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Tw()){if(r){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 r&&i.attributes.mid===n}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const n=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&&n}))}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}restartICE(e){e=GO(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,n,i,r,o){const s=this.rtpCapabilities.send,a=e===fx.VIDEO?s.videoCodecs:s.audioCodecs,c=e===fx.VIDEO?s.videoExtensions:s.audioExtensions;Tw()&&(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:n,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: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,n){const i=GO(e);return I2(i),b2(i,t),A2(i,t),w2(i),O2(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=GO(e);return O2(n,t,this.localCapabilities.recv),U2(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=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 n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Tw()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const k9=["sdp"];var M9;function U9(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function V9(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?U9(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):U9(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let x9=(M9=class e extends Ex{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,n,i){super(t,n),Db(this,"direction",void 0),Db(this,"name",void 0),Db(this,"store",void 0),Db(this,"spec",void 0),Db(this,"peerConnection",void 0),Db(this,"initialOffer",void 0),Db(this,"transport",void 0),Db(this,"statsFilter",void 0),Db(this,"localCandidateCount",0),Db(this,"_isInRestartIce",!1),Db(this,"mutex",void 0),Db(this,"onLocalCandidate",void 0),Db(this,"remoteSDP",void 0),Db(this,"pendingCandidates",[]),Db(this,"localCapabilities",void 0),Db(this,"isReady",!1),Db(this,"restartCnt",0),Db(this,"curTurnServerIndex",0),this.store=n,this.spec=t,this.mutex=new pN("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,n.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=i?i:jV.SEND_ONLY,this.name=this.direction===jV.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=KN(this.peerConnection,iD("STATS_UPDATE_INTERVAL"),void 0,Tw()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{const t=await P2();if(this.localCapabilities=M2(t),e){const{sdp:t}=e,n=P9(e,k9),i=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=g2(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"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(k2(t,e,"videoExtensions",n,i,r),k2(t,e,"videoCodecs",n,i,r),k2(t,e,"audioExtensions",n,i,r),k2(t,e,"audioCodecs",n,i,r),iD("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){UD.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&iD("FILTER_SEND_H264_BASELINE")&&(n.videoCodecs=n.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}({},{},t);this.remoteSDP=new L9({remoteIceParameters:n.iceParameters,remoteDtlsParameters:n.dtlsParameters,candidates:[],remoteRTPCapabilities:i,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=S2(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await L2({},{},r.sdp);this.localCapabilities=M2(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),V9(V9({},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=S2(e.sdp);return this.initialOffer=e,V9(V9({},t),{},{sdp:e.sdp})}}catch(e){throw new Jw(Xw.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:n,dtlsParameters:i}=e,r=await L2({},{},t);this.remoteSDP=new L9({remoteIceParameters:n,remoteDtlsParameters:i,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(Xw.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(Xw.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return EA((function*(){const r=yield mA(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=i.remoteSDP.receive(e,t,n);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const n=i.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!n)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(s[t].mid));o.push(n),e._updateRtpTransceiver(n)}})),Tw()&&!0===iD("SIMULCAST")&&(yield mA(i.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield mA(i.peerConnection.createOffer()),d=i.mungSendOfferSDP(c.sdp,e,a),l=_D(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 T2(t,iD("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}));yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=i.remoteSDP.toString();throw yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(i.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield mA(i.stopSending(a,!0)),e}yield mA(i.applySimulcastEncodings(o,e)),yield mA(i.applySendEncodings(o,e));const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield mA(i.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}))}catch(e){throw e instanceof Jw?e:new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const n=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 i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),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(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){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,n,i);if(o){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(i.sdp,r,e);null==n||n(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else UD.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(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,n,i){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,n,i);if(o){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(i.sdp,r,e);null==n||n(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else UD.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new Jw(Xw.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(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===zN.Auto&&(this.store.p2pTransport=zN.SdRtn,uP().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,uP().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}=S2(e.sdp);return this.store.descriptionStart(),this.direction===jV.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===jV.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}=S2(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(Xw.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 n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?Tw()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.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:n,remote:i}=t.getSelectedCandidatePair();return{local:V9(V9({},wN),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:V9(V9({},wN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Di(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 UD.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,n){let i=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&&(SO(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,n,i)),iD("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,n,i)),Di(o=[zN.Relay,zN.SdRtn]).call(o,n)&&(r.iceTransportPolicy="relay"),iD("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return iD("ENABLE_ENCODED_TRANSFORM")&&uP().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),UD.debug("P2PConnection p2pTransport is ".concat(n)),r}static turnServerConfigToIceServers(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=[],r=e.filter((e=>e.tcpport));UD.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(n));const o=r.length>n?r[n]:r[0];switch(t){case zN.SdRtn:const t=e.filter((e=>{var t;return Di(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL})),r=t.length>n?t[n]:t[0];r&&(i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(Z1(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(Z1(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case zN.Relay:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Z1(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Z1(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return i}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 n;t&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:n}=t.getSelectedCandidatePair()||{};if(e&&n){const t=e.address+":"+e.port,i=n.address+":"+n.port;UD.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(s2(t)),", remote ").concat(JSON.stringify(s2(i))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return UD.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return UD.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!uP().supportSetRtpSenderParameters)return UD.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const i={},r={};switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(e._encoderConfig){var o;const{bitrateMax:t,frameRate:n,scaleResolutionDownBy:i}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Di(o=e._hints).call(o,xP.LOW_STREAM)&&(n&&(r.maxFramerate=$1(n)),i&&i>=1&&(r.scaleResolutionDownBy=i))}if(iD("DSCP_TYPE")&&Bw()){var s;const e=iD("DSCP_TYPE");Di(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(n=a.encodings)||void 0===n?void 0:n[0];Tw()&&!c&&(i.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,i),UD.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!uP().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof MM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){UD.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=_D(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(b2(o,e),N2(o,e,this.store.codec))})),ED(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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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 n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof MM&&!Di(n=d._hints).call(n,xP.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.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 n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!Tw()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof MM&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._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,n,i,r,o;return!!(e instanceof MM&&iD("SIMULCAST")&&"vp8"===this.store.codec&&!Di(t=e._hints).call(t,xP.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.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,n,i){if(iD("SDP_LOGGING"))return UD.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}: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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var n,i;if(t=null!==(n=t)&&void 0!==n?n:null===(i=this.currentRemoteDescription)||void 0===i?void 0:i.sdp){var r;const n=null===(r=_D(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==n?void 0:n[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Di(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,n){const i=_D(e),r=i.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&n===fx.AUDIO&&"audio"===r.media.mediaType&&U2(r),ED(i)}},DV(M9.prototype,"establish",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"establish"),M9.prototype),DV(M9.prototype,"connect",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"connect"),M9.prototype),DV(M9.prototype,"receive",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"receive"),M9.prototype),DV(M9.prototype,"mockReceive",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"mockReceive"),M9.prototype),DV(M9.prototype,"stopReceiving",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"stopReceiving"),M9.prototype),DV(M9.prototype,"restartICE",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"restartICE"),M9.prototype),DV(M9.prototype,"close",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"close"),M9.prototype),DV(M9.prototype,"updateEncoderConfig",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"updateEncoderConfig"),M9.prototype),DV(M9.prototype,"updateSendParameters",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"updateSendParameters"),M9.prototype),DV(M9.prototype,"replaceTrack",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"replaceTrack"),M9.prototype),DV(M9.prototype,"muteLocal",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"muteLocal"),M9.prototype),DV(M9.prototype,"unmuteLocal",[F9],Object.getOwnPropertyDescriptor(M9.prototype,"unmuteLocal"),M9.prototype),M9);function F9(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}let B9=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var G9,j9,W9,K9,Y9,H9,X9,J9,z9,Z9,q9,Q9;function $9(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function e7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?$9(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$9(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let t7=(G9=n7(B9.SEND_ONLY),j9=n7(B9.SEND_ONLY),W9=n7(),K9=n7(B9.RECEIVE_ONLY),Y9=n7(B9.RECEIVE_ONLY),H9=n7(B9.RECEIVE_ONLY),X9=n7(B9.RECEIVE_ONLY),J9=n7(B9.RECEIVE_ONLY),z9=n7(B9.RECEIVE_ONLY),Z9=n7(),q9=n7(B9.RECEIVE_ONLY),Q9=class extends uO{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(yx.StateChange,t,this._state)}constructor(e,t){super(),Db(this,"isPlanB",!1),Db(this,"store",void 0),Db(this,"statsUploader",void 0),Db(this,"sendConnection",void 0),Db(this,"recvConnection",void 0),Db(this,"localTrackMap",new Map),Db(this,"remoteUserMap",new Map),Db(this,"localDataChannels",[]),Db(this,"pendingLocalTracks",[]),Db(this,"pendingRemoteTracks",[]),Db(this,"statsCollector",void 0),Db(this,"dtlsFailedCount",0),Db(this,"sendMutex",void 0),Db(this,"recvMutex",void 0),Db(this,"_state",vx.Disconnected),Db(this,"_restartStates",["disconnected","failed"]),Db(this,"reconnectInterval",void 0),Db(this,"uploadUnplinkStarted",!1),Db(this,"uploadDownlinkStarted",!1),Db(this,"uplinkStateUploadInterval",void 0),Db(this,"downlinkStatsUploadInterval",void 0),Db(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==vx.Connected)return void n(new Jw(Xw.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(Rx.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(Rx.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await OO(this,yx.RequestMuteLocal,d);const l="video"===e.trackMediaType?Mx.MUTE_LOCAL_VIDEO:Mx.MUTE_LOCAL_AUDIO;await OO(this,yx.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==vx.Connected)return void n(new Jw(Xw.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?Mx.UNMUTE_LOCAL_VIDEO:Mx.UNMUTE_LOCAL_AUDIO;await OO(this,yx.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;"boolean"==typeof i&&i||(r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(Rx.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==vx.Connected)return void t();const{id:i,track:s}=n;i&&(await this.sendConnection.updateSendParameters(i,s),await this.sendConnection.updateEncoderConfig(i,s),this.emit(yx.UpdateVideoEncoder,s)),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),Db(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(Rx.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==vx.Connected)return void t();const{id:r,track:o}=n;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),Db(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;UD.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(!this.sendConnection||!n||void 0===n[1].id||this.state!==vx.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),n[0]===Rx.LocalVideoTrack&&uP().supportDualStreamEncoding){const t=this.localTrackMap.get(Rx.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new Wh(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),Db(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),Db(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),Db(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),Db(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Z5(e),this.bindStatsUploaderEvents(),this.sendMutex=new pN("P2PChannel2-send-mutex",e.clientId),this.recvMutex=new pN("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))}))}),iD("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let n;try{if(t){this.recvConnection&&(UD.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),n=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new x9(e,this.store,jV.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const i=await this.recvConnection.establish(t);return{iceParameters:i.iceParameters,dtlsParameters:i.dtlsParameters,sdp:i.sdp}}{this.state=vx.New,this.sendConnection&&(UD.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),n=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new x9(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{n&&n()}}async p2pConnect(e){if(!this.sendConnection)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=vx.Connected}async addRemoteCandidate(e,t){if(t===jV.RECEIVE_ONLY){if(!this.sendConnection)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new Jw(Xw.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,n){var i=this;return EA((function*(){const r=yield mA(i.sendMutex.lock("From P2PChannel.publish"));try{if(!i.sendConnection||i.state!==vx.Connected){i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return void(i.pendingLocalTracks=i.pendingLocalTracks.concat(t))}i.store.pubId=i.store.pubId+1,J3.markPublishStart(i.store.clientId,i.store.pubId);const o=i.filterTobePublishedTracks(e,t,n);if(0===o.length)return void(yield mA(i.tryToUnmuteAudio(e)));o.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===Rx.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(o);const s=yield mA(i.sendConnection.send(o.map((e=>{let{track:t}=e;return t})),i.store.codec,i.store.audioCodec)),a=(yield mA(s.next())).value,c=i.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===Xw.WS_ABORT&&o.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(o),e}yield mA(s.next()),o.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.statsUploader.startUploadOutboundStats(),i.assignLocalTracks(o,a),o.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===Rx.LocalAudioTrack?"audio":"video",void 0,r)})),i.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==vx.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Di(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}const i=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:n}]=e;return{type:t,track:n}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===vx.Connected){if(n){n[1].track.close()}return i}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((n=>{let[i,{track:r,ssrcs:o}]=n;const s={stream_type:v5(r,i),ssrcs:o};r._muted||!r._enabled?e.push(s):t.push(s)})),e.length>0&&e.forEach((e=>{OO(this,yx.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{OO(this,yx.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return EA((function*(){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(UD.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await wO(this,yx.RequestRePublish,this.pendingLocalTracks),this.emit(yx.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,n,i){var r;if(!this.recvConnection)throw new Jw(Xw.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:n}],String(e.uid),i);t===fx.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new eU(o,e.uid,e._uintid,this.store),UD.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=n,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new $M(o,e.uid,e._uintid,this.store),UD.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((n=>{let{user:i,kind:r}=n;return i.uid===e.uid&&t===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(yx.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,n,i){if(!this.recvConnection)throw new Jw(Xw.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:n}],String(e.uid),i)}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let{user:i,kind:r}=n;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||n||i.forEach((t=>{let{kind:n}=t;var i;if(n===fx.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===fx.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:i}]=e;var r,o;i===fx.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===fx.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),n||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(i===fx.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!n)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),r.forEach((e=>{let[,{kind:t}]=e;OO(this,yx.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[fx.VIDEO,fx.AUDIO].forEach((e=>{t.has(e)?OO(this,yx.RequestP2PUnmuteRemote,e):OO(this,yx.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(Xw.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new Jw(Xw.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void UD.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void UD.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===fx.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.recvConnection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void UD.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||UD.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(Rx.LocalAudioTrack);if((null==t?void 0:t.track)instanceof Kk){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==Rx.LocalAudioTrack})).filter((t=>{let[n]=t;return!(e&&n===Rx.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[n]=t;return!(e&&n===Rx.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(Rx.LocalAudioTrack),o=i?this.localTrackMap.get(Rx.LocalVideoLowTrack):this.localTrackMap.get(Rx.LocalVideoTrack);cP.publish(this.store.sessionId,{eventElapse:J3.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(xP.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof Gk)),a=i?null===(o=this.localTrackMap.get(Rx.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof MM));cP.publish(this.store.sessionId,{eventElapse:J3.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(xP.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===fx.VIDEO?n._videoSSRC:n._audioSSRC;r&&cP.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===fx.VIDEO,audio:i===fx.AUDIO,peerid:n.uid,subscribeRequestid:i===fx.VIDEO?n._videoSSRC:n._audioSSRC,p2pid:this.store.p2pId,eventElapse:J3.measureFromSubscribeStart(this.store.clientId,r)})}reset(){UD.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new pN("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new pN("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(Rx.LocalAudioTrack);if((null==e?void 0:e.track)instanceof Kk){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=vx.Disconnected}getStats(e){var t,n;return e?null===(n=this.recvConnection)||void 0===n?void 0:n.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(Rx.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(Rx.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 MM||t&&t.track instanceof Gk?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 n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._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(Rx.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Jp(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(UD.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=vx.Reconnecting,iD("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.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[n,{track:i}]=e;switch(n){case Rx.LocalVideoTrack:Di(t=i._hints).call(t,xP.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case Rx.LocalAudioTrack:i instanceof Kk?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case Rx.LocalVideoLowTrack:}})),this.emit(yx.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,n]=e;Array.from(CD(n).call(n)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(yx.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),UD.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const{user:i,kind:r}=n;if((e instanceof e5?e.uid:e)===i.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 n,i;if(e===jV.SEND_ONLY){if(!this.sendConnection)throw new Jw(Xw.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");n=await this.sendMutex.lock("From P2PChannel.restartICE"),i=this.sendConnection}else{if(!this.recvConnection)throw new Jw(Xw.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");n=await this.recvMutex.lock("From P2PChannel.restartICE"),i=this.recvConnection}try{if(t){const e=await i.restartICE(t);return i.isInRestartIce=!1,e}{const e=await i.restartICE();if(e){const t=await wO(this,yx.RequestP2PRestartICE,{direction:jV.RECEIVE_ONLY,iceParameter:e});await i.restartICE(t),i.isInRestartIce=!1}}}finally{n()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(Rx.LocalVideoTrack),n=this.localTrackMap.get(Rx.LocalAudioTrack),i=e.videoSend.find((e=>{var n;return e.ssrc===(null==t||null===(n=t.ssrcs)||void 0===n?void 0:n[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==n||null===(t=n.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!i||!r)return 1;const o=NO(this,yx.NeedSignalRTT),s=i?i.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(xP.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return KU[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((n=>{let[i]=n;const r=i._audioSSRC,o=i._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=NO(this,yx.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,n)=>{this.handleMuteLocalTrack(e,t,n)}))}filterTobePublishedTracks(e,t,n){const i=[],r=uP(),o=this.getAllTracks();e=FO(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof MM&&(this.localTrackMap.has(Rx.LocalVideoTrack)||s?new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:o,type:Rx.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,n);i.push({track:e,type:Rx.LocalVideoLowTrack})}if(o instanceof Gk){const e=this.localTrackMap.get(Rx.LocalAudioTrack);if(e){if(!(e.track instanceof Kk))throw new Jw(Xw.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(Xw.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=i.find((e=>{let{type:t}=e;return t===Rx.LocalAudioTrack}));if(!(e.track instanceof Kk))throw new Jw(Xw.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(Xw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof Kk||o._bypassWebAudio)i.push({track:o,type:Rx.LocalAudioTrack});else{const e=new Kk;e.addAudioTrack(o),i.push({track:e,type:Rx.LocalAudioTrack})}a=!0}}}return i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=FO(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof Gk){const e=this.localTrackMap.get(Rx.LocalAudioTrack);if(!e)continue;e.track instanceof Kk?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([Rx.LocalAudioTrack,e]),e.track.close())):t.push([Rx.LocalAudioTrack,e])}if(n instanceof MM){const e=this.localTrackMap.get(Rx.LocalVideoTrack);if(!e)continue;t.push([Rx.LocalVideoTrack,e]);const n=this.localTrackMap.get(Rx.LocalVideoLowTrack);n&&t.push([Rx.LocalVideoLowTrack,n])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:n}=e;switch(n){case Rx.LocalVideoTrack:t.addListener(VP.GET_STATS,this.handleGetLocalVideoStats),t.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(VP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(VP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Rx.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case Rx.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof Kk?e.trackList.forEach((e=>{e.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(VP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(VP.GET_STATS,this.handleGetLocalAudioStats),e.addListener(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:n}]=e;return{track:n,type:t}}))),e.forEach((e=>{let{track:t,type:n}=e;switch(n){case Rx.LocalVideoTrack:t.off(VP.GET_STATS,this.handleGetLocalVideoStats),t.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(VP.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(VP.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Rx.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case Rx.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof Kk?e.trackList.forEach((e=>{e.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(VP.GET_STATS,this.handleGetLocalAudioStats),e.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(VP.GET_STATS,this.handleGetLocalAudioStats),e.off(VP.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(VP.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(VP.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(VP.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof $M&&t.addListener(VP.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof eU&&t.addListener(VP.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(VP.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,n]=e;n.has(fx.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),n.has(fx.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,{track:o,type:s}=e;switch(s){case Rx.LocalAudioTrack:r=ox.Audio;break;case Rx.LocalVideoTrack:r=Di(i=o._hints).call(i,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:r=ox.Low}return{kind:s===Rx.LocalAudioTrack?fx.AUDIO:fx.VIDEO,stream_type:r,mid:t[n].id,ssrcs:t[n].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let{track:i,type:r}=e;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var n;UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(yx.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),Di(n=this._restartStates).call(n,t)&&!e.isInRestartIce&&("disconnected"===t&&await QO(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),cP.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:EO.TRACER}).onSuccess(),this.emit(yx.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(KP.FIRST_FRAME_DECODED),cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_AUDIO_DECODE,WD.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_AUDIO_RECEIVED,WD.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoReceived=e=>{var t;const n=Array.from(CD(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&cP.firstRemoteFrame(this.store.sessionId,jD.FIRST_VIDEO_RECEIVED,WD.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:J3.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(yx.ConnectionTypeChange,n),UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(o2(t))," -> ").concat(JSON.stringify(o2(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{UD.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(o2(t))," -> ").concat(JSON.stringify(o2(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(yx.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===jV.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,UD.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===jV.SEND_ONLY?this.restartICE(e):wO(this,yx.RequestP2PRestartICE,{direction:jV.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(Rx.LocalAudioTrack);if(e instanceof Gk&&(null==n?void 0:n.track)instanceof Kk)return n.track.isActive||t.push([Rx.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(i&&(t.push(i),i[0]===Rx.LocalVideoTrack)){const e=this.localTrackMap.get(Rx.LocalVideoLowTrack);e&&t.push([Rx.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(Rx.LocalAudioTrack);if(e instanceof Gk&&(null==n?void 0:n.track)instanceof Kk)return n.track.isActive&&t.push([Rx.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:n}]=t;return e===n}));if(i)if(i[0]===Rx.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(Rx.LocalVideoLowTrack);e&&t.push([Rx.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,[i,{track:r,ssrcs:o,id:s}]=e;switch(i){case Rx.LocalAudioTrack:n=ox.Audio;break;case Rx.LocalVideoTrack:n=Di(t=r._hints).call(t,xP.SCREEN_TRACK)?ox.Screen:ox.High;break;case Rx.LocalVideoLowTrack:n=ox.Low}return{stream_type:n,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let[i,r]=t;n.push([e,{kind:i,id:r}])}));return n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[n,{kind:i,id:r}]=e;switch(i){case fx.VIDEO:return void(n._videoSSRC&&t.push({stream_type:fx.VIDEO,ssrcId:n._videoSSRC}));case fx.AUDIO:return void(n._audioSSRC&&t.push({stream_type:fx.AUDIO,ssrcId:n._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:n}]=e;const i=this.remoteUserMap.get(t);i&&(i.delete(n),0===Array.from(i.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(Rx.LocalVideoTrack),n=this.localTrackMap.get(Rx.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(n.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 Gk){const n=this.filterTobeUnmutedTracks(e[t]);if(0===n.length)continue;const i=this.createUnmuteMessage(n);return void await OO(this,yx.RequestUnmuteLocal,i)}}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(yx.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(yx.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 QO(mN(this.dtlsFailedCount,EN)),this.emit(yx.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(Rx.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof MM))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof MM)).length>1)throw new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof Gk)).length>1&&(e.some((e=>e instanceof Gk&&e._bypassWebAudio))||!uP().webAudioMediaStreamDest))throw new Jw(Xw.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 MM&&this.pendingLocalTracks.some((e=>e instanceof MM)))throw new Jw(Xw.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof Gk&&this.pendingLocalTracks.some((e=>e instanceof Gk))&&(!uP().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof Gk&&e._bypassWebAudio))))throw new Jw(Xw.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const n=!iD("DISABLE_DUAL_STREAM_USE_ENCODING")&&uP().supportDualStreamEncoding,i=e7(e7({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=n?e._mediaStreamTrack.clone():k5(e,i);const o=$O(8,"track-low-"),s=new MM(r,e7(e7({},n&&{scaleResolutionDownBy:r2(i,e)}),{},{frameRate:i.framerate,bitrateMax:i.bitrate,bitrateMin:i.bitrate}),void 0,void 0,o);return s.on(jP.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,FP.LOW_STREAM)})),s._hints.push(xP.LOW_STREAM),e.addListener(VP.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(CD(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||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));cP.firstRemoteVideoDecode(this.store.sessionId,jD.FIRST_VIDEO_DECODE,WD.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:J3.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:i?1:0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.recvConnection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==n}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new Jw(Xw.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new Jw(Xw.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new Jw(Xw.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new Jw(Xw.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new Jw(Xw.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new Jw(Xw.NOT_SUPPORTED)}async preConnect(e){throw new Jw(Xw.NOT_SUPPORTED)}getEstablishParams(){throw new Jw(Xw.NOT_SUPPORTED)}async reSubscribe(e){throw new Jw(Xw.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new Jw(Xw.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:n}]=e;t===Rx.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,FP.LOW_STREAM):n._updateRtpTransceiver(void 0)}))}},DV(Q9.prototype,"p2pConnect",[G9],Object.getOwnPropertyDescriptor(Q9.prototype,"p2pConnect"),Q9.prototype),DV(Q9.prototype,"unpublish",[j9],Object.getOwnPropertyDescriptor(Q9.prototype,"unpublish"),Q9.prototype),DV(Q9.prototype,"unpublishLowStream",[W9],Object.getOwnPropertyDescriptor(Q9.prototype,"unpublishLowStream"),Q9.prototype),DV(Q9.prototype,"subscribe",[K9],Object.getOwnPropertyDescriptor(Q9.prototype,"subscribe"),Q9.prototype),DV(Q9.prototype,"mockSubscribe",[Y9],Object.getOwnPropertyDescriptor(Q9.prototype,"mockSubscribe"),Q9.prototype),DV(Q9.prototype,"unsubscribe",[H9],Object.getOwnPropertyDescriptor(Q9.prototype,"unsubscribe"),Q9.prototype),DV(Q9.prototype,"muteRemote",[X9],Object.getOwnPropertyDescriptor(Q9.prototype,"muteRemote"),Q9.prototype),DV(Q9.prototype,"unmuteRemote",[J9],Object.getOwnPropertyDescriptor(Q9.prototype,"unmuteRemote"),Q9.prototype),DV(Q9.prototype,"hasRemoteMediaWithLock",[z9],Object.getOwnPropertyDescriptor(Q9.prototype,"hasRemoteMediaWithLock"),Q9.prototype),DV(Q9.prototype,"disconnectForReconnect",[Z9],Object.getOwnPropertyDescriptor(Q9.prototype,"disconnectForReconnect"),Q9.prototype),DV(Q9.prototype,"remoteMediaSsrcChanged",[q9],Object.getOwnPropertyDescriptor(Q9.prototype,"remoteMediaSsrcChanged"),Q9.prototype),Q9);function n7(e){return function(t,n,i){const r=t[n];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return i.value=async function(){for(var t=arguments.length,i=new Array(t),o=0;o<t;o++)i[o]=arguments[o];switch(e){case B9.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}case B9.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n)),t=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e(),t()}}}},i}}class i7 extends uO{constructor(e,t){super(),Db(this,"signal",void 0),Db(this,"token",void 0),Db(this,"tokenTimeout",void 0),Db(this,"tokenInterval",void 0),Db(this,"_sequence",0),Db(this,"userMap",new Map),Db(this,"encoder",new TextEncoder),this.signal=e,this.token=t;const n=()=>{this.signal.connectionState===VV.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(n,1e3):this.tokenInterval=window.setTimeout(n,3*iD("P2P_TOKEN_INTERVAL"))};n()}async send(e,t,n,i,r){var o,s,a;if(0===this.userMap.size)return;const c=Array.from(Qh(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),i=null!==(s=i)&&void 0!==s?s:$O(6,""),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:i,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(c)};iD("SHOW_P2P_LOG")&&UD.debug("send message",d,"noNeedResponse : ".concat(n));this.splitMessage(JSON.stringify(d)).forEach((e=>{this.signal.request(FV.DATA_STREAM,{payload:HO(this.encoder.encode(e))})}));const l=new Wh(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),c),this.off(kx.ABORT,a),UD.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(i)),0===this.userMap.size?r(new Jw(Xw.INVALID_REMOTE_USER)):r(new Jw(Xw.TIMEOUT))}),iD("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off(kx.ABORT,a),n&&t()},a=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),c),r(new Jw(Xw.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(i)))};this.once(kx.ABORT,a),this.once("res-@".concat(i,"_ack"),s);const c=(n,c)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off(kx.ABORT,a),"success"===n?t(c):r(new Jw(Xw.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(i)))};let l=!1;n||(this.once("res-@".concat(i),c),QO(iD("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||UD.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(i,", ").concat(d))})))}));try{return await l}catch(o){if(o.code===Xw.TIMEOUT)return await this.send(e,t,n,i,r);throw o}}onMessage(e){var t;const{_uid:n}=e;let i,r=this.userMap.get(n);if(r)i=r.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==Lx.CHECK)return;const{token:t}=e;i=new Map,r={uid:n,isStart:!0,token:t,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(n,r),this.signal.emit(GV.ON_USER_ONLINE,{uid:n}),this.handleUserOnline()}if("id"in e&&"total"in e){var o;const{id:t,total:r}=e,s=null!==(o=i.get(t))&&void 0!==o?o:[];if(s.push(e),i.has(t)||i.set(t,s),s.length!==r)return;{const r=Jp(s).call(s,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(t),(e=JSON.parse(r))._uid=n}}const{_type:s,token:a}=e;if(Di(t=[Lx.ACK,Lx.CHECK]).call(t,s))return s===Lx.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):UD.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:$O(6,""),token:this.token,_type:Lx.CHECK};iD("SHOW_P2P_LOG")&&UD.debug("send message",e),this.signal.request(FV.DATA_STREAM,{payload:HO(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:Lx.ACK,token:this.token};iD("SHOW_P2P_LOG")&&UD.debug("send message",t),this.signal.request(FV.DATA_STREAM,{payload:HO(this.encoder.encode(JSON.stringify(t)))})}response(e,t,n){this.send(Lx.RESPONSE,JSON.stringify({success:!n,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:n}=e;for(;t.has(n);){const i=t.get(n);t.delete(n),this.receiveMessage(i),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:n,_seq:i}=e,r=this.userMap.get(n),{receivedMessagesMap:o,isStart:s,nextExpectedSequenceNumber:a}=r;if(i<a)return this.ack(e._id),void UD.debug("[external-signal] receive old message, seq: ".concat(i,", ").concat(e._message));o.set(i,e),s&&i===a&&(this.receiveMessage(e),o.delete(a),r.nextExpectedSequenceNumber++,t())}receiveMessage(e){const{_id:t,_type:n,_message:i,_uid:r}=e;if(iD("SHOW_P2P_LOG")&&UD.debug("receive message",e),t){let o;switch(e._type!==Lx.ACK&&(i&&(o=JSON.parse(i)),this.ack(e._id)),e._type){case Lx.CANDIDATE:case Lx.CONTROL:this.signal.emit(n,o,r);break;case Lx.PUBLISH:case Lx.UNPUBLISH:case Lx.RESTART_ICE:case Lx.CALL:o.uid=r,wO(this.signal,n,o).then((t=>{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case Lx.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case Lx.RESPONSE:{const{success:e,message:n}=o;this.emit("res-@".concat(t),e?"success":"failed",n);break}}}}splitMessage(e){if(e.length<i7.MAX_MESSAGE_SIZE)return[e];const t=[],{remoteToken:n}=JSON.parse(e),i=$O(6,"");let r=0,o=800;const s=Math.ceil(e.length/o);for(;e.length>0;){r++;const a={id:i,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(n)};JSON.stringify(a).length>i7.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?(UD.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((()=>{UD.debug("token timeout, ".concat(t)),this.reset(e.uid)}),iD("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await wO(this.signal,Lx.CALL,void 0),t=await this.send(Lx.CALL,e);this.signal.emit(xV.P2P_CONNECTION,t,!0)}async reset(e,t){const n=this.userMap.get(e);n&&(this.emit(kx.ABORT),this.signal.emit(GV.ON_USER_OFFLINE,{uid:n.uid,reason:Ux.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(UD.debug("change local token from ".concat(t," to ").concat(t)),this.token=$O(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(kx.ABORT)}}Db(i7,"MAX_SIZE",1),Db(i7,"MAX_MESSAGE_SIZE",1024);class r7 extends uO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===VV.CONNECTED?this.emit(xV.WS_CONNECTED):e===VV.RECONNECTING?this.emit(xV.WS_RECONNECTING,this._websocketReconnectReason):e===VV.CLOSED&&this.emit(xV.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(),Db(this,"__name__","P2PSignal"),Db(this,"_disconnectedReason",void 0),Db(this,"_websocketReconnectReason",void 0),Db(this,"_connectionState",VV.CLOSED),Db(this,"reconnectToken",void 0),Db(this,"p2pToken",void 0),Db(this,"websocket",void 0),Db(this,"openConnectionTime",void 0),Db(this,"clientId",void 0),Db(this,"lastMsgTime",Date.now()),Db(this,"uploadCache",[]),Db(this,"uploadCacheInterval",void 0),Db(this,"rttRolling",new SN(5)),Db(this,"pingpongTimer",void 0),Db(this,"pingpongTimeoutCount",0),Db(this,"joinResponse",void 0),Db(this,"multiIpOption",void 0),Db(this,"initError",void 0),Db(this,"spec",void 0),Db(this,"store",void 0),Db(this,"_external_signal",void 0),Db(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(xV.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 GV.ON_DATA_STREAM:return void this.handleDataStream(t._message);case GV.MUTE_AUDIO:case GV.MUTE_VIDEO:case GV.ON_P2P_LOST:case GV.ON_USER_ONLINE:return;case GV.ON_USER_OFFLINE:const{uid:e}=t._message;return UD.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===GV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===GV.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(gO.UID_BANNED);break;case 15:this.close(gO.IP_BANNED);break;case 16:this.close(gO.CHANNEL_BANNED)}if(t._type===GV.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case UV.ERR_LICENSE_MISSING:this.close(gO.LICENSE_MISSING);break;case UV.ERR_LICENSE_EXPIRED:this.close(gO.LICENSE_EXPIRED);break;case UV.ERR_LICENSE_MINUTES_EXCEEDED:this.close(gO.LICENSE_MINUTES_EXCEEDED);break;case UV.ERR_LICENSE_PERIOD_INVALID:this.close(gO.LICENSE_PERIOD_INVALID);break;case UV.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(gO.LICENSE_MULTIPLE_SDK_SERVICE);break;case UV.ERR_LICENSE_ILLEGAL:this.close(gO.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Qx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,iD("JOIN_GATEWAY_USE_DUAL_DOMAIN"),iD("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===VV.CONNECTED&&this.reconnect("retry",bO.OFFLINE)})),this.p2pToken=$O(6,""),this._external_signal=new i7(this,this.p2pToken)}async request(e,t,n,i){const r=$O(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((e,t)=>{if(this.connectionState===VV.CONNECTED)return e();const n=()=>{this.off(xV.WS_CLOSED,i),e()},i=()=>{this.off(xV.WS_CONNECTED,n),t(new Jw(Xw.WS_ABORT))};this.once(xV.WS_CONNECTED,n),this.once(xV.WS_CLOSED,i)}));if(this.connectionState!==VV.CONNECTING&&this.connectionState!==VV.RECONNECTING||e===FV.JOIN||e===FV.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new Wh(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.emit(xV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new Jw(Xw.WS_ABORT,"type: ".concat(e))),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(xV.WS_CLOSED,c),this.once(xV.WS_RECONNECTING,c),QO(iD("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(UD.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(xV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===VV.CLOSED||e===FV.LEAVE)throw new Jw(Xw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===FV.JOIN||e===FV.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=Bx(l),h=new Jw(Xw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(UD.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===FV.JOIN||e===FV.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,UD.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",bO.MULTI_IP)):this.reconnect(u.action,bO.SERVER_ERROR),e===FV.JOIN||e===FV.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void UD.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(BV.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=iD("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==VV.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)}),iD("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}async sendExtensionMessage(e,t,n){return await this._external_signal.send(e,t,n)}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,n)=>{this.once(xV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(xV.WS_CLOSED,(()=>n(this.initError||new Jw(Xw.WS_ABORT)))),this.connectionState=VV.CONNECTING,this.websocket.init(e).catch(n)}))}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||gO.LEAVE,this.connectionState=VV.CLOSED,UD.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=$O(6,""),this._external_signal.clear(),this._external_signal=new i7(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(xV.ABORT_P2P_EXECUTION);const e=await wO(this,xV.REQUEST_JOIN_INFO),t=await this.request(FV.JOIN,e);if(!t)return this.emit(xV.REPORT_JOIN_GATEWAY,Xw.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(xV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=VV.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 n=YO(e.payload),i=(new TextDecoder).decode(n),r=JSON.parse(i);"total"in r&&"id"in r||Di(t=Object.values(Lx)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(GV.ON_DATA_STREAM,e)}catch(t){this.emit(GV.ON_DATA_STREAM,e)}}handleNotification(e){UD.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Bx(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===UV.ERR_REPEAT_JOIN_CHANNEL&&iD("IGNORE_UID_CHECK")?void this.close(gO.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(gO.UID_BANNED),void this.close()):void this.reconnect(t.action,bO.SERVER_ERROR);UD.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=iD("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(UD.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>iD("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",bO.TIMEOUT):this.request(FV.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),iD("REPORT_STATS")&&this.send(FV.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(WV.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(xV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(WV.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(WV.CLOSED,(()=>{this.connectionState=VV.CLOSED})),this.websocket.on(WV.FAILED,(()=>{this._disconnectedReason=gO.NETWORK_ERROR,this.connectionState=VV.CLOSED})),this.websocket.on(WV.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===VV.CONNECTED?this.connectionState=VV.RECONNECTING:this.connectionState=VV.CONNECTING})),this.websocket.on(WV.WILL_RECONNECT,((e,t,n)=>{"retry"!==e?(UD.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):UD.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),n(e)})),this.websocket.on(WV.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(xV.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof Jw&&e.code===Xw.UNEXPECTED_RESPONSE&&e.data.code===UV.ERR_NO_AUTHORIZED)return UD.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",bO.SERVER_ERROR);UD.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",bO.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(WV.REQUEST_NEW_URLS,((e,t)=>{wO(this,xV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(WV.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(GV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const o7={name:"P2PChannel",create:function(e){let{store:t,statsCollector:n}=e;return new t7(t,n)},createSubmodule:function(e){let{store:t,spec:n}=e;return new r7(n,t)}};function s7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function a7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s7(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class c7{constructor(e){Db(this,"sessionDesc",void 0),Db(this,"localCapabilities",void 0),Db(this,"rtpCapabilities",void 0),Db(this,"candidates",void 0),Db(this,"_originCandidates",void 0),Db(this,"iceParameters",void 0),Db(this,"dtlsParameters",void 0),Db(this,"setup",void 0),Db(this,"currentMidIndex",void 0),Db(this,"cname",void 0),e=GO(e);const{iceParameters:t,dtlsParameters:n,candidates:i,rtpCapabilities:r,setup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=_D("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=i,this._originCandidates=GO(i),this.iceParameters=t,this.dtlsParameters=n,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=n.fingerprints,s.attributes.candidates=i,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,n;return null===(t=e.rtpMap)||void 0===t?void 0:Di(n=t.encodingName.toLowerCase()).call(n,a)})),t=r.videoCodecs.filter((t=>!Di(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 ED(this.sessionDesc)}send(e,t,n){const{ssrcs:i,ssrcGroups:r}=C2(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===fx.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),s=i[0].attributes.label,a=i[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(i),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(r),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:n}=e;return this.send(t,n,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const n=[],i=[],r=[];t.attributes.ssrcs.forEach((t=>{Di(e).call(e,t.attributes.label||"")?r.push(t):n.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Di(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||i.push(e)})),t.attributes.ssrcs=n,t.attributes.ssrcGroups=i}))}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,n){e.forEach(((e,t)=>{const n=e._mediaStreamTrack,i=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===n.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],e);this.sessionDesc.mediaDescriptions[i]=r}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(a7(a7({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case gx.TCP_RELAY:this.candidates=n;break;case gx.UDP_TCP_RELAY:case gx.RELAY:this.candidates=[...t,...n];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=GO(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 n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}mungRecvMediaDsec(e,t){const n=GO(e);return b2(n,t),A2(n,t),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,n){const i=this.sessionDesc.mediaDescriptions.find((t=>e===fx.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(i){const e=i.attributes.ssrcs.find((e=>e.attributes.label===t));var r;if(e)e.attributes.label=n,null===(r=e.attributes.msid)||void 0===r||r.replace(t,n)}}mungMediaDesc(e){const t=GO(e);return I2(t),function(e){const t=e.attributes.extmaps.find((e=>E2(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 n of t.attributes.ssrcs)if(n.attributes.label===e)return[n]}}var d7;function l7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function u7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l7(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let h7=(d7=class e extends mx{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 Di(t=Object.keys(aD)).call(t,e)})))]}constructor(t,n){super(t,n),Db(this,"store",void 0),Db(this,"peerConnection",void 0),Db(this,"remoteSDP",void 0),Db(this,"initialOffer",void 0),Db(this,"statsFilter",void 0),Db(this,"useRTX",!1),Db(this,"localCapabilities",void 0),Db(this,"localCandidateCount",0),Db(this,"allCandidatesReceived",!1),Db(this,"establishPromise",void 0),Db(this,"mutex",void 0),this.store=n,this.mutex=new pN("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=KN(this.peerConnection,iD("STATS_UPDATE_INTERVAL"),void 0,Tw()?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=S2(e.sdp),n=g2(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:iD("FILTER_VIDEO_FEC"),filterAudioFec:iD("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=n,this.initialOffer=e,u7(u7({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:n},offerSDP:e.sdp})}catch(e){throw new Jw(Xw.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 c7(u7(u7({},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(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new Jw(Xw.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var n=this;return EA((function*(){const i=yield mA(n.mutex.lock());try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map((e=>n.peerConnection.addTrack(e._mediaStreamTrack))),o=yield mA(n.peerConnection.createOffer()),s=_D(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,i=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!i)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,n){const i=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===i.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&i.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(i[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:n?e.ssrcIds[1]:void 0}]:[{ssrcId:i[0].ssrcId}]}return[{ssrcId:i[0].ssrcId}]}(i,t.id,n.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{mw()&&e.replaceTrack(null),n.peerConnection.removeTrack(e)})),e}const d=n.mungSendOfferSDP(o.sdp,e);n.remoteSDP.receive(e,t,c);const l=n.remoteSDP.toString();return yield mA(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(n.applySendEncodings(r,e)),yield mA(n.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const n=e._mediaStreamTrack.id;return{localSSRC:a[t],id:n}}))}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{i()}}))()}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 n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.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=>{mw()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:n,mslabel:r}=this.remoteSDP.send(e,t,i),o=new Wh(((t,i)=>{const o=setTimeout((()=>{i(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=i=>{const a=lw();if(("Safari"===a.name&&11===Number(a.version)||Rw())&&i.track.id!==n&&i.streams[0].id===r){var c;const r=i.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,n,i.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(r)}if(i.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(i.track)};this.peerConnection.addEventListener("track",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:n}}catch(e){throw new Jw(Xw.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 n=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(n)}catch(e){throw new Jw(Xw.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 n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(mw()&&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(Xw.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 n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(mw()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return EA((function*(){const n=yield mA(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=uP().supportPCSetConfiguration;if(e===gx.RELAY&&!i)return;if(i){const n=t.peerConnection.getConfiguration(),i=e===gx.RELAY?"relay":"all";n.iceTransportPolicy!==i&&(UD.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}e!==gx.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield mA(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=S2(r.sdp),{remoteIceParameters:s}=yield o.iceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield mA(t.peerConnection.setLocalDescription(r)),yield mA(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){UD.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}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(),n=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const i=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getSenders().filter((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e}));1===n.length&&await this.applySendEncodings(n,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getSenders().find((e=>{var n;return(null===(n=e.track)||void 0===n?void 0:n.id)===t}));n&&await n.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new Jw(Xw.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new Jw(Xw.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,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),iD("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 n={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(SO(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),iD("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),n}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 n;if(!t){t=this.peerConnection.getSenders().find((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e._mediaStreamTrack.id}))}if(!t)return UD.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!uP().supportSetRtpSenderParameters)return UD.warn("Browser not support set rtp-sender parameters");const i={},r={};if(e instanceof MM)switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(iD("DSCP_TYPE")&&Bw()){var o;const e=iD("DSCP_TYPE");Di(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];a&&Object.assign(a,r),Object.assign(s,i),UD.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!uP().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];i&&r&&await this.updateRtpSenderEncodings(r,i)}}catch(e){UD.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const n=_D(e);return t.forEach(((e,t)=>{const i=e._mediaStreamTrack,r=n.mediaDescriptions.find((e=>e.attributes.mid===i.kind));r&&b2(r,e)})),ED(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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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,n)=>{let{id:i,mslabel:r}=t;const{kind:o}=e[n];return new Wh(((e,t)=>{const n=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=t=>{const a=lw();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==i&&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,i,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:r,id:i})}if(t.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:t.track,id:i})};this.peerConnection.addEventListener("track",s)}))})),n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const i=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(i),await Wh.all(t)}catch(e){throw new Jw(Xw.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(uP().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}}},DV(d7.prototype,"connect",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"connect"),d7.prototype),DV(d7.prototype,"stopSending",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"stopSending"),d7.prototype),DV(d7.prototype,"receive",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"receive"),d7.prototype),DV(d7.prototype,"stopReceiving",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"stopReceiving"),d7.prototype),DV(d7.prototype,"muteRemote",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"muteRemote"),d7.prototype),DV(d7.prototype,"unmuteRemote",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"unmuteRemote"),d7.prototype),DV(d7.prototype,"muteLocal",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"muteLocal"),d7.prototype),DV(d7.prototype,"unmuteLocal",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"unmuteLocal"),d7.prototype),DV(d7.prototype,"close",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"close"),d7.prototype),DV(d7.prototype,"updateEncoderConfig",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"updateEncoderConfig"),d7.prototype),DV(d7.prototype,"updateSendParameters",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"updateSendParameters"),d7.prototype),DV(d7.prototype,"replaceTrack",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"replaceTrack"),d7.prototype),DV(d7.prototype,"getRemoteSSRC",[p7],Object.getOwnPropertyDescriptor(d7.prototype,"getRemoteSSRC"),d7.prototype),d7);function p7(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}const _7={name:"PlanBConnection",create:function(e){let{store:t,spec:n}=e;return new h7(n,t)}},E7={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!uP().supportWebRTCEncodedTransform)return void UD.warning("browser not support audio encoded transform");if(pU.has(e))return;if(!e.track)return;const n={track:e.track};if(Ew()){if(!e.createEncodedStreams)return void UD.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void UD.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(UD.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=t.metadata&&t.metadata();s?function(e,t){const{chunk:n,controller:i}=t,r=uU.METADATA;n.data=function(e,t,n){const i=n.byteLength,r=i+dU+lU,o=aU+cU+r,s=new ArrayBuffer(e.byteLength+o),a=new DataView(s);a.setUint8(0,sU),a.setUint16(1,r),a.setUint8(3,t),a.setUint16(4,i);for(let e=0;e<i;e++)a.setUint8(6+e,n[e]);const c=new Uint8Array(a.buffer);return c.set(new Uint8Array(e),o),c.buffer}(n.data,r,e),i.enqueue(n)}(s,{sender:e,chunk:r,controller:o}):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(mw()){if("undefined"==typeof RTCRtpScriptTransform)return void UD.warning("browser not support RTCRtpScriptTransform");const r=oU(),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)!==n.track.id)UD.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=pU.get(e);if(t){pU.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){UD.warning(e&&e.message)}}}pU.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!uP().supportWebRTCEncodedTransform)return void UD.warning("browser not support audio encoded transform");if(kU.has(e))return;const n={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};if(Ew()&&!Rw()){if(!e.createEncodedStreams)return void UD.warning("browser not support createEncodedStreams() API");Cw(sw.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(e){return void UD.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(UD.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)),t.enableTopn?function(e,t,n){var i;const r=hU(new DataView(t.data));if(!r)return n.enqueue(t);const o=e.track.id;MU.set(o,e.track);const s=null===(i=r.tlv.find((e=>e.tag===uU.AUDIO_LEVEL)))||void 0===i?void 0:i.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 n=CU.get(e);if(n||(n=function(e){const t=new RU;return CU.set(e,t),bU||(bU=new yU(iD("TOPN_SILENCE_THRESHOLD")||500),bU.on("ActiveSpeakerChanged",(e=>{null!=e&&(IU=e)}))),bU.addSpeakers([t]),t}(e)),CU.size<=AU)return{selected:!0,speaker:n};if(!bU)throw new Error("no active speaker detector");return bU.levelChanged(n.id,t),wU=bU.loudest.map((e=>e.id)),IU&&!Di(wU).call(wU,IU)&&wU.length>=AU&&wU.pop(),{selected:Di(wU).call(wU,n.id)||n.id===IU,speaker:n}}(e,c),u=function(e,t,n){const i=OU.get(e)||new PU(e,t);return i.score=n,OU.set(e,i),function(e){if(NU.set(e,!0),!DU)return void(DU=Date.now());const t=Date.now();t-DU>1e3&&(NU.get(e)?NU.set(e,!1):(LU(e),NU.delete(e)),DU=t)}(e),i}(o,e.track,l.energyScore);u.addSample(d),u.active&&(t.data=r.frame.buffer,n.enqueue(t))}(e,r,o):t.enableMetadata||t.enablePts?function(e,t,n,i){const r=new DataView(e.data),o=r.getUint8(0);let s;if(0!=(128&o)&&71!==o){const t=function(e){if(e.byteLength<=0)return[];const t=[];let n=0;for(;n<e.byteLength;){const i=(128&e.getUint8(n))>>7,r=127&e.getUint8(n);if(!(i&&n+4<=e.byteLength)){n++;break}{const i=e.getUint32(n,!1),o=(16776192&i)>>10,s=1023&i;t.push({pt:r,ts_offset:o,length:s,data:new Uint8Array}),n+=4}}let i=e.byteLength-n;for(const r of t){if(r.length>i)return console.warn("Broken red payload"),[];r.length>0&&(r.data=new Uint8Array(e.buffer,e.byteOffset+n,r.length),n+=r.length,i-=r.length)}if(i>0){const r={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:i,data:new Uint8Array(e.buffer,e.byteOffset+n,i)};t.push(r)}return t}(r);if(t.length>0){const n=function(e){let t=0;for(let n=0;n<e.length;n++)t+=n<e.length-1?4:1,t+=e[n].length;const n=new Uint8Array(t);let i=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;n[i++]=r>>24&255,n[i++]=r>>16&255,n[i++]=r>>8&255,n[i++]=255&r}else n[i++]=127&e[t].pt;for(const t of e)n.set(t.data,i),i+=t.length;return n}(t.map((e=>{const t=new Uint8Array(e.length);t.set(e.data);const n=hU(new DataView(t.buffer));return null!=n&&n.frame&&(e.data=null==n?void 0:n.frame),s=n,e})));e.data=n.buffer}}else s=hU(r),s&&(e.data=s.frame.buffer);if(t.enqueue(e),!s)return;const a=s.tlv.find((e=>e.tag===uU.METADATA));a&&n&&a.value instanceof Uint8Array&&n(a.value);const c=s.tlv.find((e=>e.tag===uU.AUDIO_64_BIT_PTS));c&&i&&c.value instanceof Uint8Array&&8==c.value.length&&i(new DataView(c.value.buffer).getBigUint64(0,!0))}(r,o,t.onMetadata,t.onPts):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void UD.warning("browser not support RTCRtpScriptTransform");const t=oU(),r=new MessageChannel;await new Wh((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:r.port2},[r.port2]);e.transform=o,await new Wh((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==n.track.id?(UD.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)):t.data.metadata&&n.onMetadata?n.onMetadata(t.data.metadata):t.data.pts&&n.onPts&&n.onPts(t.data.pts)},n.worker=t}function i(){e.track.removeEventListener("ended",i),function(e){const t=kU.get(e);if(t){!function(e){const t=CU.get(e);t&&(CU.delete(e),bU&&(bU.removeSpeakers([t]),0===CU.size&&(bU.destroy(),bU=null)))}(e),LU(e.track.id),kU.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){UD.warning(e&&e.message)}}}(e)}kU.set(e,n),e.track.addEventListener("ended",i)},interceptLocalVideoFrame:async function(e,t){if(!uP().supportWebRTCEncodedTransform)return void UD.warning("browser not support video encoded transform");if(GU.has(e))return;if(!e.track)return;const n={track:e.track};if(Ew()){if(!e.createEncodedStreams)return void UD.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void UD.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){n.controller||(n.controller=r),e.track&&e.track.id!==n.track.id&&(UD.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=BU(new Uint8Array(t.data)),a=o.shift();if(a){const e=function(e,t,n){switch(n){case UU:return function(e,t){const n=FU(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(6+r+1+i+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(n,6+a),s.set(new Uint8Array(e),6+a+i),s.buffer}(e,t);case VU:return function(e,t){const n=FU(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(7+r+1+i+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(n,7+a),a+=i,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)}else{if(!mw())return;{if("undefined"==typeof RTCRtpScriptTransform)return void UD.warning("browser not support RTCRtpScriptTransform");const r=oU(),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)!==n.track.id&&(UD.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i))},n.worker=r}}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=GU.get(e);if(t){GU.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){UD.warning(e&&e.message)}}}GU.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!uP().supportWebRTCEncodedTransform)return void UD.warning("browser not support video encoded transform");if(!e.track)return;if(jU.has(e)){const n=jU.get(e);return void(n&&(n.onSei=t.onSei))}const n={track:e.track,onSei:t.onSei};if(Ew()){if(!e.createEncodedStreams)return void UD.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void UD.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){if(n.controller||(n.controller=o),!n.firstFrameInfo){var s;const e=r.getMetadata()||{};n.firstFrameInfo=dL({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,n.firstFrameInfo)}e.track&&e.track.id!==n.track.id&&(UD.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const a=function(e,t){switch(t){case UU:return function(e){const t=new DataView(e.data);let n=0;for(;n+4<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&6===t.getUint8(n+4)){let i=n+6,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=xU(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);case VU:return function(e){const t=new DataView(e.data);let n=0;for(;n+5<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&78===t.getUint8(n+4)&&1===t.getUint8(n+5)&&101===t.getUint8(n+6)){let i=n+7,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=xU(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);default:return null}}(r,BU(new Uint8Array(r.data)));a&&n.onSei&&n.onSei(a),o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(mw()){if("undefined"==typeof RTCRtpScriptTransform)return void UD.warning("browser not support RTCRtpScriptTransform");const r=oU(),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)!==n.track.id)UD.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.sei&&n.onSei)n.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)}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}!function(e){const t=jU.get(e);if(t){jU.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){UD.warning(e&&e.message)}}}(e)}jU.set(e,n),e.track.addEventListener("ended",i)}},m7={name:"InterceptFrame",create:()=>E7};var f7;function g7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function S7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?g7(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let T7=(f7=class e extends mx{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 Di(t=Object.keys(aD)).call(t,e)})))]}constructor(e,t,n){super(e,t),Db(this,"id",$O(5,"connection-")),Db(this,"store",void 0),Db(this,"peerConnection",void 0),Db(this,"forceTurn",!1),Db(this,"remoteSDP",void 0),Db(this,"initialOffer",void 0),Db(this,"transportEventReceiver",void 0),Db(this,"statsFilter",void 0),Db(this,"extension",{useXR:iD("USE_XR")}),Db(this,"localCapabilities",void 0),Db(this,"remoteCodecs",void 0),Db(this,"localCandidateCount",0),Db(this,"allCandidatesReceived",!1),Db(this,"isPreallocation",!1),Db(this,"preMediaMap",new Map),Db(this,"dataStreamChannelMap",new Map),Db(this,"establishPromise",void 0),Db(this,"recoveredDataChannelIds",[]),Db(this,"currentDataChannelId",1),Db(this,"supportAV1RtpSpec",!1),Db(this,"mutex",void 0),Db(this,"qualityLimitationReason",UN.NONE),Db(this,"isFirstConnected",!1),this.store=t,this.forceTurn=w5(e),this.mutex=new pN("NVConnectionExtension-mutex",t.clientId),this.peerConnection=n,this.isFirstConnected=!1,this.statsFilter=KN(this.peerConnection,iD("STATS_UPDATE_INTERVAL"),void 0,Tw()?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 UD.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 n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else UD.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 n=S2(t.sdp),i=await P2({filterRTX:!iD("USE_PUB_RTX")&&!iD("USE_SUB_RTX"),filterVideoFec:iD("FILTER_VIDEO_FEC"),filterAudioFec:iD("FILTER_AUDIO_FEC"),filterVideoCodec:iD("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:iD("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:iD("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=M2(i),this.initialOffer=t,iD("ENABLE_SVC")&&"av1"==this.store.codec){const t=await D2();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&W2(t.sdp)&&(r=GO(i),l2(r)),S7(S7({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new Jw(Xw.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&W2(this.initialOffer.sdp)&&u2(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new a5(S7(S7({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!iD("ENABLE_PRE_SUB_WITH_PRE_PC")||!iD("PRE_USE_LOCAL_CODECS"))&&EP(this.store),!0),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),_P()){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=iD("PRE_SUB_NUM")||1,i=e>n?e:n,{mids:r,preSSRCs:o}=this.remoteSDP.preloadRemoteMedia(i),s=B2(this.initialOffer.sdp,this.extension),a=this.logSDPExchange(s||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:s}),null==a||a(s),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const c=await this.peerConnection.createOffer(),d=this.logSDPExchange(c.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(c);const l=this.remoteSDP.toString();null==d||d(l),await this.peerConnection.setRemoteDescription({type:"answer",sdp:l}),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(o)),this.presetMedia(r,o);const u=this.peerConnection.getTransceivers()[0];null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver)}else{const t=this.remoteSDP.toString(),i=B2(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),EP(this.store))if(e.preallocation&&iD("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=iD("PRE_SUB_NUM")||1,i=e>t?e:t,{mids:r,preSSRCs:o}=this.remoteSDP.preloadRemoteMedia(i);await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(o)),this.presetMedia(r,o)}else{const{preSSRCs:t=[]}=e,n=t.map((e=>e.ssrcMsg[0].ssrcId));if(0===t.length)return;const{mids:i}=this.remoteSDP.batchSend(t.map((e=>Object.assign({},e))));await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(i,n)}}}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const r=i.receiver.track;let o;"video"===r.kind&&iD("ENABLE_PRE_RENDER")&&(o=new Zk({trackId:"track-".concat(r.kind,"-unknown-").concat(this.store.clientId,"_").concat($O(5,""))},!0),o.updateVideoTrack(r),o.onFirstVideoFrameRender=()=>{var e;const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},o.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},o.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[n],{mid:e,track:r,player:o,transceiver:i})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1;const{rtpCapabilities:n}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(n),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const{preSSRCs:i=[]}=e,r=i.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(r)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((n=>{let[i,{mid:r,player:o,track:s}]=n;return e.push(r),t.push(i),this.preMediaMap.delete(i),o&&o.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await F2(this.peerConnection,this.remoteSDP,this.extension),UD.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),cP.reportApiInvoke(this.store.sessionId,{name:_O.PRELOAD_MEDIA_FAILED,options:[i,t],tag:EO.TRACER}).onSuccess()),i.length>0){const{mids:e}=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e))));await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(r)),this.presetMedia(e,r)}}t?(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):UD.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return EA((function*(){const r=yield mA(i.mutex.lock("From NVConnectionExtension.send"));try{if(!i.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const o=[],s=c2();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,S7({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),Tw()&&!0===iD("SIMULCAST")&&(yield mA(i.applySimulcastForFirefox(o,e)));const a=yield mA(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=_D(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 T2(t,iD("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield mA(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield mA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield mA(i.applySimulcastEncodings(o,e)),yield mA(i.applySendEncodings(o,e)),null==_||_(p),yield mA(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof Jw?e:new Jw(Xw.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 n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)UD.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");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:iD("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const{needExchangeSDP:i}=this.remoteSDP.sendDataChannel();if(i){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),UD.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else UD.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof Jw?e:new Jw(Xw.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(Xw.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=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;R5(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),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(Xw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){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,n,i);o&&(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.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,transceiver:s}}catch(e){throw new Jw(Xw.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:n}=this.remoteSDP.batchSend(e);return n&&(await F2(this.peerConnection,this.remoteSDP,this.extension),UD.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(Xw.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[n,{mid:i,player:r}]=t;if(i===e)return this.preMediaMap.delete(n),r&&r.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.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(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.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(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new Jw(Xw.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),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==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return EA((function*(){const n=yield mA(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=uP().supportPCSetConfiguration,r=iD("FORCE_TURN_TCP")||t.forceTurn;if(e===gx.RELAY&&!i)return;if(i&&!r){const n=e===gx.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(UD.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield mA(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=S2(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 mA(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield mA(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){UD.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(gx.TCP_RELAY),await F2(this.peerConnection,this.remoteSDP,this.extension)}catch(e){UD.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{R5(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 S7(S7({},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 n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Jw(Xw.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?Tw()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.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:n,remote:i}=t.getSelectedCandidatePair();return{local:S7(S7({},wN),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:S7(S7({},wN),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.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 n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=s2(e.url||"");UD.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&UD.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,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,UD.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),iD("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 n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(SO(t.turnServer.servers)?n.iceServers=t.turnServer.servers:iD("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(iD("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),iD("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),iD("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),iD("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),iD("ENABLE_ENCODED_TRANSFORM")&&uP().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}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(Z1(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!iD("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 n=iD("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Z1(e.turnServerURL),":443?transport=tcp")}):4===n&&(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(Z1(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 n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const{local:e,remote:t}=n.getSelectedCandidatePair()||{};if(e&&t){const n=e.address+":"+e.port,i=t.address+":"+t.port;UD.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(s2(n)),", remote ").concat(JSON.stringify(s2(i))))}}}))}}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 n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return UD.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return UD.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!uP().supportSetRtpSenderParameters)return UD.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=a2(this.peerConnection,e._mediaStreamTrack),a=qL(e);if(g5(e)&&s&&t&&a&&this.getLocalVideoStats&&Di(n=["vp8","vp9"]).call(n,this.store.codec)){var c;const n=r.degradationPreference||(Di(c=e._hints).call(c,xP.CUSTOM_TRACK)?iD("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");T5(this.id+s.mid,a,this,n,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const{bitrateMax:t,frameRate:n,scaleResolutionDownBy:i}=e._encoderConfig;t&&(o.maxBitrate=1e3*t),(Di(d=e._hints).call(d,xP.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(o.maxFramerate=$1(n)),i&&i>=1&&(o.scaleResolutionDownBy=i))}const{maxFramerate:l}=iD("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),iD("DSCP_TYPE")&&Bw()){var u;const e=iD("DSCP_TYPE");Di(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(i=h.encodings)||void 0===i?void 0:i[0];Tw()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),UD.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await j2(this.store.codec,t,iD("SVC_MODE"))}async updateAdaptation(e,t){var n,i;if(!e)return UD.debug("[updateAdaptation] no rtpSender found");if(!uP().supportSetRtpSenderParameters)return UD.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=$1(s)),a&&a>=1&&Di(n=["vp8","vp9"]).call(n,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),UD.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?UD.debug("[updateAdaptation] peerConnection not connected}"):UD.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):UD.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!uP().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof MM&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){UD.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=_D(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(b2(o,e),N2(o,e,this.store.codec))})),ED(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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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 n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof MM&&!Di(n=d._hints).call(n,xP.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.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 n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!Tw()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof MM&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._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,n,i,r,o;return!!(e instanceof MM&&iD("SIMULCAST")&&"vp8"===this.store.codec&&!Di(t=e._hints).call(t,xP.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.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,n,i){if(iD("SDP_LOGGING"))return UD.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during NVConnectionExtension.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}: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(uP().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},DV(f7.prototype,"updateRemoteRTPCapabilities",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"updateRemoteRTPCapabilities"),f7.prototype),DV(f7.prototype,"connect",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"connect"),f7.prototype),DV(f7.prototype,"updateRemoteConnect",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"updateRemoteConnect"),f7.prototype),DV(f7.prototype,"createDataChannels",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"createDataChannels"),f7.prototype),DV(f7.prototype,"receive",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"receive"),f7.prototype),DV(f7.prototype,"batchReceive",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"batchReceive"),f7.prototype),DV(f7.prototype,"stopReceiving",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"stopReceiving"),f7.prototype),DV(f7.prototype,"muteRemote",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"muteRemote"),f7.prototype),DV(f7.prototype,"unmuteRemote",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"unmuteRemote"),f7.prototype),DV(f7.prototype,"muteLocal",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"muteLocal"),f7.prototype),DV(f7.prototype,"unmuteLocal",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"unmuteLocal"),f7.prototype),DV(f7.prototype,"close",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"close"),f7.prototype),DV(f7.prototype,"updateEncoderConfig",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"updateEncoderConfig"),f7.prototype),DV(f7.prototype,"updateSendParameters",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"updateSendParameters"),f7.prototype),DV(f7.prototype,"replaceTrack",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"replaceTrack"),f7.prototype),DV(f7.prototype,"updateAdaptation",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"updateAdaptation"),f7.prototype),DV(f7.prototype,"getRemoteSSRC",[R7],Object.getOwnPropertyDescriptor(f7.prototype,"getRemoteSSRC"),f7.prototype),f7);function R7(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}var v7;function y7(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=gA,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new C7(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function C7(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 C7=function(e){this.s=e,this.n=e.next},C7.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Wh.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Wh.reject(e):t(n.apply(this.s,arguments))}},new C7(e)}let b7=(v7=class e extends mx{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,n){super(t,n),Db(this,"name","DataChannelConnection"),Db(this,"store",void 0),Db(this,"peerConnection",void 0),Db(this,"cname",void 0),Db(this,"mutex",new pN("DataChannelConnection-mutex")),Db(this,"dataChannel",void 0),Db(this,"_p2pConnection",void 0),Db(this,"establishPromise",void 0),Db(this,"_nvMedia",void 0),this.store=n,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 T7(t,n,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,n)=>{const i=setTimeout((()=>{this.closeSignal(),n(new dP(Xw.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),iD("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(i),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),n(e)},this.dataChannel.addEventListener("close",(()=>{n(new dP(Xw.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(e){return this._p2pConnection.checkDtlsParameters(e)}checkIceParameters(e){return this._p2pConnection.checkIceParameters(e)}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,n){var i=this;return EA((function*(){const r=yield mA(i.mutex.lock("From DataChannelConnection.send"));try{return yield*fA(y7(i._p2pConnection.send(e,t,n)))}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,n,i){return this._nvMedia?(UD.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(UD.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,n,i))}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 EA((function*(){return yield*fA(y7(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,n,i){if(iD("SDP_LOGGING"))return UD.upload("exchanging ".concat(n," ").concat(t," SDP during DataChannelConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(SO(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),iD("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),iD("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),iD("ENABLE_ENCODED_TRANSFORM")&&uP().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}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(Z1(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!iD("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,n)=>{var i;return null===(i=this.onFirstVideoDecoded)||void 0===i?void 0:i.call(this,e,t,n)},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 n;return null===(n=this.onSelectedLocalCandidateChanged)||void 0===n?void 0:n.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n?void 0:n.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)}},DV(v7.prototype,"connect",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"connect"),v7.prototype),DV(v7.prototype,"updateRemoteRTPCapabilities",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"updateRemoteRTPCapabilities"),v7.prototype),DV(v7.prototype,"createDataChannels",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"createDataChannels"),v7.prototype),DV(v7.prototype,"receive",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"receive"),v7.prototype),DV(v7.prototype,"stopReceiving",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"stopReceiving"),v7.prototype),DV(v7.prototype,"muteRemote",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"muteRemote"),v7.prototype),DV(v7.prototype,"unmuteRemote",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"unmuteRemote"),v7.prototype),DV(v7.prototype,"muteLocal",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"muteLocal"),v7.prototype),DV(v7.prototype,"unmuteLocal",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"unmuteLocal"),v7.prototype),DV(v7.prototype,"close",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"close"),v7.prototype),DV(v7.prototype,"updateEncoderConfig",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"updateEncoderConfig"),v7.prototype),DV(v7.prototype,"updateSendParameters",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"updateSendParameters"),v7.prototype),DV(v7.prototype,"replaceTrack",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"replaceTrack"),v7.prototype),DV(v7.prototype,"getRemoteSSRC",[I7],Object.getOwnPropertyDescriptor(v7.prototype,"getRemoteSSRC"),v7.prototype),v7);function I7(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=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 i.apply(this,o)}finally{n()}},n}function A7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class w7 extends uO{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Di(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(wx.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(wx.CONNECTED):"closed"===this._state?this.emit(wx.CLOSED):"failed"===this._state&&this.emit(wx.FAILED))}constructor(e,t,n,i){super(),Db(this,"connectionID",0),Db(this,"currentURLIndex",0),Db(this,"reconnectReason",void 0),Db(this,"_reconnectMode","tryNext"),Db(this,"_initMutex",void 0),Db(this,"_name",void 0),Db(this,"_state","closed"),Db(this,"_reconnectInterrupter",void 0),Db(this,"_url",void 0),Db(this,"_retryConfig",void 0),Db(this,"_reconnectCount",0),Db(this,"_forceCloseTimeout",5e3),Db(this,"_onlineReconnectListener",void 0),Db(this,"_closeEstablishingTransmitter",(()=>{})),Db(this,"_store",void 0),Db(this,"_joinChannelServiceRecordIndex",void 0),Db(this,"_transmitter",void 0),Db(this,"_useCompress",void 0),Db(this,"_inflateLength",0),Db(this,"_deflateLength",0),this._store=i,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?A7(Object(n),!0).forEach((function(t){Db(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):A7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this._useCompress=n}resetReconnectCount(e){UD.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 UD.warning("[".concat(this._name,"] can not reconnect, no websocket"));var n;(void 0!==e&&(this.reconnectMode=e),UD.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(n=this._store)||void 0===n||n.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const i=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),i&&i.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 O7=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class N7{constructor(e,t,n){Db(this,"version",1),Db(this,"initialRTO",void 0),Db(this,"maxBatchAckCount",void 0),Db(this,"maxRTO",void 0),Db(this,"initialRTT",void 0),Db(this,"ID",void 0),Db(this,"rtt",void 0),Db(this,"packetNumber",1),Db(this,"rtoRatioMap",new Map),Db(this,"timeoutMap",new Map),Db(this,"unorderedPacketQueue",[]),Db(this,"batchAckPacketQueue",[]),Db(this,"lastOrderedPacketNumber",0),Db(this,"batchAckTimer",void 0),Db(this,"sendImpl",void 0),Db(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=$O(7,"transmitter-"),this.initialRTO=void 0!==(null==n?void 0:n.initialRTO)?n.initialRTO:iD("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:iD("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:iD("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==n?void 0:n.maxBatchAckCount)?n.maxBatchAckCount:iD("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==n?void 0:n.maxRTO)?n.maxRTO:iD("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:O7.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case O7.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const n=new ArrayBuffer(t.length+15),i=new DataView(n);i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.packetNumber),rO(i,7,BigInt(e.sendTs));return new Uint8Array(i.buffer).set(t,15),n}case O7.Ack:{const t=new ArrayBuffer(16),n=new DataView(t);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.maxAckPacketNumber),n.setUint8(7,e.shift),rO(n,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),n=t.getUint16(0),i=t.getUint8(2);switch(i){case O7.Default:{const r=t.getUint32(3),o=iO(t,7),s=e.slice(15),a=new Uint8Array(s);return{version:n,type:i,packetNumber:r,sendTs:Number(o),payload:a}}case O7.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=iO(t,8);return{version:n,type:i,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw UD.error("[".concat(this.ID,"] Unrecognized packet type ").concat(i)),new Error("Unrecognized packet type ".concat(i))}}sendMessage(e){iD("DC_DEBUG_LOG")&&"string"==typeof e&&UD.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 n=this.calculateRTO(t),i=window.setTimeout((()=>{this.resendMessage(t)}),n);this.timeoutMap.set(t.packetNumber,i),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===O7.Default?this.ack(t):t.type===O7.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,n]=e;window.clearTimeout(n)})),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),n=window.setTimeout((()=>{iD("DC_DEBUG_LOG")&&"string"==typeof e.payload&&UD.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,n),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 n=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),n>this.maxRTO?this.maxRTO:n}}updateRTT(e,t){const n=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-n-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:O7.Ack,version:this.version};iD("DC_DEBUG_LOG")&&UD.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:O7.Ack,version:this.version};iD("DC_DEBUG_LOG")&&UD.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:O7.Ack,version:this.version};iD("DC_DEBUG_LOG")&&UD.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===O7.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 D7 extends w7{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),Db(this,"_initMutex",void 0),Db(this,"_reconnectInterrupter",void 0),Db(this,"_url",void 0),Db(this,"_transmitter",void 0),Db(this,"_addresses",void 0),Db(this,"_reliableTransmission",void 0),Db(this,"_textEncoder",void 0),Db(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new pN("datachannel");const{timeout:n,timeoutFactor:i}=t,r=Math.max(300,Math.floor(3*n/5)),o=Math.max(1.2,Math.floor(8*i)/10);IO.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),PO.on(AO.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===IO.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=i))}))}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 n=(t,n)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||iD("FINGERPRINT")));const i=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(i).then(t).catch(n),this.once(wx.CLOSED,(()=>n(new dP(Xw.WS_DISCONNECT)))),this.once(wx.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new Wh(((e,t)=>{n(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 dP(Xw.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const n=this._textEncoder.encode(e),i=Pj(n,{raw:!0});this._reliableTransmission.sendMessage(i)}catch(e){throw new dP(Xw.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,n)=>{var i;const r=()=>{UD.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var i;if(null===(i=this._closeEstablishingTransmitter)||void 0===i||i.call(this),UD.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 i=NO(this,wx.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(i);if("closed"===this.state)return void UD.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return n(new dP(Xw.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else n(new dP(Xw.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),UD.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(i=this._store)||void 0===i?void 0:i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();wO(this,wx.TO_CONNECT_DATACHANNEL).then((e=>{var t,n;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:i,close:d}=e;this._transmitter=i,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;UD.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new N7((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(wx.ON_MESSAGE,e);else{const t=kj(e,{raw:!0}).buffer,n=this._textDecoder.decode(t);this.emit(wx.ON_MESSAGE,n)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),i.onclose=o,i.onmessage=s,null===(n=this._store)||void 0===n||n.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 dP&&e.code===Xw.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof dP&&e.code===Xw.WS_ERR){const t=new dP(Xw.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return UD.error("[".concat(this._name,"]").concat(t)),void n(t)}o&&o(e)}else n(new dP(Xw.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||PO.networkState!==IO.OFFLINE||(this._onlineReconnectListener=PO.onlineWaiter&&PO.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let n=!0;if(this._reconnectInterrupter=()=>{n=!1},t){const t=mN(this._reconnectCount,this._retryConfig);UD.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await Wh.race([QO(t),this._onlineReconnectListener||new Wh((()=>{}))])}if("closed"===this.state||!n)return!1;this._reconnectCount+=1;const i=async(e,t)=>{this.emit(wx.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];await i(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||iD("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return UD.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);UD.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];await i(t,e)}else"recover"===e&&(UD.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(wx.FAILBACK));return!0}catch(n){var r,o;return UD.error("[".concat(this._name,"] reconnect failed"),n.toString()),null!=n&&null!==(r=n.data)&&void 0!==r&&r.desc&&Array.isArray(n.data.desc)&&n.data.desc.length&&Di(o=n.data.desc).call(o,"dynamic key expired")?(this.emit(wx.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class P7 extends uO{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===VV.CONNECTED?this.emit(xV.WS_CONNECTED):e===VV.RECONNECTING?this.emit(xV.WS_RECONNECTING,this._websocketReconnectReason):e===VV.CLOSED&&this.emit(xV.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&&(UD.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let{type:t,message:n}=e;this.emit(t,n),t===GV.ON_NOTIFICATION&&this.handleNotification(n),t===GV.ON_USER_BANNED&&this.handleUserBanned(n)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(gO.UID_BANNED);break;case 15:this.close(gO.IP_BANNED);break;case 16:this.close(gO.CHANNEL_BANNED)}}constructor(e,t){super(),Db(this,"__name__","DataChannelSignal"),Db(this,"_disconnectedReason",void 0),Db(this,"_websocketReconnectReason",void 0),Db(this,"_connectionState",VV.CLOSED),Db(this,"reconnectToken",void 0),Db(this,"websocket",void 0),Db(this,"openConnectionTime",void 0),Db(this,"clientId",void 0),Db(this,"lastMsgTime",Date.now()),Db(this,"uploadCache",[]),Db(this,"uploadCacheInterval",void 0),Db(this,"rttRolling",new SN(5)),Db(this,"pingpongTimer",void 0),Db(this,"inflateDataTimer",void 0),Db(this,"pingpongTimeoutCount",0),Db(this,"ortc",void 0),Db(this,"joinResponse",void 0),Db(this,"multiIpOption",void 0),Db(this,"initError",void 0),Db(this,"spec",void 0),Db(this,"store",void 0),Db(this,"isJoining",!1),Db(this,"pendingNotifications",[]),Db(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(xV.ON_BINARY_DATA,e);const t=JSON.parse(e);if(iD("DC_DEBUG_LOG")&&UD.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===GV.ON_NOTIFICATION||t._type===GV.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===GV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===GV.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),UD.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===GV.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===GV.ON_USER_BANNED&&this.handleUserBanned(t._message)))})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new D7("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===VV.CONNECTED&&this.reconnect("retry",Ax.OFFLINE)}))}async request(e,t,n,i){const r=$O(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((t,n)=>{if(this.connectionState===VV.CONNECTED)return t();const i=()=>{this.off(xV.WS_CLOSED,r),t()},r=()=>{this.off(xV.WS_CONNECTED,i),n(new dP(Xw.WS_ABORT))};this.once(xV.WS_CONNECTED,i),this.once(xV.WS_CLOSED,r),e!==FV.PUBLISH&&e!==FV.SUBSCRIBE&&e!==FV.UNSUBSCRIBE&&e!==FV.UNPUBLISH&&e!==FV.CONTROL&&e!==FV.RESTART_ICE||this.once(xV.DISCONNECT_P2P,(()=>{n(new dP(Xw.DISCONNECT_P2P))})),e!==FV.PUBLISH&&e!==FV.RESTART_ICE||this.once(xV.ABORT_P2P_EXECUTION,(()=>{n(new dP(Xw.DISCONNECT_P2P))}))}));if(this.connectionState!==VV.CONNECTING&&this.connectionState!==VV.RECONNECTING||e===FV.JOIN||e===FV.REJOIN||await a(),e===FV.LEAVE&&(this.websocket.unbindDcCloseEventListener(),i=!0),iD("DC_DEBUG_LOG")&&UD.debug("[datachannel-signal] sendMessage",o),await this.websocket.sendMessage(o,!0,!1),i)return;const c=new Wh(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.emit(xV.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new dP(Xw.WS_ABORT,"type: ".concat(e))),this.off(xV.WS_CLOSED,c),this.off(xV.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(xV.WS_CLOSED,c),this.once(xV.WS_RECONNECTING,c),QO(iD("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(UD.warning("dc request timeout, type: ".concat(e)),this.emit(xV.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===VV.CLOSED||e===FV.LEAVE)throw new dP(Xw.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===FV.JOIN||e===FV.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=Bx(l),h=new dP(Xw.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(UD.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===FV.JOIN||e===FV.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,UD.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ax.MULTI_IP)):this.reconnect(u.action,Ax.SERVER_ERROR),e===FV.JOIN||e===FV.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void UD.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(BV.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=iD("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==VV.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)}),iD("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const n={_type:e,_message:t};await this.websocket.sendMessage(n)}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,n)=>{this.once(xV.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(xV.WS_CLOSED,(()=>n(this.initError||new dP(Xw.WS_ABORT)))),this.connectionState=VV.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(wx.FAILBACK,(()=>{n(new dP(Xw.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(UD.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new dP(Xw.INIT_DATACHANNEL_TIMEOUT)))}),iD("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||gO.LEAVE,this.connectionState=VV.CLOSED,UD.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===gO.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new D7("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),iD("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(xV.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await wO(this,xV.REQUEST_JOIN_INFO);this.store.joinReq();let t=await wO(this,xV.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(this.isJoining=!0,this.pendingNotifications=[],t){UD.debug("join response from pre join response");const n=await this.request(FV.JOIN,e);n&&"ortc"in n&&(t=n)}else UD.debug("join response from request join_v3"),t=await this.request(FV.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(xV.REPORT_JOIN_GATEWAY,Xw.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(xV.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=VV.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new dP(Xw.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=DO(this,xV.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(FV.REJOIN,e);return!!t&&(this.connectionState=VV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),iD("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(GV.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(GV.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(GV.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(GV.MUTE_AUDIO,{uid:e.uid}):this.emit(GV.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(GV.MUTE_VIDEO,{uid:e.uid}):this.emit(GV.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(GV.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(GV.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(GV.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(GV.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(GV.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(FV.DOWNGRADE_CODEC,t)}handleNotification(e){UD.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Bx(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(gO.UID_BANNED),void this.close()):void this.reconnect(t.action,Ax.SERVER_ERROR);UD.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,iD("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const e=iD("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(UD.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>iD("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",Ax.FALLBACK):this.request(FV.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),iD("REPORT_STATS")&&this.send(FV.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(BV.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(wx.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(xV.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(wx.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(wx.CLOSED,(()=>{this.connectionState=VV.CLOSED})),this.websocket.on(wx.FAILED,(()=>{this._disconnectedReason=gO.NETWORK_ERROR,this.connectionState=VV.CLOSED})),this.websocket.on(wx.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===VV.CONNECTED?this.connectionState=VV.RECONNECTING:this.connectionState=VV.CONNECTING})),this.websocket.on(wx.WILL_RECONNECT,((e,t)=>{if(DO(this,xV.IS_P2P_DISCONNECTED)&&"retry"===e)return UD.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(xV.NEED_RENEW_SESSION),this.emit(xV.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(UD.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(xV.NEED_RENEW_SESSION),this.emit(xV.DISCONNECT_P2P)),t(e)})),this.websocket.on(wx.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{UD.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Ax.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(xV.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof dP&&e.code===Xw.UNEXPECTED_RESPONSE&&e.data.code===UV.ERR_NO_AUTHORIZED)return UD.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Ax.SERVER_ERROR);UD.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ax.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(wx.REQUEST_NEW_URLS,((e,t)=>{wO(this,xV.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(wx.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(GV.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(wx.TO_CONNECT_DATACHANNEL,((e,t)=>{wO(this,xV.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(wx.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(xV.DATACHANNEL_FAILBACK)}))}}const L7={name:"DataChannelConnection",create:function(e){let{store:t,spec:n}=e;return new b7(n,t)}};const k7={name:"DataChannelSignal",create:function(e){let{store:t,spec:n}=e;return new P7(n,t)}};HN(),nD("PROCESS_ID","process-".concat($O(8,""),"-").concat($O(4,""),"-").concat($O(4,""),"-").concat($O(4,""),"-").concat($O(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void UD.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();UD.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(tD,e)){const{value:i,expires:r}=t[e];if(r&&r<=n)return;oD[e]=i,tD[e]=i}}))}catch(t){UD.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(oD.AREAS)&&oD.AREAS.length>0&&p3(oD.AREAS,!0);const M7=(e,t,n)=>{UD.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),nD(e,t,n)};H2(M8,!1),H2(j8,!1),H2(I6,!1),H2(S9,!1),H2(P8,!1),H2(o7,!1),H2(_7,!1),H2(m7,!1),H2(L7,!1),H2(k7,!1);const U7=function(e){const t=new uO,n=e,i={getListeners:t.getListeners.bind(t),on:(e,n)=>(function(e,t){e===Ox.SECURITY_POLICY_VIOLATION&&O8(t,!0)}(e,n),t.on.bind(t)(e,n)),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 A8(A8({},n),i)}({__TRACK_LIST__:MP,VERSION:XN,BUILD:$N,ESM_BUNDLER:!1,ESM:!0,UMD:!1,DEV:!1,setParameter:M7,getParameter:iD,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(e){let t;return uP().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(!n)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}(n)}catch(e){throw new dP(Xw.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=cP.reportApiInvoke(null,{name:_O.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:EO.TRACER}),n=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const n=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,r=window.WebSocket;t=!(!n||!r),e&&!i&&(t=!1),t&&Gw()&&yw(75)&&(new n).close()}catch(e){UD.error("check system requirement failed: ",e),t=!1}return t}(e),i=T8();UD.debug("checkSystemRequirements, api:",n,"browser",i);const r=n&&i;return t.onSuccess(r),iD("IGNORE_RTC_DEVICE_CHECK")?n:r},getDevices:function(e){return LL.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return LL.getRecordingDevices(e)},getCameras:function(e){return LL.getCamerasDevices(e)},getElectronScreenSources:bL,getPlaybackDevices:function(e){return LL.getSpeakers(e)},createClient:S8,createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=iD("CAMERA_CAPTURE_CONFIG"),n=$O(8,"track-cam-"),i=cP.reportApiInvoke(null,{id:n,tag:EO.TRACER,name:_O.CREATE_CAM_VIDEO_TRACK,options:[dL({},e),t]});t&&(e.encoderConfig=t);const r=JL(e);let o=null;UD.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{o=(await OL({video:r},n)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new Jw(Xw.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(UD)}if(e.optimizationMode&&xM(n,o,e,NP(e.encoderConfig)),iD("USE_STANDARD_BITRATE_DEFAULT")){const t=NP(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const s=new UM(o,e,r,e.scalabiltyMode?PP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return i.onSuccess(s.getTrackId()),UD.info("create camera video success, trackId:",n),s},createCustomVideoTrack:function(e){const t=$O(8,"track-cus-"),n=cP.reportApiInvoke(null,{id:t,tag:EO.TRACER,name:_O.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});iD("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const i=new MM(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?PP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[xP.CUSTOM_TRACK]);return n.onSuccess(i.getTrackId()),UD.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const n="object"==typeof t?function(e){const t=zL(e);return TP()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),RP()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;n&&(t="auto");const i=$O(8,"track-scr-v-"),r=cP.reportApiInvoke(null,{id:i,tag:EO.TRACER,name:_O.CREATE_SCREEN_VIDEO_TRACK,options:[dL({},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&&Ew()&&(t.extensionId=e.extensionId);const{displaySurface:n,selfBrowserSurface:i,surfaceSwitching:r,systemAudio:o,preferCurrentTab:s,windowAudio:a,monitorTypeSurfaces:c}=e;(vw(107)||bw(107)||Dw(93))&&(n&&(Zw(n,"displaySurface",["browser","window","monitor"]),t.displaySurface=n),i?(Zw(i,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=i):t.selfBrowserSurface="include",r&&(Zw(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(vw(105)||bw(105)||Dw(91))&&o&&(Zw(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(vw(94)||bw(94)||Dw(80))&&s&&(t.preferCurrentTab=!0),(vw(141)||bw(141)||Dw(125))&&a&&(Zw(a,"windowAudio",["exclude","system"]),t.windowAudio=a),(vw(119)||bw(119)||Dw(105))&&c&&(Zw(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const d=e.encoderConfig?DP(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=uP();if(!c.supportShareAudio&&"enable"===t){const e=new Jw(Xw.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(UD)}UD.info("start create screen video track with config",e,"withAudio",t,"trackId",i);const d=c.supportShareAudio&&"disable"!==t;try{const e=await OL({screen:o,screenAudio:d?n||!0:void 0},i);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!s){const e=new Jw(Xw.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(UD)}if(!a&&"enable"===t){s&&s.stop();const e=new Jw(Xw.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(UD)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(xM(i,s,e,e.encoderConfig&&DP(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new MM(s,e.encoderConfig?DP(e.encoderConfig):{},e.scalabiltyMode?PP(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i,[xP.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),UD.info("create screen video track success","video:",l.getTrackId()),l;const u=new Gk(a,void 0,$O(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),UD.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 n=iD("CAMERA_CAPTURE_CONFIG"),i=$O(8,"track-mic-"),r=$O(8,"track-cam-"),o=cP.reportApiInvoke(null,{id:"".concat(i,"-").concat(r),tag:EO.TRACER,name:_O.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const s=JL(t),a=ZL(e);let c=null,d=null;UD.info("start create camera video track(".concat(r,") and microphone audio track(").concat(i,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await OL({audio:a,video:s},"".concat(i,"-").concat(r));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new Jw(Xw.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(UD)}if(t.optimizationMode&&xM(r,d,t,NP(t.encoderConfig)),iD("USE_STANDARD_BITRATE_DEFAULT")){const e=NP(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const l=new jk(c,e,a,i),u=new UM(d,t,s,t.scalabiltyMode?PP(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),UD.info("create camera video track(".concat(r,") and microphone audio track(").concat(i,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=$O(8,"track-mic-"),n=cP.reportApiInvoke(null,{id:t,tag:EO.TRACER,name:_O.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=ZL(e);let r=null;UD.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await OL({audio:i},t)).getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!r){const e=new Jw(Xw.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(UD)}const o=new jk(r,e,i,t);return n.onSuccess(o.getTrackId()),UD.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:VM,createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:n,encoderConfig:i}=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:n,encoderConfig:i},s=$O(8,"track-buf-"),a=cP.reportApiInvoke(null,{id:s,tag:EO.TRACER,name:_O.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(iD("DISABLE_WEBAUDIO"))throw new Jw(Xw.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");UD.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 n=null;if("string"==typeof e){const t=Hk.get(e);if(t)return UD.debug("use cached audio resource: ",e),t;try{n=(await fN((()=>$A.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new Jw(Xw.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Wh(((t,n)=>{const i=new FileReader;i.onload=e=>{e.target?t(e.target.result):n(new Jw(Xw.READ_LOCAL_AUDIO_FILE_ERROR))},i.onerror=()=>{n(new Jw(Xw.READ_LOCAL_AUDIO_FILE_ERROR))},i.readAsArrayBuffer(e)}));n=await t}const i=await function(e){const t=mL();return new Wh(((n,i)=>{t.decodeAudioData(e,(e=>{n(e)}),(e=>{i(new Jw(Xw.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(n);return"string"==typeof e&&t&&Hk.set(e,i),i}(r,n)}catch(e){return a.onError(e),e.throw(UD)}const d=new Yk(r),l=new Wk(c,d,i?kP(i):{},s);return UD.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(UD.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw UD.debug("Invalid appType"),new dP(Xw.INVALID_PARAMS,"invalid app type",e);nD("APP_TYPE",Math.floor(e))},setLogLevel:function(e){UD.setLogLevel(e)},enableLogUpload:function(){iD("USE_NEW_LOG")?nD("UPLOAD_LOG",!0):UD.enableLogUpload()},disableLogUpload:function(){iD("USE_NEW_LOG")?nD("UPLOAD_LOG",!1):UD.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new Q3},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=cP.reportApiInvoke(null,{tag:EO.TRACER,name:_O.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Gk||e instanceof eU)){const e=new dP(Xw.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof Gk?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:i,maxVolumeLevel:o,result:t};UD.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),n.onSuccess(s),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=cP.reportApiInvoke(null,{tag:EO.TRACER,name:_O.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof MM||e instanceof $M)){const e=new dP(Xw.INVALID_TRACK,"the parameter is not a video track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof MM?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,(mw()||_w())&&(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,n,i){let r,o=0,s=null;return new Wh(((a,c)=>{function d(){o>i&&r&&(r(),a(o));const t=n.getContext("2d");if(!t){const e=new dP(Xw.UNEXPECTED_ERROR,"can not get canvas 2d context.");return UD.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,n.width,n.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=SL((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw n.onError(e),e}T4===sw.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:i,result:d};return UD.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),n.onSuccess(l),d},setArea:p3,audioElementPlayCenter:FL,resumeAudioContext:function(){return FL.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){b8.processExternalMediaAEC(e)},registerExtensions:function(e){const t=iD("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Di(t).call(t,e.name)&&t.push(e.name);const n=e;n.__registered__=!0,n.logger.hookLog=UD.extLog,n.reporter.hookApiInvoke=cP.extApiInvoke,n.parameters&&Object.keys(n.parameters).forEach((e=>{n.parameters[e]=iD(e)}))})),M7("PLUGIN_INFO",t)},ChannelMediaRelayError:rx,ChannelMediaRelayEvent:nx,ChannelMediaRelayState:ix,RemoteStreamFallbackType:GP,RemoteStreamType:BP,ConnectionDisconnectedReason:gO,AudienceLatencyLevelType:fO,AREAS:dx,preload:async function(e,t,n,i){return U4(e,t,n,i)},startLastmileProbeTest:async function(e,t,n,i){let r={state:"unavailable"};await U4(e,t,n,i);const o=await V4({appId:e,cname:t,token:n||e,uid:i,cloudProxyServer:"disabled"});if(!o)return r;await F4(o);const s=S8({mode:"rtc",codec:"vp8"});let a;try{a=await s.join(e,t,n,i,{networkQualityProbe:!0})}catch(e){return r}const c=new M4,d=c.createMuteAudioTrack(),l=await VM({mediaStreamTrack:d});await s.publish([l]);const[u,h,p]=await new Wh(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e([!0,null,"audio"])}),5e3);s.on("user-published",(async(t,i)=>{t.uid===a&&(clearTimeout(n),e([!1,t,i]))}))}));if(u||!h)return await s.unpublish([l]),await s.leave(),l.close(),c.close(),r;await s.subscribe(h,p),await new Wh(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e(null)}),5e3)}));const _=s.getRTCStats(),E=s.getLocalAudioStats(),m=_.RTT,f=E.sendJitterMs,g=E.currentPacketLossRate;return r={state:"complete",rtt:m,packetLossRate:g,jitter:f,networkQuality:((e,t,n)=>{let i=1;if(n>0){let e=Math.log(100*n)/Math.log(2)+1;e=Math.min(5,Math.max(0,e)),i=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*i+.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,g)},await s.unsubscribe(h),await s.unpublish([l]),await s.leave(),l.close(),c.close(),await F4(o),r}});Object.defineProperties(U7,{onAudioAutoplayFailed:{get:()=>ML.onAudioAutoplayFailed,set:e=>{ML.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>ML.onAutoplayFailed,set:e=>{ML.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>U7._onSecurityPolicyViolation,set(e){U7._onSecurityPolicyViolation=e,O8(e)}},__CLIENT_LIST__:{get:()=>iD("SHOW_GLOBAL_CLIENT_LIST")?YU:[]}}),LL.on(tL.CAMERA_DEVICE_CHANGED,(e=>{UD.info("camera device changed",JSON.stringify(e)),U7.onCameraChanged&&U7.onCameraChanged(e),U7.safeEmit(Ox.CAMERA_CHANGED,e)})),LL.on(tL.RECORDING_DEVICE_CHANGED,(e=>{UD.info("microphone device changed",JSON.stringify(e)),U7.onMicrophoneChanged&&U7.onMicrophoneChanged(e),U7.safeEmit(Ox.MICROPHONE_CHANGED,e)})),LL.on(tL.PLAYOUT_DEVICE_CHANGED,(e=>{UD.debug("playout device changed",JSON.stringify(e)),U7.onPlaybackDeviceChanged&&U7.onPlaybackDeviceChanged(e),U7.safeEmit(Ox.PLAYBACK_DEVICE_CHANGED,e)})),FL.onAutoplayFailed=()=>{UD.info("detect audio element autoplay failed"),ML.onAudioAutoplayFailed&&ML.onAudioAutoplayFailed()},EL.on("autoplay-failed",(()=>{UD.info("detect webaudio autoplay failed"),ML.onAudioAutoplayFailed&&ML.onAudioAutoplayFailed(),U7.safeEmit(Ox.AUTOPLAY_FAILED)})),EL.on(vP.STATE_CHANGE,((e,t)=>{UD.info("audio context state changed: ".concat(t," => ").concat(e)),U7.onAudioContextStateChanged&&U7.onAudioContextStateChanged(e,t),U7.safeEmit(Ox.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),PO.on(AO.NETWORK_STATE_CHANGE,((e,t)=>{UD.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=U7);export{U7 as default};
