UNPKG

agora-rtc-sdk-ng

Version:
7 lines • 1.08 MB
/**
 * AgoraWebSDK_N-v4.24.9-0-g2319458dd Copyright AgoraInc.
 */

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTC=t()}(this,(function(){"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n=function(e){try{return!!e()}catch(e){return!0}},r=!n((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),o=r,s=Function.prototype,a=s.call,c=o&&s.bind.bind(a,a),d=o?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math===Math&&e},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||u("object"==typeof t&&t)||function(){return this}()||Function("return this")(),p=r,_=Function.prototype,E=_.apply,f=_.call,m="object"==typeof Reflect&&Reflect.apply||(p?f.bind(E):function(){return f.apply(E,arguments)}),S=d,g=S({}.toString),T=S("".slice),R=function(e){return T(g(e),8,-1)},v=R,C=d,I=function(e){if("Function"===v(e))return C(e)},y="object"==typeof document&&document.all,A=void 0===y&&void 0!==y?function(e){return"function"==typeof e||e===y}:function(e){return"function"==typeof e},b={},O=!n((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),w=r,N=Function.prototype.call,D=w?N.bind(N):function(){return N.apply(N,arguments)},P={},L={}.propertyIsEnumerable,k=Object.getOwnPropertyDescriptor,M=k&&!L.call({1:2},1);P.f=M?function(e){var t=k(this,e);return!!t&&t.enumerable}:L;var U,V,x=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},F=n,B=R,j=Object,G=d("".split),W=F((function(){return!j("z").propertyIsEnumerable(0)}))?function(e){return"String"===B(e)?G(e,""):j(e)}:j,H=function(e){return null==e},K=H,Y=TypeError,q=function(e){if(K(e))throw new Y("Can't call method on "+e);return e},J=W,z=q,X=function(e){return J(z(e))},Q=A,$=function(e){return"object"==typeof e?null!==e:Q(e)},Z={},ee=Z,te=h,ie=A,ne=function(e){return ie(e)?e:void 0},re=function(e,t){return arguments.length<2?ne(ee[e])||ne(te[e]):ee[e]&&ee[e][t]||te[e]&&te[e][t]},oe=h.navigator,se=oe&&oe.userAgent,ae=se?String(se):"",ce=h,de=ae,le=ce.process,ue=ce.Deno,he=le&&le.versions||ue&&ue.version,pe=he&&he.v8;pe&&(V=(U=pe.split("."))[0]>0&&U[0]<4?1:+(U[0]+U[1])),!V&&de&&(!(U=de.match(/Edge\/(\d+)/))||U[1]>=74)&&(U=de.match(/Chrome\/(\d+)/))&&(V=+U[1]);var _e=V,Ee=_e,fe=n,me=h.String,Se=!!Object.getOwnPropertySymbols&&!fe((function(){var e=Symbol("symbol detection");return!me(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ee&&Ee<41})),ge=Se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Te=re,Re=A,ve=l,Ce=Object,Ie=ge?function(e){return"symbol"==typeof e}:function(e){var t=Te("Symbol");return Re(t)&&ve(t.prototype,Ce(e))},ye=String,Ae=function(e){try{return ye(e)}catch(e){return"Object"}},be=A,Oe=Ae,we=TypeError,Ne=function(e){if(be(e))return e;throw new we(Oe(e)+" is not a function")},De=Ne,Pe=H,Le=function(e,t){var i=e[t];return Pe(i)?void 0:De(i)},ke=D,Me=A,Ue=$,Ve=TypeError,xe={exports:{}},Fe=h,Be=Object.defineProperty,je=h,Ge=function(e,t){try{Be(Fe,e,{value:t,configurable:!0,writable:!0})}catch(i){Fe[e]=t}return t},We="__core-js_shared__",He=xe.exports=je[We]||Ge(We,{});(He.versions||(He.versions=[])).push({version:"3.49.0",mode:"pure",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Ke=xe.exports,Ye=Ke,qe=function(e,t){return Ye[e]||(Ye[e]=t||{})},Je=q,ze=Object,Xe=function(e){return ze(Je(e))},Qe=Xe,$e=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return $e(Qe(e),t)},et=d,tt=0,it=Math.random(),nt=et(1.1.toString),rt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+nt(++tt+it,36)},ot=qe,st=Ze,at=rt,ct=Se,dt=ge,lt=h.Symbol,ut=ot("wks"),ht=dt?lt.for||lt:lt&&lt.withoutSetter||at,pt=function(e){return st(ut,e)||(ut[e]=ct&&st(lt,e)?lt[e]:ht("Symbol."+e)),ut[e]},_t=D,Et=$,ft=Ie,mt=Le,St=function(e,t){var i,n;if("string"===t&&Me(i=e.toString)&&!Ue(n=ke(i,e)))return n;if(Me(i=e.valueOf)&&!Ue(n=ke(i,e)))return n;if("string"!==t&&Me(i=e.toString)&&!Ue(n=ke(i,e)))return n;throw new Ve("Can't convert object to primitive value")},gt=TypeError,Tt=pt("toPrimitive"),Rt=function(e,t){if(!Et(e)||ft(e))return e;var i,n=mt(e,Tt);if(n){if(void 0===t&&(t="default"),i=_t(n,e,t),!Et(i)||ft(i))return i;throw new gt("Can't convert object to primitive value")}return void 0===t&&(t="number"),St(e,t)},vt=Ie,Ct=function(e){var t=Rt(e,"string");return vt(t)?t:t+""},It=$,yt=h.document,At=It(yt)&&It(yt.createElement),bt=function(e){return At?yt.createElement(e):{}},Ot=bt,wt=!O&&!n((function(){return 7!==Object.defineProperty(Ot("div"),"a",{get:function(){return 7}}).a})),Nt=O,Dt=D,Pt=P,Lt=x,kt=X,Mt=Ct,Ut=Ze,Vt=wt,xt=Object.getOwnPropertyDescriptor;b.f=Nt?xt:function(e,t){if(e=kt(e),t=Mt(t),Vt)try{return xt(e,t)}catch(e){}if(Ut(e,t))return Lt(!Dt(Pt.f,e,t),e[t])};var Ft=n,Bt=A,jt=/#|\.prototype\./,Gt=function(e,t){var i=Ht[Wt(e)];return i===Yt||i!==Kt&&(Bt(t)?Ft(t):!!t)},Wt=Gt.normalize=function(e){return String(e).replace(jt,".").toLowerCase()},Ht=Gt.data={},Kt=Gt.NATIVE="N",Yt=Gt.POLYFILL="P",qt=Gt,Jt=Ne,zt=r,Xt=I(I.bind),Qt=function(e,t){return Jt(e),void 0===t?e:zt?Xt(e,t):function(){return e.apply(t,arguments)}},$t={},Zt=O&&n((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),ei=$,ti=String,ii=TypeError,ni=function(e){if(ei(e))return e;throw new ii(ti(e)+" is not an object")},ri=O,oi=wt,si=Zt,ai=ni,ci=Ct,di=TypeError,li=Object.defineProperty,ui=Object.getOwnPropertyDescriptor,hi="enumerable",pi="configurable",_i="writable";$t.f=ri?si?function(e,t,i){if(ai(e),t=ci(t),ai(i),"function"==typeof e&&"prototype"===t&&"value"in i&&_i in i&&!i[_i]){var n=ui(e,t);n&&n[_i]&&(e[t]=i.value,i={configurable:pi in i?i[pi]:n[pi],enumerable:hi in i?i[hi]:n[hi],writable:!1})}return li(e,t,i)}:li:function(e,t,i){if(ai(e),t=ci(t),ai(i),oi)try{return li(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new di("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ei=$t,fi=x,mi=O?function(e,t,i){return Ei.f(e,t,fi(1,i))}:function(e,t,i){return e[t]=i,e},Si=h,gi=m,Ti=I,Ri=A,vi=b.f,Ci=qt,Ii=Z,yi=Qt,Ai=mi,bi=Ze,Oi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return gi(e,this,arguments)};return t.prototype=e.prototype,t},wi=function(e,t){var i,n,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?Si:p?Si[u]:Si[u]&&Si[u].prototype,f=h?Ii:Ii[u]||Ai(Ii,u,{})[u],m=f.prototype;for(o in t)n=!(i=Ci(h?o:u+(p?".":"#")+o,e.forced))&&E&&bi(E,o),a=f[o],n&&(c=e.dontCallGetSet?(l=vi(E,o))&&l.value:E[o]),s=n&&c?c:t[o],(i||_||typeof a!=typeof s)&&(d=e.bind&&n?yi(s,Si):e.wrap&&n?Oi(s):_&&Ri(s)?Ti(s):s,(e.sham||s&&s.sham||a&&a.sham)&&Ai(d,"sham",!0),Ai(f,o,d),_&&(bi(Ii,r=u+"Prototype")||Ai(Ii,r,{}),Ai(Ii[r],o,s),e.real&&m&&(i||!m[o])&&Ai(m,o,s)))},Ni=Math.ceil,Di=Math.floor,Pi=Math.trunc||function(e){var t=+e;return(t>0?Di:Ni)(t)},Li=Pi,ki=function(e){var t=+e;return t!=t||0===t?0:Li(t)},Mi=ki,Ui=Math.max,Vi=Math.min,xi=function(e,t){var i=Mi(e);return i<0?Ui(i+t,0):Vi(i,t)},Fi=ki,Bi=Math.min,ji=function(e){var t=Fi(e);return t>0?Bi(t,9007199254740991):0},Gi=function(e){return ji(e.length)},Wi=X,Hi=xi,Ki=Gi,Yi=function(e){return function(t,i,n){var r=Wi(t),o=Ki(r);if(0===o)return!e&&-1;var s,a=Hi(n,o);if(e&&i!=i){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((e||a in r)&&r[a]===i)return e||a||0;return!e&&-1}},qi={includes:Yi(!0),indexOf:Yi(!1)},Ji=wi,zi=qi.includes,Xi=n,Qi=Xi((function(){return!Array(1).includes()})),$i=Xi((function(){return[,1].includes(void 0,1)}));Ji({target:"Array",proto:!0,forced:Qi||$i},{includes:function(e){return zi(this,e,arguments.length>1?arguments[1]:void 0)}});var Zi=h,en=Z,tn=function(e,t){var i=en[e+"Prototype"],n=i&&i[t];if(n)return n;var r=Zi[e],o=r&&r.prototype;return o&&o[t]},nn=tn("Array","includes"),rn=$,on=R,sn=pt("match"),an=function(e){var t;return rn(e)&&(void 0!==(t=e[sn])?!!t:"RegExp"===on(e))},cn=an,dn=TypeError,ln={};ln[pt("toStringTag")]="z";var un="[object z]"===String(ln),hn=un,pn=A,_n=R,En=pt("toStringTag"),fn=Object,mn="Arguments"===_n(function(){return arguments}()),Sn=hn?_n:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=fn(e),En))?i:mn?_n(t):"Object"===(n=_n(t))&&pn(t.callee)?"Arguments":n},gn=Sn,Tn=String,Rn=function(e){if("Symbol"===gn(e))throw new TypeError("Cannot convert a Symbol value to a string");return Tn(e)},vn=pt("match"),Cn=wi,In=function(e){if(cn(e))throw new dn("The method doesn't accept regular expressions");return e},yn=q,An=Rn,bn=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[vn]=!1,"/./"[e](t)}catch(e){}}return!1},On=d("".indexOf);Cn({target:"String",proto:!0,forced:!bn("includes")},{includes:function(e){return!!~On(An(yn(this)),An(In(e)),arguments.length>1?arguments[1]:void 0)}});var wn=tn("String","includes"),Nn=l,Dn=nn,Pn=wn,Ln=Array.prototype,kn=String.prototype,Mn=function(e){var t=e.includes;return e===Ln||Nn(Ln,e)&&t===Ln.includes?Dn:"string"==typeof e||e===kn||Nn(kn,e)&&t===kn.includes?Pn:t},Un=i(Mn),Vn=Ne,xn=Xe,Fn=W,Bn=Gi,jn=TypeError,Gn="Reduce of empty array with no initial value",Wn=function(e){return function(t,i,n,r){var o=xn(t),s=Fn(o),a=Bn(o);if(Vn(i),0===a&&n<2)throw new jn(Gn);var c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw new jn(Gn)}for(;e?c>=0:a>c;c+=d)c in s&&(r=i(r,s[c],c,o));return r}},Hn={left:Wn(!1),right:Wn(!0)},Kn=n,Yn=function(e,t){var i=[][e];return!!i&&Kn((function(){i.call(null,t||function(){return 1},1)}))},qn=h,Jn=ae,zn=R,Xn=function(e){return Jn.slice(0,e.length)===e},Qn=Xn("Bun/")?"BUN":Xn("Cloudflare-Workers")?"CLOUDFLARE":Xn("Deno/")?"DENO":Xn("Node.js/")?"NODE":qn.Bun&&"string"==typeof Bun.version?"BUN":qn.Deno&&"object"==typeof Deno.version?"DENO":"process"===zn(qn.process)?"NODE":qn.window&&qn.document?"BROWSER":"REST",$n="NODE"===Qn,Zn=Hn.left;wi({target:"Array",proto:!0,forced:!$n&&_e>79&&_e<83||!Yn("reduce")},{reduce:function(e){var t=arguments.length;return Zn(this,e,t,t>1?arguments[1]:void 0)}});var er=tn("Array","reduce"),tr=l,ir=er,nr=Array.prototype,rr=function(e){var t=e.reduce;return e===nr||tr(nr,e)&&t===nr.reduce?ir:t},or=rr,sr=i(or),ar=R,cr=Array.isArray||function(e){return"Array"===ar(e)},dr=wi,lr=cr,ur=d([].reverse),hr=[1,2];dr({target:"Array",proto:!0,forced:String(hr)===String(hr.reverse())},{reverse:function(){return lr(this)&&(this.length=this.length),ur(this)}});var pr=tn("Array","reverse"),_r=l,Er=pr,fr=Array.prototype,mr=function(e){var t=e.reverse;return e===fr||_r(fr,e)&&t===fr.reverse?Er:t},Sr=mr,gr=i(Sr),Tr=rt,Rr=qe("keys"),vr=function(e){return Rr[e]||(Rr[e]=Tr(e))},Cr=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ir=Ze,yr=A,Ar=Xe,br=Cr,Or=vr("IE_PROTO"),wr=Object,Nr=wr.prototype,Dr=br?wr.getPrototypeOf:function(e){var t=Ar(e);if(Ir(t,Or))return t[Or];var i=t.constructor;return yr(i)&&t instanceof i?i.prototype:t instanceof wr?Nr:null},Pr=d,Lr=Ne,kr=$,Mr=function(e){return kr(e)||null===e},Ur=String,Vr=TypeError,xr=function(e,t,i){try{return Pr(Lr(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},Fr=$,Br=q,jr=function(e){if(Mr(e))return e;throw new Vr("Can't set "+Ur(e)+" as a prototype")},Gr=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=xr(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return Br(i),jr(n),Fr(i)?(t?e(i,n):i.__proto__=n,i):i}}():void 0),Wr={},Hr={},Kr=Ze,Yr=X,qr=qi.indexOf,Jr=Hr,zr=d([].push),Xr=function(e,t){var i,n=Yr(e),r=0,o=[];for(i in n)!Kr(Jr,i)&&Kr(n,i)&&zr(o,i);for(;t.length>r;)Kr(n,i=t[r++])&&(~qr(o,i)||zr(o,i));return o},Qr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],$r=Xr,Zr=Qr.concat("length","prototype");Wr.f=Object.getOwnPropertyNames||function(e){return $r(e,Zr)};var eo={};eo.f=Object.getOwnPropertySymbols;var to=re,io=Wr,no=eo,ro=ni,oo=d([].concat),so=to("Reflect","ownKeys")||function(e){var t=io.f(ro(e)),i=no.f;return i?oo(t,i(e)):t},ao=Ze,co=so,lo=b,uo=$t,ho={},po=Xr,_o=Qr,Eo=Object.keys||function(e){return po(e,_o)},fo=O,mo=Zt,So=$t,go=ni,To=X,Ro=Eo;ho.f=fo&&!mo?Object.defineProperties:function(e,t){go(e);for(var i,n=To(t),r=Ro(t),o=r.length,s=0;o>s;)So.f(e,i=r[s++],n[i]);return e};var vo,Co=re("document","documentElement"),Io=ni,yo=ho,Ao=Qr,bo=Hr,Oo=Co,wo=bt,No="prototype",Do="script",Po=vr("IE_PROTO"),Lo=function(){},ko=function(e){return"<"+Do+">"+e+"</"+Do+">"},Mo=function(e){e.write(ko("")),e.close();var t=e.parentWindow.Object;return e=null,t},Uo=function(){try{vo=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;Uo="undefined"!=typeof document?document.domain&&vo?Mo(vo):(t=wo("iframe"),i="java"+Do+":",t.style.display="none",Oo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(ko("document.F=Object")),e.close(),e.F):Mo(vo);for(var n=Ao.length;n--;)delete Uo[No][Ao[n]];return Uo()};bo[Po]=!0;var Vo=Object.create||function(e,t){var i;return null!==e?(Lo[No]=Io(e),i=new Lo,Lo[No]=null,i[Po]=e):i=Uo(),void 0===t?i:yo.f(i,t)},xo=$,Fo=mi,Bo=Error,jo=d("".replace),Go=String(new Bo("zxcasd").stack),Wo=/\n\s*at [^:]*:[^\n]*/,Ho=Wo.test(Go),Ko=x,Yo=!n((function(){var e=new Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Ko(1,7)),7!==e.stack)})),qo=mi,Jo=function(e,t){if(Ho&&"string"==typeof e&&!Bo.prepareStackTrace)for(;t--;)e=jo(e,Wo,"");return e},zo=Yo,Xo=Error.captureStackTrace,Qo={},$o=Qo,Zo=pt("iterator"),es=Array.prototype,ts=function(e){return void 0!==e&&($o.Array===e||es[Zo]===e)},is=Sn,ns=Le,rs=H,os=Qo,ss=pt("iterator"),as=function(e){if(!rs(e))return ns(e,ss)||ns(e,"@@iterator")||os[is(e)]},cs=D,ds=Ne,ls=ni,us=Ae,hs=as,ps=TypeError,_s=function(e,t){var i=arguments.length<2?hs(e):t;if(ds(i))return ls(cs(i,e));throw new ps(us(e)+" is not iterable")},Es=D,fs=ni,ms=Le,Ss=function(e,t,i){var n,r;fs(e);try{if(!(n=ms(e,"return"))){if("throw"===t)throw i;return i}n=Es(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return fs(n),i},gs=Qt,Ts=D,Rs=ni,vs=Ae,Cs=ts,Is=Gi,ys=l,As=_s,bs=as,Os=Ss,ws=TypeError,Ns=function(e,t){this.stopped=e,this.result=t},Ds=Ns.prototype,Ps=function(e,t,i){var n,r,o,s,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=gs(t,l),f=function(e){var t=n;return n=void 0,t&&Os(t,"normal"),new Ns(!0,e)},m=function(e){return u?(Rs(e),_?E(e[0],e[1],f):E(e[0],e[1])):_?E(e,f):E(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=bs(e)))throw new ws(vs(e)+" is not iterable");if(Cs(r)){for(o=0,s=Is(e);s>o;o++)if((a=m(e[o]))&&ys(Ds,a))return a;return new Ns(!1)}n=As(e,r)}for(c=h?e.next:n.next;!(d=Ts(c,n)).done;){var S=d.value;try{a=m(S)}catch(e){if(!n)throw e;Os(n,"throw",e)}if("object"==typeof a&&a&&ys(Ds,a))return a}return new Ns(!1)},Ls=Rn,ks=wi,Ms=l,Us=Dr,Vs=Gr,xs=function(e,t,i){for(var n=co(t),r=uo.f,o=lo.f,s=0;s<n.length;s++){var a=n[s];ao(e,a)||i&&ao(i,a)||r(e,a,o(t,a))}},Fs=Vo,Bs=mi,js=x,Gs=function(e,t){xo(t)&&"cause"in t&&Fo(e,"cause",t.cause)},Ws=function(e,t,i,n){zo&&(Xo?Xo(e,t):qo(e,"stack",Jo(i,n)))},Hs=Ps,Ks=function(e,t){return void 0===e?arguments.length<2?"":t:Ls(e)},Ys=pt("toStringTag"),qs=Error,Js=[].push,zs=function(e,t){var i,n=Ms(Xs,this);Vs?i=Vs(new qs,n?Us(this):Xs):(i=n?this:Fs(Xs),Bs(i,Ys,"Error")),void 0!==t&&Bs(i,"message",Ks(t)),Ws(i,zs,i.stack,1),arguments.length>2&&Gs(i,arguments[2]);var r=[];return Hs(e,Js,{that:r}),Bs(i,"errors",r),i};Vs?Vs(zs,qs):xs(zs,qs,{name:!0});var Xs=zs.prototype=Fs(qs.prototype,{constructor:js(1,zs),message:js(1,""),name:js(1,"AggregateError")});ks({global:!0,constructor:!0,arity:2},{AggregateError:zs});var Qs,$s,Zs,ea=A,ta=h.WeakMap,ia=ea(ta)&&/native code/.test(String(ta)),na=h,ra=$,oa=mi,sa=Ze,aa=Ke,ca=vr,da=Hr,la="Object already initialized",ua=na.TypeError,ha=na.WeakMap;if(ia||aa.state){var pa=aa.state||(aa.state=new ha);pa.get=pa.get,pa.has=pa.has,pa.set=pa.set,Qs=function(e,t){if(pa.has(e))throw new ua(la);return t.facade=e,pa.set(e,t),t},$s=function(e){return pa.get(e)||{}},Zs=function(e){return pa.has(e)}}else{var _a=ca("state");da[_a]=!0,Qs=function(e,t){if(sa(e,_a))throw new ua(la);return t.facade=e,oa(e,_a,t),t},$s=function(e){return sa(e,_a)?e[_a]:{}},Zs=function(e){return sa(e,_a)}}var Ea,fa,ma,Sa={set:Qs,get:$s,has:Zs,enforce:function(e){return Zs(e)?$s(e):Qs(e,{})},getterFor:function(e){return function(t){var i;if(!ra(t)||(i=$s(t)).type!==e)throw new ua("Incompatible receiver, "+e+" required");return i}}},ga=O,Ta=Ze,Ra=Function.prototype,va=ga&&Object.getOwnPropertyDescriptor,Ca=Ta(Ra,"name"),Ia={EXISTS:Ca,PROPER:Ca&&"something"===function(){}.name,CONFIGURABLE:Ca&&(!ga||ga&&va(Ra,"name").configurable)},ya=mi,Aa=function(e,t,i,n){return n&&n.enumerable?e[t]=i:ya(e,t,i),e},ba=n,Oa=A,wa=$,Na=Vo,Da=Dr,Pa=Aa,La=pt("iterator"),ka=!1;[].keys&&("next"in(ma=[].keys())?(fa=Da(Da(ma)))!==Object.prototype&&(Ea=fa):ka=!0);var Ma=!wa(Ea)||ba((function(){var e={};return Ea[La].call(e)!==e}));Oa((Ea=Ma?{}:Na(Ea))[La])||Pa(Ea,La,(function(){return this}));var Ua={IteratorPrototype:Ea,BUGGY_SAFARI_ITERATORS:ka},Va=Sn,xa=un?{}.toString:function(){return"[object "+Va(this)+"]"},Fa=un,Ba=$t.f,ja=mi,Ga=Ze,Wa=xa,Ha=pt("toStringTag"),Ka=function(e,t,i,n){var r=i?e:e&&e.prototype;r&&(Ga(r,Ha)||Ba(r,Ha,{configurable:!0,value:t}),n&&!Fa&&ja(r,"toString",Wa))},Ya=Ua.IteratorPrototype,qa=Vo,Ja=x,za=Ka,Xa=Qo,Qa=function(){return this},$a=function(e,t,i,n){var r=t+" Iterator";return e.prototype=qa(Ya,{next:Ja(+!n,i)}),za(e,r,!1,!0),Xa[r]=Qa,e},Za=wi,ec=D,tc=Ia,ic=$a,nc=Dr,rc=Ka,oc=Aa,sc=Qo,ac=Ua,cc=tc.PROPER,dc=ac.BUGGY_SAFARI_ITERATORS,lc=pt("iterator"),uc="keys",hc="values",pc="entries",_c=function(){return this},Ec=function(e,t,i,n,r,o,s){ic(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!dc&&e&&e in p)return p[e];switch(e){case uc:case hc:case pc:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[lc]||p["@@iterator"]||r&&p[r],E=!dc&&_||l(r),f="Array"===t&&p.entries||_;if(f&&(a=nc(f.call(new e)))!==Object.prototype&&a.next&&(rc(a,u,!0,!0),sc[u]=_c),cc&&r===hc&&_&&_.name!==hc&&(h=!0,E=function(){return ec(_,this)}),r)if(c={values:l(hc),keys:o?E:l(uc),entries:l(pc)},s)for(d in c)(dc||h||!(d in p))&&oc(p,d,c[d]);else Za({target:t,proto:!0,forced:dc||h},c);return s&&p[lc]!==E&&oc(p,lc,E,{name:r}),sc[t]=E,c},fc=function(e,t){return{value:e,done:t}},mc=X,Sc=Qo,gc=Sa;$t.f;var Tc=Ec,Rc=fc,vc="Array Iterator",Cc=gc.set,Ic=gc.getterFor(vc);Tc(Array,"Array",(function(e,t){Cc(this,{type:vc,target:mc(e),index:0,kind:t})}),(function(){var e=Ic(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Rc(void 0,!0);switch(e.kind){case"keys":return Rc(i,!1);case"values":return Rc(t[i],!1)}return Rc([i,t[i]],!1)}),"values"),Sc.Arguments=Sc.Array;var yc=$t,Ac=function(e,t,i){return yc.f(e,t,i)},bc=re,Oc=Ac,wc=O,Nc=pt("species"),Dc=l,Pc=TypeError,Lc=function(e,t){if(Dc(t,e))return e;throw new Pc("Incorrect invocation")},kc=A,Mc=Ke,Uc=d(Function.toString);kc(Mc.inspectSource)||(Mc.inspectSource=function(e){return Uc(e)});var Vc=Mc.inspectSource,xc=d,Fc=n,Bc=A,jc=Sn,Gc=Vc,Wc=function(){},Hc=re("Reflect","construct"),Kc=/^\s*(?:class|function)\b/,Yc=xc(Kc.exec),qc=!Kc.test(Wc),Jc=function(e){if(!Bc(e))return!1;try{return Hc(Wc,[],e),!0}catch(e){return!1}},zc=function(e){if(!Bc(e))return!1;switch(jc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qc||!!Yc(Kc,Gc(e))}catch(e){return!0}};zc.sham=!0;var Xc,Qc,$c,Zc,ed=!Hc||Fc((function(){var e;return Jc(Jc.call)||!Jc(Object)||!Jc((function(){e=!0}))||e}))?zc:Jc,td=ed,id=Ae,nd=TypeError,rd=ni,od=function(e){if(td(e))return e;throw new nd(id(e)+" is not a constructor")},sd=H,ad=pt("species"),cd=function(e,t){var i,n=rd(e).constructor;return void 0===n||sd(i=rd(n)[ad])?t:od(i)},dd=d([].slice),ld=TypeError,ud=function(e,t){if(e<t)throw new ld("Not enough arguments");return e},hd=ae,pd=/ipad|iphone|ipod/i.test(hd)&&/applewebkit/i.test(hd),_d=h,Ed=m,fd=Qt,md=A,Sd=Ze,gd=n,Td=Co,Rd=dd,vd=bt,Cd=ud,Id=pd,yd=$n,Ad=_d.setImmediate,bd=_d.clearImmediate,Od=_d.process,wd=_d.Dispatch,Nd=_d.Function,Dd=_d.MessageChannel,Pd=_d.String,Ld=0,kd={},Md="onreadystatechange";gd((function(){Xc=_d.location}));var Ud=function(e){if(Sd(kd,e)){var t=kd[e];delete kd[e],t()}},Vd=function(e){return function(){Ud(e)}},xd=function(e){Ud(e.data)},Fd=function(e){_d.postMessage(Pd(e),Xc.protocol+"//"+Xc.host)};Ad&&bd||(Ad=function(e){Cd(arguments.length,1);var t=md(e)?e:Nd(e),i=Rd(arguments,1);return kd[++Ld]=function(){Ed(t,void 0,i)},Qc(Ld),Ld},bd=function(e){delete kd[e]},yd?Qc=function(e){Od.nextTick(Vd(e))}:wd&&wd.now?Qc=function(e){wd.now(Vd(e))}:Dd&&!Id?(Zc=($c=new Dd).port2,$c.port1.onmessage=xd,Qc=fd(Zc.postMessage,Zc)):_d.addEventListener&&md(_d.postMessage)&&!_d.importScripts&&Xc&&"file:"!==Xc.protocol&&!gd(Fd)?(Qc=Fd,_d.addEventListener("message",xd,!1)):Qc=Md in vd("script")?function(e){Td.appendChild(vd("script"))[Md]=function(){Td.removeChild(this),Ud(e)}}:function(e){setTimeout(Vd(e),0)});var Bd={set:Ad,clear:bd},jd=h,Gd=O,Wd=Object.getOwnPropertyDescriptor,Hd=function(e){if(!Gd)return jd[e];var t=Wd(jd,e);return t&&t.value},Kd=function(){this.head=null,this.tail=null};Kd.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var Yd,qd,Jd,zd,Xd,Qd=Kd,$d=/ipad|iphone|ipod/i.test(ae)&&"undefined"!=typeof Pebble,Zd=/web0s(?!.*chrome)/i.test(ae),el=h,tl=Hd,il=Qt,nl=Bd.set,rl=Qd,ol=pd,sl=$d,al=Zd,cl=$n,dl=el.MutationObserver||el.WebKitMutationObserver,ll=el.document,ul=el.process,hl=el.Promise,pl=tl("queueMicrotask");if(!pl){var _l=new rl,El=function(){var e,t;for(cl&&(e=ul.domain)&&e.exit();t=_l.get();)try{t()}catch(e){throw _l.head&&Yd(),e}e&&e.enter()};ol||cl||al||!dl||!ll?!sl&&hl&&hl.resolve?((zd=hl.resolve(void 0)).constructor=hl,Xd=il(zd.then,zd),Yd=function(){Xd(El)}):cl?Yd=function(){ul.nextTick(El)}:(nl=il(nl,el),Yd=function(){nl(El)}):(qd=!0,Jd=ll.createTextNode(""),new dl(El).observe(Jd,{characterData:!0}),Yd=function(){Jd.data=qd=!qd}),pl=function(e){_l.head||Yd(),_l.add(e)}}var fl=pl,ml=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},Sl=h.Promise,gl=h,Tl=Sl,Rl=A,vl=qt,Cl=Vc,Il=pt,yl=Qn,Al=_e,bl=Tl&&Tl.prototype,Ol=Il("species"),wl=!1,Nl=Rl(gl.PromiseRejectionEvent),Dl=vl("Promise",(function(){var e=Cl(Tl),t=e!==String(Tl);if(!t&&66===Al)return!0;if(!bl.catch||!bl.finally)return!0;if(!Al||Al<51||!/native code/.test(e)){var i=new Tl((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Ol]=n,!(wl=i.then((function(){}))instanceof n))return!0}return!(t||"BROWSER"!==yl&&"DENO"!==yl||Nl)})),Pl={CONSTRUCTOR:Dl,REJECTION_EVENT:Nl,SUBCLASSING:wl},Ll={},kl=Ne,Ml=TypeError,Ul=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw new Ml("Bad Promise constructor");t=e,i=n})),this.resolve=kl(t),this.reject=kl(i)};Ll.f=function(e){return new Ul(e)};var Vl,xl,Fl,Bl=wi,jl=$n,Gl=h,Wl=Z,Hl=D,Kl=Aa,Yl=Ka,ql=function(e){var t=bc(e);wc&&t&&!t[Nc]&&Oc(t,Nc,{configurable:!0,get:function(){return this}})},Jl=Ne,zl=A,Xl=$,Ql=Lc,$l=cd,Zl=Bd.set,eu=fl,tu=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(e){}},iu=ml,nu=Qd,ru=Sa,ou=Sl,su=Pl,au=Ll,cu="Promise",du=su.CONSTRUCTOR,lu=su.REJECTION_EVENT,uu=ru.getterFor(cu),hu=ru.set,pu=ou&&ou.prototype,_u=ou,Eu=pu,fu=Gl.TypeError,mu=Gl.document,Su=Gl.process,gu=au.f,Tu=gu,Ru=!!(mu&&mu.createEvent&&Gl.dispatchEvent),vu="unhandledrejection",Cu=function(e){var t;return!(!Xl(e)||!zl(t=e.then))&&t},Iu=function(e,t){var i,n,r,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(2===t.rejection&&wu(t),t.rejection=1),!0===a?i=o:(l&&l.enter(),i=a(o),l&&(l.exit(),r=!0)),i===e.promise?d(new fu("Promise-chain cycle")):(n=Cu(i))?Hl(n,i,c,d):c(i)):d(o)}catch(e){l&&!r&&l.exit(),d(e)}},yu=function(e,t){e.notified||(e.notified=!0,eu((function(){for(var i,n=e.reactions;i=n.get();)Iu(i,e);e.notified=!1,t&&!e.rejection&&bu(e)})))},Au=function(e,t,i){var n,r;Ru?((n=mu.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),Gl.dispatchEvent(n)):n={promise:t,reason:i},!lu&&(r=Gl["on"+e])?r(n):e===vu&&tu("Unhandled promise rejection",i)},bu=function(e){Hl(Zl,Gl,(function(){var t,i=e.facade,n=e.value;if(Ou(e)&&(t=iu((function(){jl?Su.emit("unhandledRejection",n,i):Au(vu,i,n)})),e.rejection=jl||Ou(e)?2:1,t.error))throw t.value}))},Ou=function(e){return 1!==e.rejection&&!e.parent},wu=function(e){Hl(Zl,Gl,(function(){var t=e.facade;jl?Su.emit("rejectionHandled",t):Au("rejectionhandled",t,e.value)}))},Nu=function(e,t,i){return function(n){e(t,n,i)}},Du=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,yu(e,!0))},Pu=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new fu("Promise can't be resolved itself");var n=Cu(t);n?eu((function(){var i={done:!1};try{Hl(n,t,Nu(Pu,i,e),Nu(Du,i,e))}catch(t){Du(i,t,e)}})):(e.value=t,e.state=1,yu(e,!1))}catch(t){Du({done:!1},t,e)}}};du&&(Eu=(_u=function(e){Ql(this,Eu),Jl(e),Hl(Vl,this);var t=uu(this);try{e(Nu(Pu,t),Nu(Du,t))}catch(e){Du(t,e)}}).prototype,(Vl=function(e){hu(this,{type:cu,done:!1,notified:!1,parent:!1,reactions:new nu,rejection:!1,state:0,value:null})}).prototype=Kl(Eu,"then",(function(e,t){var i=uu(this),n=gu($l(this,_u));return i.parent=!0,n.ok=!zl(e)||e,n.fail=zl(t)&&t,n.domain=jl?Su.domain:void 0,0===i.state?i.reactions.add(n):eu((function(){Iu(n,i)})),n.promise})),xl=function(){var e=new Vl,t=uu(e);this.promise=e,this.resolve=Nu(Pu,t),this.reject=Nu(Du,t)},au.f=gu=function(e){return e===_u||e===Fl?new xl(e):Tu(e)}),Bl({global:!0,constructor:!0,wrap:!0,forced:du},{Promise:_u}),Fl=Wl.Promise,Yl(_u,cu,!1,!0),ql(cu);var Lu=pt("iterator"),ku=!1;try{var Mu=0,Uu={next:function(){return{done:!!Mu++}},return:function(){ku=!0}};Uu[Lu]=function(){return this},Array.from(Uu,(function(){throw 2}))}catch(e){}var Vu=function(e,t){try{if(!t&&!ku)return!1}catch(e){return!1}var i=!1;try{var n={};n[Lu]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(e){}return i},xu=Sl,Fu=Pl.CONSTRUCTOR||!Vu((function(e){xu.all(e).then(void 0,(function(){}))})),Bu=D,ju=Ne,Gu=Ll,Wu=ml,Hu=Ps;wi({target:"Promise",stat:!0,forced:Fu},{all:function(e){var t=this,i=Gu.f(t),n=i.resolve,r=i.reject,o=Wu((function(){var i=ju(t.resolve),o=[],s=0,a=1;Hu(e,(function(e){var c=s++,d=!1;a++,Bu(i,t,e).then((function(e){d||(d=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ku=wi,Yu=Pl.CONSTRUCTOR;Sl&&Sl.prototype,Ku({target:"Promise",proto:!0,forced:Yu,real:!0},{catch:function(e){return this.then(void 0,e)}});var qu=D,Ju=Ne,zu=Ll,Xu=ml,Qu=Ps;wi({target:"Promise",stat:!0,forced:Fu},{race:function(e){var t=this,i=zu.f(t),n=i.reject,r=Xu((function(){var r=Ju(t.resolve);Qu(e,(function(e){qu(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var $u=Ll;wi({target:"Promise",stat:!0,forced:Pl.CONSTRUCTOR},{reject:function(e){var t=$u.f(this);return(0,t.reject)(e),t.promise}});var Zu=ni,eh=$,th=Ll,ih=function(e,t){if(Zu(e),eh(t)&&t.constructor===e)return t;var i=th.f(e);return(0,i.resolve)(t),i.promise},nh=wi,rh=Sl,oh=Pl.CONSTRUCTOR,sh=ih,ah=re("Promise"),ch=!oh;nh({target:"Promise",stat:!0,forced:true},{resolve:function(e){return sh(ch&&this===ah?rh:this,e)}});var dh=D,lh=Ne,uh=Ll,hh=ml,ph=Ps;wi({target:"Promise",stat:!0,forced:Fu},{allSettled:function(e){var t=this,i=uh.f(t),n=i.resolve,r=i.reject,o=hh((function(){var i=lh(t.resolve),r=[],o=0,s=1;ph(e,(function(e){var a=o++,c=!1;s++,dh(i,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||n(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||n(r))}))})),--s||n(r)}));return o.error&&r(o.value),i.promise}});var _h=D,Eh=Ne,fh=re,mh=Ll,Sh=ml,gh=Ps,Th="No one promise resolved";wi({target:"Promise",stat:!0,forced:Fu},{any:function(e){var t=this,i=fh("AggregateError"),n=mh.f(t),r=n.resolve,o=n.reject,s=Sh((function(){var n=Eh(t.resolve),s=[],a=0,c=1,d=!1;gh(e,(function(e){var l=a++,u=!1;c++,_h(n,t,e).then((function(e){u||d||(d=!0,r(e))}),(function(e){u||d||(u=!0,s[l]=e,--c||o(new i(s,Th)))}))})),--c||o(new i(s,Th))}));return s.error&&o(s.value),n.promise}});var Rh=wi,vh=m,Ch=dd,Ih=Ll,yh=Ne,Ah=ml,bh=h.Promise,Oh=!1;Rh({target:"Promise",stat:!0,forced:!bh||!bh.try||Ah((function(){bh.try((function(e){Oh=8===e}),8)})).error||!Oh},{try:function(e){var t=arguments.length>1?Ch(arguments,1):[],i=Ih.f(this),n=Ah((function(){return vh(yh(e),void 0,t)}));return(n.error?i.reject:i.resolve)(n.value),i.promise}});var wh=Ll;wi({target:"Promise",stat:!0},{withResolvers:function(){var e=wh.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var Nh=wi,Dh=Sl,Ph=n,Lh=re,kh=A,Mh=cd,Uh=ih,Vh=Dh&&Dh.prototype;Nh({target:"Promise",proto:!0,real:!0,forced:!!Dh&&Ph((function(){Vh.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Mh(this,Lh("Promise")),i=kh(e);return this.then(i?function(i){return Uh(t,e()).then((function(){return i}))}:e,i?function(i){return Uh(t,e()).then((function(){throw i}))}:e)}});var xh=d,Fh=ki,Bh=Rn,jh=q,Gh=xh("".charAt),Wh=xh("".charCodeAt),Hh=xh("".slice),Kh=function(e){return function(t,i){var n,r,o=Bh(jh(t)),s=Fh(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=Wh(o,s))<55296||n>56319||s+1===a||(r=Wh(o,s+1))<56320||r>57343?e?Gh(o,s):n:e?Hh(o,s,s+2):r-56320+(n-55296<<10)+65536}},Yh={codeAt:Kh(!1),charAt:Kh(!0)},qh=Yh.charAt,Jh=Rn,zh=Sa,Xh=Ec,Qh=fc,$h="String Iterator",Zh=zh.set,ep=zh.getterFor($h);Xh(String,"String",(function(e){Zh(this,{type:$h,string:Jh(e),index:0})}),(function(){var e,t=ep(this),i=t.string,n=t.index;return n>=i.length?Qh(void 0,!0):(e=qh(i,n),t.index+=e.length,Qh(e,!1))}));var tp=Z.Promise,ip={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},np=h,rp=Ka,op=Qo;for(var sp in ip)rp(np[sp],sp),op[sp]=op.Array;var ap=tp,cp=i(ap),dp=tn("Array","values"),lp=Sn,up=Ze,hp=l,pp=dp,_p=Array.prototype,Ep={DOMTokenList:!0,NodeList:!0},fp=function(e){var t=e.values;return e===_p||hp(_p,e)&&t===_p.values||up(Ep,lp(e))?pp:t},mp=i(fp),Sp=Ae,gp=TypeError,Tp=dd,Rp=Math.floor,vp=function(e,t){var i=e.length;if(i<8)for(var n,r,o=1;o<i;){for(r=o,n=e[o];r&&t(e[r-1],n)>0;)e[r]=e[--r];r!==o++&&(e[r]=n)}else for(var s=Rp(i/2),a=vp(Tp(e,0,s),t),c=vp(Tp(e,s),t),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)e[u+h]=u<d&&h<l?t(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return e},Cp=vp,Ip=ae.match(/firefox\/(\d+)/i),yp=!!Ip&&+Ip[1],Ap=/MSIE|Trident/.test(ae),bp=ae.match(/AppleWebKit\/(\d+)\./),Op=!!bp&&+bp[1],wp=wi,Np=d,Dp=Ne,Pp=Xe,Lp=Gi,kp=function(e,t){if(!delete e[t])throw new gp("Cannot delete property "+Sp(t)+" of "+Sp(e))},Mp=Rn,Up=n,Vp=Cp,xp=Yn,Fp=yp,Bp=Ap,jp=_e,Gp=Op,Wp=[],Hp=Np(Wp.sort),Kp=Np(Wp.push),Yp=Up((function(){Wp.sort(void 0)})),qp=Up((function(){Wp.sort(null)})),Jp=xp("sort"),zp=!Up((function(){if(jp)return jp<70;if(!(Fp&&Fp>3)){if(Bp)return!0;if(Gp)return Gp<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)Wp.push({k:t+n,v:i})}for(Wp.sort((function(e,t){return t.v-e.v})),n=0;n<Wp.length;n++)t=Wp[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));wp({target:"Array",proto:!0,forced:Yp||!qp||!Jp||!zp},{sort:function(e){void 0!==e&&Dp(e);var t=Pp(this);if(zp)return void 0===e?Hp(t):Hp(t,e);var i,n,r=[],o=Lp(t);for(n=0;n<o;n++)n in t&&Kp(r,t[n]);for(Vp(r,function(e){return function(t,i){if(void 0===i)return-1;if(void 0===t)return 1;if(void 0!==e)return+e(t,i)||0;var n=Mp(t),r=Mp(i);return n===r?0:n>r?1:-1}}(e)),i=Lp(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)kp(t,n++);return t}});var Xp=tn("Array","sort"),Qp=l,$p=Xp,Zp=Array.prototype,e_=function(e){var t=e.sort;return e===Zp||Qp(Zp,e)&&t===Zp.sort?$p:t},t_=i(e_),i_=wi,n_=d,r_=xi,o_=RangeError,s_=String.fromCharCode,a_=String.fromCodePoint,c_=n_([].join);i_({target:"String",stat:!0,arity:1,forced:!!a_&&1!==a_.length},{fromCodePoint:function(e){for(var t,i=[],n=arguments.length,r=0;n>r;){if(r_(t=+arguments[r],1114111)!==t)throw new o_(t+" is not a valid code point");i[r++]=t<65536?s_(t):s_(55296+((t-=65536)>>10),t%1024+56320)}return c_(i,"")}});var d_=n,l_=pt("iterator"),u_=!d_((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),n="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),n+=i+e})),i.delete("a",2),i.delete("b",void 0),!e.toJSON||!i.has("a",1)||i.has("a",2)||!i.has("a",void 0)||i.has("b")||!t.size&&true||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[l_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==n||"x"!==new URL("https://x",void 0).host})),h_=Aa,p_=wi,__=h,E_=Hd,f_=re,m_=D,S_=d,g_=O,T_=u_,R_=Aa,v_=Ac,C_=function(e,t,i){for(var n in t)i&&i.unsafe&&e[n]?e[n]=t[n]:h_(e,n,t[n],i);return e},I_=Ka,y_=$a,A_=Sa,b_=Lc,O_=A,w_=Ze,N_=Qt,D_=Sn,P_=ni,L_=$,k_=Rn,M_=Vo,U_=x,V_=_s,x_=as,F_=fc,B_=ud,j_=Cp,G_=pt("iterator"),W_="URLSearchParams",H_=W_+"Iterator",K_=A_.set,Y_=A_.getterFor(W_),q_=A_.getterFor(H_),J_=E_("fetch"),z_=E_("Request"),X_=E_("Headers"),Q_=z_&&z_.prototype,$_=X_&&X_.prototype,Z_=__.TypeError,eE=__.encodeURIComponent,tE=String.fromCharCode,iE=f_("String","fromCodePoint"),nE=parseInt,rE=S_("".charAt),oE=S_([].join),sE=S_([].push),aE=S_("".replace),cE=S_([].shift),dE=S_([].splice),lE=S_("".split),uE=S_("".slice),hE=S_(/./.exec),pE=/\+/g,_E=/^[0-9a-f]+$/i,EE=function(e,t){var i=uE(e,t,t+2);return hE(_E,i)?nE(i,16):NaN},fE=function(e){for(var t=0,i=128;i>0&&0!=(e&i);i>>=1)t++;return t},mE=function(e){var t=null,i=e.length;switch(i){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return null===t||t>1114111||t>=55296&&t<=57343||t<(i>3?65536:i>2?2048:i>1?128:0)?null:t},SE=function(e){for(var t=(e=aE(e,pE," ")).length,i="",n=0;n<t;){var r=rE(e,n);if("%"===r){if("%"===rE(e,n+1)||n+3>t){i+="%",n++;continue}var o=EE(e,n+1);if(o!=o){i+=r,n++;continue}n+=2;var s=fE(o);if(0===s)r=tE(o);else{if(1===s||s>4){i+="�",n++;continue}for(var a=[o],c=1;c<s&&!(++n+3>t||"%"!==rE(e,n));){var d=EE(e,n+1);if(d!=d||d>191||d<128)break;if(1===c){if(224===o&&d<160)break;if(237===o&&d>159)break;if(240===o&&d<144)break;if(244===o&&d>143)break}sE(a,d),n+=2,c++}if(a.length!==s){i+="�";continue}var l=mE(a);if(null===l){for(var u=0;u<s;u++)i+="�";n++;continue}r=iE(l)}}i+=r,n++}return i},gE=/[!'()~]|%20/g,TE={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},RE=function(e){return TE[e]},vE=function(e){return aE(eE(e),gE,RE)},CE=y_((function(e,t){K_(this,{type:H_,target:Y_(e).entries,index:0,kind:t})}),W_,(function(){var e=q_(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,F_(void 0,!0);var n=t[i];switch(e.kind){case"keys":return F_(n.key,!1);case"values":return F_(n.value,!1)}return F_([n.key,n.value],!1)}),!0),IE=function(e){this.entries=[],this.url=null,void 0!==e&&(L_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rE(e,0)?uE(e,1):e:k_(e)))};IE.prototype={type:W_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,n,r,o,s,a,c=this.entries,d=x_(e);if(d)for(i=(t=V_(e,d)).next;!(n=m_(i,t)).done;){if(o=(r=V_(P_(n.value))).next,(s=m_(o,r)).done||(a=m_(o,r)).done||!m_(o,r).done)throw new Z_("Expected sequence with length 2");sE(c,{key:k_(s.value),value:k_(a.value)})}else for(var l in e)w_(e,l)&&sE(c,{key:l,value:k_(e[l])})},parseQuery:function(e){if(e)for(var t,i,n=this.entries,r=lE(e,"&"),o=0;o<r.length;)(t=r[o++]).length&&(i=lE(t,"="),sE(n,{key:SE(cE(i)),value:SE(oE(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],sE(i,vE(e.key)+"="+vE(e.value));return oE(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yE=function(){b_(this,AE);var e=K_(this,new IE(arguments.length>0?arguments[0]:void 0));g_||(this.size=e.entries.length)},AE=yE.prototype;if(C_(AE,{append:function(e,t){var i=Y_(this);B_(arguments.length,2),sE(i.entries,{key:k_(e),value:k_(t)}),g_||this.size++,i.updateURL()},delete:function(e){for(var t=Y_(this),i=B_(arguments.length,1),n=t.entries,r=k_(e),o=i<2?void 0:arguments[1],s=void 0===o?o:k_(o),a=0;a<n.length;){var c=n[a];c.key!==r||void 0!==s&&c.value!==s?a++:dE(n,a,1)}g_||(this.size=n.length),t.updateURL()},get:function(e){var t=Y_(this).entries;B_(arguments.length,1);for(var i=k_(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){var t=Y_(this).entries;B_(arguments.length,1);for(var i=k_(e),n=[],r=0;r<t.length;r++)t[r].key===i&&sE(n,t[r].value);return n},has:function(e){for(var t=Y_(this).entries,i=B_(arguments.length,1),n=k_(e),r=i<2?void 0:arguments[1],o=void 0===r?r:k_(r),s=0;s<t.length;){var a=t[s++];if(a.key===n&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=Y_(this);B_(arguments.length,2);for(var n,r=i.entries,o=!1,s=k_(e),a=k_(t),c=0;c<r.length;c++)(n=r[c]).key===s&&(o?dE(r,c--,1):(o=!0,n.value=a));o||sE(r,{key:s,value:a}),g_||(this.size=r.length),i.updateURL()},sort:function(){var e=Y_(this);j_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Y_(this).entries,n=N_(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new CE(this,"keys")},values:function(){return new CE(this,"values")},entries:function(){return new CE(this,"entries")}},{enumerable:!0}),R_(AE,G_,AE.entries,{name:"entries"}),R_(AE,"toString",(function(){return Y_(this).serialize()}),{enumerable:!0}),g_&&v_(AE,"size",{get:function(){return Y_(this).entries.length},configurable:!0,enumerable:!0}),I_(yE,W_),p_({global:!0,constructor:!0,forced:!T_},{URLSearchParams:yE}),!T_&&O_(X_)){var bE=S_($_.has),OE=S_($_.set),wE=function(e){if(L_(e)){var t,i=e.body;if(D_(i)===W_)return t=e.headers?new X_(e.headers):new X_,bE(t,"content-type")||OE(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),M_(e,{body:U_(0,k_(i)),headers:U_(0,t)})}return e};if(O_(J_)&&p_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return J_(e,arguments.length>1?wE(arguments[1]):{})}}),O_(z_)){var NE=function(e){return b_(this,Q_),new z_(e,arguments.length>1?wE(arguments[1]):{})};Q_.constructor=NE,NE.prototype=Q_,p_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:NE})}}var DE,PE={URLSearchParams:yE,getState:Y_},LE=Z.URLSearchParams,kE=O,ME=d,UE=D,VE=n,xE=Eo,FE=eo,BE=P,jE=Xe,GE=W,WE=Object.assign,HE=Object.defineProperty,KE=ME([].concat),YE=!WE||VE((function(){if(kE&&1!==WE({b:1},WE(HE({},"a",{enumerable:!0,get:function(){HE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach((function(e){t[e]=e})),7!==WE({},e)[i]||xE(WE({},t)).join("")!==n}))?function(e,t){for(var i=jE(e),n=arguments.length,r=1,o=FE.f,s=BE.f;n>r;)for(var a,c=GE(arguments[r++]),d=o?KE(xE(c),o(c)):xE(c),l=d.length,u=0;l>u;)a=d[u++],kE&&!UE(s,c,a)||(i[a]=c[a]);return i}:WE,qE=ni,JE=Ss,zE=O,XE=$t,QE=x,$E=function(e,t,i){zE?XE.f(e,t,QE(0,i)):e[t]=i},ZE=O,ef=cr,tf=TypeError,nf=Object.getOwnPropertyDescriptor,rf=ZE&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}()?function(e,t){if(ef(e)&&!nf(e,"length").writable)throw new tf("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},of=Qt,sf=D,af=Xe,cf=function(e,t,i,n){try{return n?t(qE(i)[0],i[1]):t(i)}catch(t){JE(e,"throw",t)}},df=ts,lf=ed,uf=Gi,hf=$E,pf=rf,_f=_s,Ef=as,ff=Ss,mf=Array,Sf=function(e){var t=lf(this),i=arguments.length,n=i>1?arguments[1]:void 0,r=void 0!==n;r&&(n=of(n,i>2?arguments[2]:void 0));var o,s,a,c,d,l,u=af(e),h=Ef(u),p=0;if(!h||this===mf&&df(h))for(o=uf(u),s=t?new this(o):mf(o);o>p;p++)l=r?n(u[p],p):u[p],hf(s,p,l);else for(s=t?new this:[],d=(c=_f(u,h)).next;!(a=sf(d,c)).done;p++){l=r?cf(c,n,[a.value,p],!0):a.value;try{hf(s,p,l)}catch(e){ff(c,"throw",e)}}return pf(s,p),s},gf=d,Tf=2147483647,Rf=/[^\0-\u007E]/,vf=/[.\u3002\uFF0E\uFF61]/g,Cf="Overflow: input needs wider integers to process",If=RangeError,yf=gf(vf.exec),Af=Math.floor,bf=String.fromCharCode,Of=gf("".charCodeAt),wf=gf([].join),Nf=gf([].push),Df=gf("".replace),Pf=gf("".split),Lf=gf("".toLowerCase),kf=function(e){return e+22+75*(e<26)},Mf=function(e,t,i){var n=0;for(e=i?Af(e/700):e>>1,e+=Af(e/t);e>455;)e=Af(e/35),n+=36;return Af(n+36*e/(e+38))},Uf=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=Of(e,i++);if(r>=55296&&r<=56319&&i<n){var o=Of(e,i++);56320==(64512&o)?Nf(t,((1023&r)<<10)+(1023&o)+65536):(Nf(t,r),i--)}else Nf(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&Nf(t,bf(n));var c=t.length,d=c;for(c&&Nf(t,"-");d<r;){var l=Tf;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<l&&(l=n);var u=d+1;if(l-o>Af((Tf-s)/u))throw new If(Cf);for(s+=(l-o)*u,o=l,i=0;i<e.length;i++){if((n=e[i])<o&&++s>Tf)throw new If(Cf);if(n===o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,f=36-_;Nf(t,bf(kf(_+E%f))),h=Af(E/f),p+=36}Nf(t,bf(kf(h))),a=Mf(s,u,d===c),s=0,d++}}s++,o++}return wf(t,"")},Vf=wi,xf=O,Ff=u_,Bf=h,jf=Qt,Gf=d,Wf=Aa,Hf=Ac,Kf=Lc,Yf=Ze,qf=YE,Jf=Sf,zf=dd,Xf=Yh.codeAt,Qf=function(e){var t,i,n=[],r=Pf(Df(Lf(e),vf,"."),".");for(t=0;t<r.length;t++)i=r[t],Nf(n,yf(Rf,i)?"xn--"+Uf(i):i);return wf(n,".")},$f=Rn,Zf=Ka,em=ud,tm=PE,im=Sa,nm=im.set,rm=im.getterFor("URL"),om=tm.URLSearchParams,sm=tm.getState,am=Bf.URL,cm=Bf.TypeError,dm=Bf.encodeURIComponent,lm=Bf.parseInt,um=Math.floor,hm=Math.pow,pm=Gf("".charAt),_m=Gf(/./.exec),Em=Gf([].join),fm=Gf(1.1.toString),mm=Gf([].pop),Sm=Gf([].push),gm=Gf("".replace),Tm=Gf([].shift),Rm=Gf("".split),vm=Gf("".slice),Cm=Gf("".toLowerCase),Im=Gf([].unshift),ym="Invalid scheme",Am="Invalid host",bm="Invalid port",Om=/[a-z]/i,wm=/[\d+\-.a-z]/i,Nm=/\d/,Dm=/^0x/i,Pm=/^[0-7]+$/,Lm=/^\d+$/,km=/^[\da-f]+$/i,Mm=/[\0\t\n\r #%/:<>?@[\\\]^|]/,Um=/[\0\t\n\r #/:<>?@[\\\]^|]/,Vm=/^[\u0000-\u0020]+/,xm=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Fm=/[\t\n\r]/g,Bm=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)Im(t,e%256),e=um(e/256);return Em(t,".")}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i?n:t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=fm(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},jm={},Gm=qf({},jm,{" ":1,'"':1,"#":1,"<":1,">":1}),Wm=qf({},Gm,{"'":1}),Hm=qf({},jm,{" ":1,'"':1,"<":1,">":1,"`":1}),Km=qf({},Hm,{"#":1,"?":1,"{":1,"}":1,"^":1}),Ym=qf({},Km,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),qm=function(e,t){var i=Xf(e,0);return i>=32&&i<127&&!Yf(t,e)?e:"'"===e&&Yf(t,e)?"%27":dm(e)},Jm={ftp:21,file:null,http:80,https:443,ws:80,wss:443},zm=function(e,t){var i;return 2===e.length&&_m(Om,pm(e,0))&&(":"===(i=pm(e,1))||!t&&"|"===i)},Xm=function(e){var t;return e.length>1&&zm(vm(e,0,2))&&(2===e.length||"/"===(t=pm(e,2))||"\\"===t||"?"===t||"#"===t)},Qm=function(e){return"."===e||"%2e"===Cm(e)},$m={},Zm={},eS={},tS={},iS={},nS={},rS={},oS={},sS={},aS={},cS={},dS={},lS={},uS={},hS={},pS={},_S={},ES={},fS={},mS={},SS={},gS=function(e,t,i){var n,r,o,s=$f(e);if(t){if(r=this.parse(s))throw new cm(r);this.searchParams=null}else{if(void 0!==i&&(n=new gS(i,!0)),r=this.parse(s,null,n))throw new cm(r);(o=sm(new om)).bindURL(this),this.searchParams=o}};gS.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,d=t||$m,l=0,u="",h=!1,p=!1,_=!1;for(e=$f(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,Vm,""),e=gm(e,xm,"$1")),e=gm(e,Fm,""),n=Jf(e);l<=n.length;){switch(r=n[l],d){case $m:if(!r||!_m(Om,r)){if(t)return ym;d=eS;continue}u+=Cm(r),d=Zm;break;case Zm:if(r&&_m(wm,r))u+=Cm(r);else{if(":"!==r){if(t)return ym;u="",d=eS,l=0;continue}if(t&&(c.isSpecial()!==Yf(Jm,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&""===c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&Jm[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?d=uS:c.isSpecial()&&i&&i.scheme===c.scheme?d=tS:c.isSpecial()?d=oS:"/"===n[l+1]?(d=iS,l++):(c.cannotBeABaseURL=!0,Sm(c.path,""),d=fS)}break;case eS:if(!i||i.cannotBeABaseURL&&"#"!==r)return ym;if(i.cannotBeABaseURL&&"#"===r){c.scheme=i.scheme,c.path=zf(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=SS;break}d="file"===i.scheme?uS:nS;continue;case tS:if("/"!==r||"/"!==n[l+1]){d=nS;continue}d=sS,l++;break;case iS:if("/"===r){d=aS;break}d=ES;continue;case nS:if(c.scheme=i.scheme,r===DE)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=zf(i.path),c.query=i.query;else if("/"===r||"\\"===r&&c.isSpecial())d=rS;else if("?"===r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=zf(i.path),c.query="",d=mS;else{if("#"!==r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=zf(i.path),c.path.length&&c.path.length--,d=ES;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=zf(i.path),c.query=i.query,c.fragment="",d=SS}break;case rS:if(!c.isSpecial()||"/"!==r&&"\\"!==r){if("/"!==r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=ES;continue}d=aS}else d=sS;break;case oS:if(d=sS,"/"!==r||"/"!==n[l+1])continue;l++;break;case sS:if("/"!==r&&"\\"!==r){d=aS;continue}break;case aS:if("@"===r){h&&(u="%40"+u),h=!0,o=Jf(u);for(var E=0;E<o.length;E++){var f=o[E];if(":"!==f||_){var m=qm(f,Ym);_?c.password+=m:c.username+=m}else _=!0}u=""}else if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(h&&""===u)return"Invalid authority";l-=Jf(u).length+1,u="",d=cS}else u+=r;break;case cS:case dS:if(t&&"file"===c.scheme){d=pS;continue}if(":"!==r||p){if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(c.isSpecial()&&""===u)return Am;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",d=_S,t)return;continue}"["===r?p=!0:"]"===r&&(p=!1),u+=r}else{if(""===u)return Am;if(t===dS)return;if(s=c.parseHost(u))return s;u="",d=lS}break;case lS:if(!_m(Nm,r)){if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()||t){if(""!==u){var S=lm(u,10);if(S>65535)return bm;c.port=c.isSpecial()&&S===Jm[c.scheme]?null:S,u=""}if(t)return;d=_S;continue}return bm}u+=r;break;case uS:if(c.scheme="file",c.host="","/"===r||"\\"===r)d=hS;else{if(!i||"file"!==i.scheme){d=ES;continue}switch(r){case DE:c.host=i.host,c.path=zf(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=zf(i.path),c.query="",d=mS;break;case"#":c.host=i.host,c.path=zf(i.path),c.query=i.query,c.fragment="",d=SS;break;default:c.host=i.host,Xm(Em(zf(n,l),""))||(c.path=zf(i.path),c.shortenPath()),d=ES;continue}}break;case hS:if("/"===r||"\\"===r){d=pS;break}i&&"file"===i.scheme&&(c.host=i.host,!Xm(Em(zf(n,l),""))&&zm(i.path[0],!0)&&Sm(c.path,i.path[0])),d=ES;continue;case pS:if(r===DE||"/"===r||"\\"===r||"?"===r||"#"===r){if(!t&&zm(u))d=ES;else if(""===u){if(c.host="",t)return;d=_S}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",d=_S}continue}u+=r;break;case _S:if(c.isSpecial()){if(d=ES,"/"!==r&&"\\"!==r)continue}else if(t||"?"!==r)if(t||"#"!==r){if(r!==DE&&(d=ES,"/"!==r))continue}else c.fragment="",d=SS;else c.query="",d=mS;break;case ES:if(r===DE||"/"===r||"\\"===r&&c.isSpecial()||!t&&("?"===r||"#"===r)){if(".."===(a=Cm(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===r||"\\"===r&&c.isSpecial()||Sm(c.path,"")):Qm(u)?"/"===r||"\\"===r&&c.isSpecial()||Sm(c.path,""):("file"===c.scheme&&!c.path.length&&zm(u)&&(null!==c.host&&""!==c.host&&(c.host=""),u=pm(u,0)+":"),Sm(c.path,u)),u="","file"===c.scheme&&(r===DE||"?"===r||"#"===r))for(;c.path.length>1&&""===c.path[0];)Tm(c.path);"?"===r?(c.query="",d=mS):"#"===r&&(c.fragment="",d=SS)}else u+=qm(r,Km);break;case fS:"?"===r?(c.query="",d=mS):"#"===r?(c.fragment="",d=SS):r!==DE&&(c.path[0]+=qm(r,jm));break;case mS:t||"#"!==r?r!==DE&&(c.query+=qm(r,c.isSpecial()?Wm:Gm)):(c.fragment="",d=SS);break;case SS:r!==DE&&(c.fragment+=qm(r,Hm))}l++}},parseHost:function(e){var t,i,n;if("["===pm(e,0)){if("]"!==pm(e,e.length-1))return Am;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return pm(e,u)};if(":"===h()){if(":"!==pm(e,1))return;u+=2,l=++d}for(;h();){if(8===d)return;if(":"!==h()){for(t=i=0;i<4&&_m(km,h());)t=16*t+lm(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!("."===h()&&n<4))return;u++}if(!_m(Nm,h()))return;for(;_m(Nm,h());){if(o=lm(h(),10),null===r)r=o;else{if(0===r)return;r=10*r+o}if(r>255)return;u++}c[d]=256*c[d]+r,2!=++n&&4!==n||d++}if(4!==n)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[d++]=t}else{if(null!==l)return;u++,l=++d}}if(null!==l)for(s=d-l,d=7;0!==d&&s>0;)a=c[d],c[d--]=c[l+s-1],c[l+--s]=a;else if(8!==d)return;return c}(vm(e,1,-1)),!t)return Am;this.host=t}else if(this.isSpecial()){if(e=Qf(e),_m(Mm,e))return Am;if(function(e){var t,i,n=Rm(e,".");if(""===n[n.length-1]){if(1===n.length)return!1;n.length--}return t=n[n.length-1],!!_m(Lm,t)||!!_m(Dm,t)&&(""===(i=vm(t,2))||!!_m(km,i))}(e)){if(t=function(e){var t,i,n,r,o,s,a,c=Rm(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return null;for(i=[],n=0;n<t;n++){if(""===(r=c[n]))return null;if(o=10,r.length>1&&"0"===pm(r,0)&&(o=_m(Dm,r)?16:8,r=vm(r,8===o?1:2)),""===r)s=0;else{if(!_m(10===o?Lm:8===o?Pm:km,r))return null;s=lm(r,o)}Sm(i,s)}for(n=0;n<t;n++)if(s=i[n],n===t-1){if(s>=hm(256,5-t))return null}else if(s>255)return null;for(a=mm(i),n=0;n<i.length;n++)a+=i[n]*hm(256,3-n);return a}(e),null===t)return Am;this.host=t}else this.host=e}else{if(_m(Um,e))return Am;for(t="",i=Jf(e),n=0;n<i.length;n++)t+=qm(i[n],jm);this.host=t}},cannotHaveUsernamePasswordPort:function(){return null===this.host||""===this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return Yf(Jm,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&zm(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,d=t+":";return null!==r?(d+="//",e.includesCredentials()&&(d+=i+(n?":"+n:"")+"@"),d+=Bm(r),null!==o&&(d+=":"+o)):"file"===t&&(d+="//"),null===r&&!e.cannotBeABaseURL&&s.length>1&&""===s[0]&&(d+="/."),d+=e.cannotBeABaseURL?s[0]:s.length?"/"+Em(s,"/"):"",null!==a&&(d+="?"+a),null!==c&&(d+="#"+c),d},setHref:function(e){var t=this.parse(e);if(t)throw new cm(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new TS(this.path[0]).origin}catch(e){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+Bm(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse($f(e)+":",$m)},getUsername:function(){return this.username},setUsername:function(e){var t=Jf($f(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=qm(t[i],Ym)}},getPassword:function(){return this.password},setPassword:function(e){var t=Jf($f(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=qm(t[i],Ym)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?Bm(e):Bm(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,cS)},getHostname:function(){var e=this.host;return null===e?"":Bm(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,dS)},getPort:function(){var e=this.port;return null===e?"":$f(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=$f(e))?this.port=null:this.parse(e,lS))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Em(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,_S))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=$f(e))?this.query=null:("?"===pm(e,0)&&(e=vm(e,1)),this.query="",this.parse(e,mS)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=$f(e))?("#"===pm(e,0)&&(e=vm(e,1)),this.fragment="",this.parse(e,SS)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var TS=function(e){var t=Kf(this,RS),i=em(arguments.length,1)>1?arguments[1]:void 0,n=nm(t,new gS(e,!1,i));xf||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},RS=TS.prototype,vS=function(e,t){return{get:function(){return rm(this)[e]()},set:t&&function(e){return rm(this)[t](e)},configurable:!0,enumerable:!0}};if(xf&&(Hf(RS,"href",vS("serialize","setHref")),Hf(RS,"origin",vS("getOrigin")),Hf(RS,"protocol",vS("getProtocol","setProtocol")),Hf(RS,"username",vS("getUsername","setUsername")),Hf(RS,"password",vS("getPassword","setPassword")),Hf(RS,"host",vS("getHost","setHost")),Hf(RS,"hostname",vS("getHostname","setHostname")),Hf(RS,"port",vS("getPort","setPort")),Hf(RS,"pathname",vS("getPathname","setPathname")),Hf(RS,"search",vS("getSearch","setSearch")),Hf(RS,"searchParams",vS("getSearchParams")),Hf(RS,"hash",vS("getHash","setHash"))),Wf(RS,"toJSON",(function(){return rm(this).serialize()}),{enumerable:!0}),Wf(RS,"toString",(function(){return rm(this).serialize()}),{enumerable:!0}),am){var CS=am.createObjectURL,IS=am.revokeObjectURL;CS&&Wf(TS,"createObjectURL",jf(CS,am)),IS&&Wf(TS,"revokeObjectURL",jf(IS,am))}Zf(TS,"URL"),Vf({global:!0,constructor:!0,forced:!Ff,sham:!xf},{URL:TS});var yS=wi,AS=n,bS=ud,OS=Rn,wS=u_,NS=re("URL"),DS=wS&&AS((function(){NS.canParse()})),PS=AS((function(){return 1!==NS.canParse.length}));yS({target:"URL",stat:!0,forced:!DS||PS},{canParse:function(e){var t=bS(arguments.length,1),i=OS(e),n=t<2||void 0===arguments[1]?void 0:OS(arguments[1]);try{return!!new NS(i,n)}catch(e){return!1}}});var LS=wi,kS=ud,MS=Rn,US=u_,VS=re("URL");LS({target:"URL",stat:!0,forced:!US},{parse:function(e){var t=kS(arguments.length,1),i=MS(e),n=t<2||void 0===arguments[1]?void 0:MS(arguments[1]);try{return new VS(i,n)}catch(e){return null}}});var xS=i(Z.URL);let FS=!0,BS=!0;function jS(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function GS(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function WS(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(FS=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function HS(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(BS=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function KS(){if("object"==typeof window){if(FS)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function YS(e,t){BS&&console.warn(e+" is deprecated, please use "+t+" instead.")}function qS(e){return"[object Object]"===Object.prototype.toString.call(e)}function JS(e){var t;return qS(e)?sr(t=Object.keys(e)).call(t,(function(t,i){const n=qS(e[i]),r=n?JS(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function zS(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?zS(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{zS(e,e.get(t),i)}))})))}function XS(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&zS(e,i,r)}))})),r}const QS=KS;function $S(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>{var i;return Un(i=e.label.toLowerCase()).call(i,t)}))));return!s&&i.length&&Un(t).call(t,"back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),QS("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return QS("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>cp.reject(o(e))))))}}}function ZS(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function eg(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else GS(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function tg(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ig(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),i=e[0],n=e[1],r=e[2];if(arguments.length>0&&"function"==typeof i)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof i))return t.apply(this,[]);const o=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const e=function(e){n(s(o(e)))};return t.apply(this,[e,i])}return new cp(((e,i)=>{t.apply(this,[function(t){e(s(o(t)))},i])})).then(n,r)}}function ng(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>XS(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}),GS(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>XS(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?cp.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():cp.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function rg(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function og(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return rg(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find((e=>e.track===t));if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),cp.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function sg(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function ag(e,t){GS(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var cg=Object.freeze({__proto__:null,fixNegotiationNeeded:ag,shimAddTrackRemoveTrack:og,shimAddTrackRemoveTrackWithNative:rg,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:tg,shimGetStats:ig,shimGetUserMedia:$S,shimMediaStream:ZS,shimOnTrack:eg,shimPeerConnection:sg,shimSenderReceiverGetStats:ng});function dg(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){YS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function lg(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 ug(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),r=e[0],o=e[1],s=e[2];return n.apply(this,[r||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(o,s)}}function hg(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):cp.resolve(new Map)}}function pg(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}),GS(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function _g(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){YS("removeStream","removeTrack"),this.getSenders().forEach((t=>{var i;t.track&&Un(i=e.getTracks()).call(i,t.track)&&this.removeTrack(t)}))})}function Eg(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function fg(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const t=n.sender,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function mg(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 Sg(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?cp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function gg(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?cp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Tg=Object.freeze({__proto__:null,shimAddTransceiver:fg,shimCreateAnswer:gg,shimCreateOffer:Sg,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,cp.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:mg,shimGetUserMedia:dg,shimOnTrack:lg,shimPeerConnection:ug,shimRTCDataChannel:Eg,shimReceiverGetStats:pg,shimRemoveStream:_g,shimSenderGetStats:hg});function Rg(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var i;this._localStreams||(this._localStreams=[]),Un(i=this._localStreams).call(i,e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{var t;this._localStreams?Un(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{Un(i).call(i,e.track)&&this.removeTrack(e)}))})}}function vg(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=[]),Un(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const i=new Event("addstream");i.stream=e,this.dispatchEvent(i)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Cg(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),cp.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),cp.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),cp.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),cp.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),cp.resolve()):n},t.addIceCandidate=a}function Ig(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(yg(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function yg(e){return e&&void 0!==e.video?Object.assign({},e,{video:JS(e.video)}):e}function Ag(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(YS("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function bg(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 Og(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function wg(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ng=Object.freeze({__proto__:null,shimAudioContext:wg,shimCallbacksAPI:Cg,shimConstraints:yg,shimCreateOfferLegacy:Og,shimGetUserMedia:Ig,shimLocalStreamsAPI:Rg,shimRTCIceServerUrls:Ag,shimRemoteStreamsAPI:vg,shimTrackEventTransceiver:bg}),Dg="\t\n\v\f\r                 \u2028\u2029\ufeff",Pg=q,Lg=Rn,kg=Dg,Mg=d("".replace),Ug=RegExp("^["+kg+"]+"),Vg=RegExp("(^|[^"+kg+"])["+kg+"]+$"),xg=function(e){return function(t){var i=Lg(Pg(t));return 1&e&&(i=Mg(i,Ug,"")),2&e&&(i=Mg(i,Vg,"$1")),i}},Fg={start:xg(1),end:xg(2),trim:xg(3)},Bg=Ia.PROPER,jg=n,Gg=Dg,Wg=Fg.trim;wi({target:"String",proto:!0,forced:function(e){return jg((function(){return!!Gg[e]()||"​…᠎"!=="​…᠎"[e]()||Bg&&Gg[e].name!==e}))}("trim")},{trim:function(){return Wg(this)}});var Hg=tn("String","trim"),Kg=l,Yg=Hg,qg=String.prototype,Jg=function(e){var t=e.trim;return"string"==typeof e||e===qg||Kg(qg,e)&&t===qg.trim?Yg:t},zg=i(Jg),Xg={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&void 0!==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 i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const o=n[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const n=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Xg);var Qg=Xg.exports,$g=i(Qg),Zg=e({__proto__:null,default:$g},[Qg]);function eT(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),n=$g.parseCandidate(e.candidate),r=Object.assign(i,n);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,GS(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function tT(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||GS(e,"icecandidate",(e=>{if(e.candidate){const t=$g.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function iT(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=$g.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=$g.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},o=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=$g.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=o(arguments[0],e);let s;s=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function nT(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},GS(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function rT(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function oT(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==zg(e).call(e))).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function sT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?cp.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),cp.resolve())})}function aT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var cT=Object.freeze({__proto__:null,removeExtmapAllowMixed:oT,shimAddIceCandidateNullOrEmpty:sT,shimConnectionState:rT,shimMaxMessageSize:iT,shimParameterlessSetLocalDescription:aT,shimRTCIceCandidate:eT,shimRTCIceCandidateRelayProtocol:tT,shimSendThrowTypeError:nT});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=KS,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const i=e.navigator;if(i.mozGetUserMedia)t.browser="firefox",t.version=jS(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=jS(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=jS(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:cT,extractVersion:jS,disableLog:WS,disableWarnings:HS,sdp:Zg};switch(n.browser){case"chrome":if(!cg||!sg||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=cg,sT(e,n),aT(e),$S(e,n),ZS(e),sg(e,n),eg(e),og(e,n),tg(e),ig(e),ng(e),ag(e,n),eT(e),tT(e),rT(e),iT(e,n),nT(e),oT(e,n);break;case"firefox":if(!Tg||!ug||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Tg,sT(e,n),aT(e),dg(e,n),ug(e,n),lg(e),_g(e),hg(e),pg(e),Eg(e),fg(e),mg(e),Sg(e),gg(e),eT(e),rT(e),iT(e,n),nT(e);break;case"safari":if(!Ng||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Ng,sT(e,n),aT(e),Ag(e),Og(e),Cg(e),Rg(e),vg(e),bg(e),Ig(e),wg(e),eT(e),tT(e),iT(e,n),nT(e),oT(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),wi({target:"Array",stat:!0},{isArray:cr});var dT=i(Z.Array.isArray);var lT=TypeError,uT=function(e){if(e>9007199254740991)throw new lT("Maximum allowed index exceeded");return e},hT=cr,pT=ed,_T=$,ET=pt("species"),fT=Array,mT=function(e){var t;return hT(e)&&(t=e.constructor,(pT(t)&&(t===fT||hT(t.prototype))||_T(t)&&null===(t=t[ET]))&&(t=void 0)),void 0===t?fT:t},ST=function(e,t){return new(mT(e))(0===t?0:t)},gT=n,TT=_e,RT=pt("species"),vT=function(e){return TT>=51||!gT((function(){var t=[];return(t.constructor={})[RT]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},CT=wi,IT=n,yT=cr,AT=$,bT=Xe,OT=Gi,wT=uT,NT=$E,DT=rf,PT=ST,LT=vT,kT=_e,MT=pt("isConcatSpreadable"),UT=kT>=51||!IT((function(){var e=[];return e[MT]=!1,e.concat()[0]!==e})),VT=function(e){if(!AT(e))return!1;var t=e[MT];return void 0!==t?!!t:yT(e)};CT({target:"Array",proto:!0,arity:1,forced:!UT||!LT("concat")},{concat:function(e){var t,i,n,r,o,s=bT(this),a=PT(s,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(VT(o=-1===t?s:arguments[t]))for(r=OT(o),wT(c+r),i=0;i<r;i++,c++)i in o&&NT(a,c,o[i]);else wT(c+1),NT(a,c++,o);return DT(a,c),a}});var xT={},FT=R,BT=X,jT=Wr.f,GT=dd,WT="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];xT.f=function(e){return WT&&"Window"===FT(e)?function(e){try{return jT(e)}catch(e){return GT(WT)}}(e):jT(BT(e))};var HT={},KT=pt;HT.f=KT;var YT=Z,qT=Ze,JT=HT,zT=$t.f,XT=function(e){var t=YT.Symbol||(YT.Symbol={});qT(t,e)||zT(t,e,{value:JT.f(e)})},QT=D,$T=re,ZT=pt,eR=Aa,tR=function(){var e=$T("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,n=ZT("toPrimitive");t&&!t[n]&&eR(t,n,(function(e){return QT(i,this)}),{arity:1})},iR=Qt,nR=W,rR=Xe,oR=Gi,sR=ST,aR=$E,cR=function(e){var t=1===e,i=2===e,n=3===e,r=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,d,l){for(var u,h,p=rR(c),_=nR(p),E=oR(_),f=iR(d,l),m=0,S=0,g=t?sR(c,E):i||s?sR(c,0):void 0;E>m;m++)if((a||m in _)&&(h=f(u=_[m],m,p),e))if(t)aR(g,m,h);else if(h)switch(e){case 3:return!0;case 5:return u;case 6:return m;case 2:aR(g,S++,u)}else switch(e){case 4:return!1;case 7:aR(g,S++,u)}return o?-1:n||r?r:g}},dR={forEach:cR(0),map:cR(1),filter:cR(2),some:cR(3),every:cR(4),find:cR(5),findIndex:cR(6),filterReject:cR(7)},lR=wi,uR=h,hR=D,pR=d,_R=O,ER=Se,fR=n,mR=Ze,SR=l,gR=ni,TR=X,RR=Ct,vR=Rn,CR=x,IR=Vo,yR=Eo,AR=Wr,bR=xT,OR=eo,wR=b,NR=$t,DR=ho,PR=P,LR=Aa,kR=Ac,MR=qe,UR=Hr,VR=rt,xR=pt,FR=HT,BR=XT,jR=tR,GR=Ka,WR=Sa,HR=dR.forEach,KR=vr("hidden"),YR="Symbol",qR="prototype",JR=WR.set,zR=WR.getterFor(YR),XR=Object[qR],QR=uR.Symbol,$R=QR&&QR[qR],ZR=uR.RangeError,ev=uR.TypeError,tv=uR.QObject,iv=wR.f,nv=NR.f,rv=bR.f,ov=PR.f,sv=pR([].push),av=MR("symbols"),cv=MR("op-symbols"),dv=MR("wks"),lv=!tv||!tv[qR]||!tv[qR].findChild,uv=function(e,t,i){var n=iv(XR,t);return n&&delete XR[t],nv(e,t,i),n&&e!==XR&&nv(XR,t,n),e},hv=_R&&fR((function(){return 7!==IR(nv({},"a",{get:function(){return nv(this,"a",{value:7}).a}})).a}))?uv:nv,pv=function(e,t){var i=av[e]=IR($R);return JR(i,{type:YR,tag:e,description:t}),_R||(i.description=t),i},_v=function(e,t,i){e===XR&&_v(cv,t,i),gR(e);var n=RR(t);return gR(i),mR(av,n)?(("enumerable"in i?!i.enumerable:!mR(e,n)||mR(e,KR)&&e[KR][n])?(mR(e,KR)||nv(e,KR,CR(1,IR(null))),e[KR][n]=!0):(mR(e,KR)&&e[KR][n]&&(e[KR][n]=!1),i=IR(i,{enumerable:CR(0,!1)})),hv(e,n,i)):nv(e,n,i)},Ev=function(e,t){gR(e);var i=TR(t),n=yR(i).concat(gv(i));return HR(n,(function(t){_R&&!hR(fv,i,t)||_v(e,t,i[t])})),e},fv=function(e){var t=RR(e),i=hR(ov,this,t);return!(this===XR&&mR(av,t)&&!mR(cv,t))&&(!(i||!mR(this,t)||!mR(av,t)||mR(this,KR)&&this[KR][t])||i)},mv=function(e,t){var i=TR(e),n=RR(t);if(i!==XR||!mR(av,n)||mR(cv,n)){var r=iv(i,n);return!r||!mR(av,n)||mR(i,KR)&&i[KR][n]||(r.enumerable=!0),r}},Sv=function(e){var t=rv(TR(e)),i=[];return HR(t,(function(e){mR(av,e)||mR(UR,e)||sv(i,e)})),i},gv=function(e){var t=e===XR,i=rv(t?cv:TR(e)),n=[];return HR(i,(function(e){!mR(av,e)||t&&!mR(XR,e)||sv(n,av[e])})),n};ER||(QR=function(){if(SR($R,this))throw new ev("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?vR(arguments[0]):void 0,t=VR(e),i=function(e){var n=void 0===this?uR:this;n===XR&&hR(i,cv,e),mR(n,KR)&&mR(n[KR],t)&&(n[KR][t]=!1);var r=CR(1,e);try{hv(n,t,r)}catch(e){if(!(e instanceof ZR))throw e;uv(n,t,r)}};return _R&&lv&&hv(XR,t,{configurable:!0,set:i}),pv(t,e)},LR($R=QR[qR],"toString",(function(){return zR(this).tag})),LR(QR,"withoutSetter",(function(e){return pv(VR(e),e)})),PR.f=fv,NR.f=_v,DR.f=Ev,wR.f=mv,AR.f=bR.f=Sv,OR.f=gv,FR.f=function(e){return pv(xR(e),e)},_R&&kR($R,"description",{configurable:!0,get:function(){return zR(this).description}})),lR({global:!0,constructor:!0,wrap:!0,forced:!ER,sham:!ER},{Symbol:QR}),HR(yR(dv),(function(e){BR(e)})),lR({target:YR,stat:!0,forced:!ER},{useSetter:function(){lv=!0},useSimple:function(){lv=!1}}),lR({target:"Object",stat:!0,forced:!ER,sham:!_R},{create:function(e,t){return void 0===t?IR(e):Ev(IR(e),t)},defineProperty:_v,defineProperties:Ev,getOwnPropertyDescriptor:mv}),lR({target:"Object",stat:!0,forced:!ER},{getOwnPropertyNames:Sv}),jR(),GR(QR,YR),UR[KR]=!0;var Tv=Se&&!!Symbol.for&&!!Symbol.keyFor,Rv=wi,vv=re,Cv=Ze,Iv=Rn,yv=qe,Av=Tv,bv=yv("string-to-symbol-registry"),Ov=yv("symbol-to-string-registry");Rv({target:"Symbol",stat:!0,forced:!Av},{for:function(e){var t=Iv(e);if(Cv(bv,t))return bv[t];var i=vv("Symbol")(t);return bv[t]=i,Ov[i]=t,i}});var wv=wi,Nv=Ze,Dv=Ie,Pv=Ae,Lv=Tv,kv=qe("symbol-to-string-registry");wv({target:"Symbol",stat:!0,forced:!Lv},{keyFor:function(e){if(!Dv(e))throw new TypeError(Pv(e)+" is not a symbol");if(Nv(kv,e))return kv[e]}});var Mv=$,Uv=Sa.get,Vv=d,xv=Ze,Fv=SyntaxError,Bv=parseInt,jv=String.fromCharCode,Gv=Vv("".charAt),Wv=Vv("".slice),Hv=Vv(/./.exec),Kv={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},Yv=/^[\da-f]{4}$/i,qv=/^[\u0000-\u001F]$/,Jv=!n((function(){var e="9007199254740993",t=JSON.rawJSON(e);return!JSON.isRawJSON(t)||JSON.stringify(t)!==e})),zv=wi,Xv=re,Qv=m,$v=D,Zv=d,eC=n,tC=cr,iC=A,nC=function(e){if(!Mv(e))return!1;var t=Uv(e);return!!t&&"RawJSON"===t.type},rC=Ie,oC=R,sC=Rn,aC=dd,cC=function(e,t){for(var i=!0,n="";t<e.length;){var r=Gv(e,t);if("\\"===r){var o=Wv(e,t,t+2);if(xv(Kv,o))n+=Kv[o],t+=2;else{if("\\u"!==o)throw new Fv('Unknown escape sequence: "'+o+'"');var s=Wv(e,t+=2,t+4);if(!Hv(Yv,s))throw new Fv("Bad Unicode escape at: "+t);n+=jv(Bv(s,16)),t+=4}}else{if('"'===r){i=!1,t++;break}if(Hv(qv,r))throw new Fv("Bad control character in string literal at: "+t);n+=r,t++}}if(i)throw new Fv("Unterminated string at: "+t);return{value:n,end:t}},dC=rt,lC=Se,uC=Jv,hC=String,pC=Xv("JSON","stringify"),_C=Zv(/./.exec),EC=Zv("".charAt),fC=Zv("".charCodeAt),mC=Zv("".replace),SC=Zv("".slice),gC=Zv([].push),TC=Zv(1.1.toString),RC=/[\uD800-\uDFFF]/g,vC=/^[\uD800-\uDBFF]$/,CC=/^[\uDC00-\uDFFF]$/,IC=dC(),yC=IC.length,AC=!lC||eC((function(){var e=Xv("Symbol")("stringify detection");return"[null]"!==pC([e])||"{}"!==pC({a:e})||"{}"!==pC(Object(e))})),bC=eC((function(){return'"\\udf06\\ud834"'!==pC("\udf06\ud834")||'"\\udead"'!==pC("\udead")})),OC=AC?function(e,t){var i=aC(arguments),n=NC(t);if(iC(n)||void 0!==e&&!rC(e))return i[1]=function(e,t){if(iC(n)&&(t=$v(n,this,hC(e),t)),!rC(t))return t},Qv(pC,null,i)}:pC,wC=function(e,t,i){var n=EC(i,t-1),r=EC(i,t+1);return _C(vC,e)&&!_C(CC,r)||_C(CC,e)&&!_C(vC,n)?"\\u"+TC(fC(e,0),16):e},NC=function(e){if(iC(e))return e;if(tC(e)){for(var t=e.length,i=[],n=0;n<t;n++){var r=e[n];"string"==typeof r?gC(i,r):"number"!=typeof r&&"Number"!==oC(r)&&"String"!==oC(r)||gC(i,sC(r))}var o=i.length,s=!0;return function(e,t){if(s)return s=!1,t;if(tC(this))return t;for(var n=0;n<o;n++)if(i[n]===e)return t}}};pC&&zv({target:"JSON",stat:!0,arity:3,forced:AC||bC||!uC},{stringify:function(e,t,i){var n=NC(t),r=[],o=OC(e,(function(e,t){var i=iC(n)?$v(n,this,hC(e),t):t;return!uC&&nC(i)?IC+(gC(r,i.rawJSON)-1):i}),i);if("string"!=typeof o)return o;if(bC&&(o=mC(o,RC,wC)),uC)return o;for(var s="",a=o.length,c=0;c<a;c++){var d=EC(o,c);if('"'===d){var l=cC(o,++c).end-1,u=SC(o,c,l);s+=SC(u,0,yC)===IC?r[SC(u,yC)]:'"'+u+'"',c=l}else s+=d}return s}});var DC=eo,PC=Xe;wi({target:"Object",stat:!0,forced:!Se||n((function(){DC.f(1)}))},{getOwnPropertySymbols:function(e){var t=DC.f;return t?t(PC(e)):[]}}),XT("asyncDispose"),XT("asyncIterator"),XT("dispose"),XT("hasInstance"),XT("isConcatSpreadable"),XT("iterator"),XT("match"),XT("matchAll"),XT("replace"),XT("search"),XT("species"),XT("split");var LC=tR;XT("toPrimitive"),LC();var kC=re,MC=Ka;XT("toStringTag"),MC(kC("Symbol"),"Symbol"),XT("unscopables"),Ka(h.JSON,"JSON",!0);var UC=Z.Symbol,VC=pt,xC=$t.f,FC=VC("metadata"),BC=Function.prototype;void 0===BC[FC]&&xC(BC,FC,{value:null}),XT("metadata");var jC=UC,GC=d,WC=re("Symbol"),HC=WC.keyFor,KC=GC(WC.prototype.valueOf),YC=WC.isRegisteredSymbol||function(e){try{return void 0!==HC(KC(e))}catch(e){return!1}};wi({target:"Symbol",stat:!0},{isRegisteredSymbol:YC});for(var qC=qe,JC=re,zC=d,XC=Ie,QC=pt,$C=JC("Symbol"),ZC=$C.isWellKnownSymbol,eI=JC("Object","getOwnPropertyNames"),tI=zC($C.prototype.valueOf),iI=qC("wks"),nI=0,rI=eI($C),oI=rI.length;nI<oI;nI++)try{var sI=rI[nI];XC($C[sI])&&QC(sI)}catch(e){}var aI=function(e){if(ZC&&ZC(e))return!0;try{for(var t=tI(e),i=0,n=eI(iI),r=n.length;i<r;i++)if(iI[n[i]]==t)return!0}catch(e){}return!1};wi({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:aI}),XT("customMatcher"),XT("observable"),wi({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:YC}),wi({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:aI}),XT("matcher"),XT("metadataKey"),XT("patternMatch"),XT("replaceAll");var cI=i(jC),dI=i(as),lI=Xe,uI=Gi,hI=rf,pI=uT;wi({target:"Array",proto:!0,arity:1,forced:n((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function(e){var t=lI(this),i=uI(t),n=arguments.length;pI(i+n);for(var r=0;r<n;r++)t[i]=arguments[r],i++;return hI(t,i),i}});var _I=tn("Array","push"),EI=l,fI=_I,mI=Array.prototype,SI=function(e){var t=e.push;return e===mI||EI(mI,e)&&t===mI.push?fI:t},gI=i(SI);var TI=wi,RI=cr,vI=ed,CI=$,II=xi,yI=Gi,AI=X,bI=$E,OI=rf,wI=pt,NI=dd,DI=vT("slice"),PI=wI("species"),LI=Array,kI=Math.max;TI({target:"Array",proto:!0,forced:!DI},{slice:function(e,t){var i,n,r,o=AI(this),s=yI(o),a=II(e,s),c=II(void 0===t?s:t,s);if(RI(o)&&(i=o.constructor,(vI(i)&&(i===LI||RI(i.prototype))||CI(i)&&null===(i=i[PI]))&&(i=void 0),i===LI||void 0===i))return NI(o,a,c);for(n=new(void 0===i?LI:i)(kI(c-a,0)),r=0;a<c;a++,r++)a in o&&bI(n,r,o[a]);return OI(n,r),n}});var MI=tn("Array","slice"),UI=l,VI=MI,xI=Array.prototype,FI=function(e){var t=e.slice;return e===xI||UI(xI,e)&&t===xI.slice?VI:t},BI=i(FI),jI=Sf;wi({target:"Array",stat:!0,forced:!Vu((function(e){Array.from(e)}))},{from:jI});var GI=i(Z.Array.from);function WI(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function HI(e,t){return function(e){if(dT(e))return e}(e)||function(e,t){var i=null==e?null:void 0!==cI&&dI(e)||e["@@iterator"];if(null!=i){var n,r,o,s,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=o.call(i)).done)&&(gI(a).call(a,n.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){var i;if(e){if("string"==typeof e)return WI(e,t);var n=BI(i=Object.prototype.toString.call(e)).call(i,8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?GI(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?WI(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var KI=n,YI=h.RegExp,qI=!KI((function(){var e=!0;try{YI(".","d")}catch(t){e=!1}var t={},i="",n=e?"dgimsy":"gimsy",r=function(e,n){Object.defineProperty(t,e,{get:function(){return i+=n,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var s in e&&(o.hasIndices="d"),o)r(s,o[s]);return Object.getOwnPropertyDescriptor(YI.prototype,"flags").get.call(t)!==n||i!==n})),JI=ni,zI=D,XI=Ze,QI=l,$I={correct:qI},ZI=function(){var e=JI(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},ey=RegExp.prototype,ty=$I.correct?function(e){return e.flags}:function(e){return $I.correct||!QI(ey,e)||XI(e,"flags")?e.flags:zI(ZI,e)},iy=d,ny=Xe,ry=Math.floor,oy=iy("".charAt),sy=iy("".replace),ay=iy("".slice),cy=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dy=/\$([$&'`]|\d{1,2})/g,ly=wi,uy=D,hy=d,py=q,_y=A,Ey=$,fy=an,my=Rn,Sy=Le,gy=ty,Ty=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=dy;return void 0!==r&&(r=ny(r),c=cy),sy(o,c,(function(o,c){var d;switch(oy(c,0)){case"$":return"$";case"&":return e;case"`":return ay(t,0,i);case"'":return ay(t,s);case"<":d=r[ay(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>a){var u=ry(l/10);return 0===u?o:u<=a?void 0===n[u-1]?oy(c,1):n[u-1]+oy(c,1):o}d=n[l-1]}return void 0===d?"":d}))},Ry=pt("replace"),vy=TypeError,Cy=hy("".indexOf),Iy=hy("".replace),yy=hy("".slice),Ay=Math.max;ly({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,d,l,u,h=py(this),p=0,_="";if(Ey(e)){if((i=fy(e))&&(n=my(py(gy(e))),!~Cy(n,"g")))throw new vy("`.replaceAll` does not allow non-global regexes");if(r=Sy(e,Ry))return uy(r,e,h,t);if(i)return Iy(my(h),e,t)}for(o=my(h),s=my(e),(a=_y(t))||(t=my(t)),c=s.length,d=Ay(1,c),l=Cy(o,s);-1!==l;)u=a?my(t(s,l,o)):Ty(s,o,l,[],void 0,t),_+=yy(o,p,l)+u,p=l+c,l=l+d>o.length?-1:Cy(o,s,l+d);return p<o.length&&(_+=yy(o,p)),_}});var by=tn("String","replaceAll"),Oy=l,wy=by,Ny=String.prototype,Dy=function(e){var t=e.replaceAll;return"string"==typeof e||e===Ny||Oy(Ny,e)&&t===Ny.replaceAll?wy:t},Py=i(Dy),Ly=h;wi({global:!0,forced:Ly.globalThis!==Ly},{globalThis:Ly});var ky=i(h),My={exports:{}};!function(e,i){!function(t,n){var r="function",o="undefined",s="object",a="string",c="major",d="model",l="name",u="type",h="vendor",p="version",_="architecture",E="console",f="mobile",m="tablet",S="smarttv",g="wearable",T="embedded",R="Amazon",v="Apple",C="ASUS",I="BlackBerry",y="Browser",A="Chrome",b="Firefox",O="Google",w="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",V="Xiaomi",x="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},W=function(e,t){return typeof e===a&&-1!==H(t).indexOf(H(e))},H=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,350)},Y=function(e,t){for(var i,o,a,c,d,l,u=0;u<t.length&&!d;){var h=t[u],p=t[u+1];for(i=o=0;i<h.length&&!d&&h[i];)if(d=h[i++].exec(e))for(a=0;a<p.length;a++)l=d[++o],typeof(c=p[a])===s&&c.length>0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(W(t[i][r],e))return"?"===i?n:i}else if(W(t[i],e))return"?"===i?n:i;return e},J={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"},z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+y],p],[/\bfocus\/([\w\.]+)/i],[p,[l,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[p,[l,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+y],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,A+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,A+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,q,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,H]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[h,k],[u,m]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[h,k],[u,f]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[h,v],[u,f]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[h,v],[u,m]],[/(macintosh);/i],[d,[h,v]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[h,M],[u,f]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[h,w],[u,m]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[h,w],[u,f]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[h,V],[u,f]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[h,V],[u,m]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[h,"OPPO"],[u,f]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[h,"Vivo"],[u,f]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[h,"Realme"],[u,f]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[h,P],[u,f]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[h,P],[u,m]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[h,N],[u,m]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[h,N],[u,f]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[h,"Lenovo"],[u,m]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[h,"Nokia"],[u,f]],[/(pixel c)\b/i],[d,[h,O],[u,m]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[h,O],[u,f]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[h,U],[u,f]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[h,U],[u,m]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[h,"OnePlus"],[u,f]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[h,R],[u,m]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[h,R],[u,f]],[/(playbook);[-\w\),; ]+(rim)/i],[d,h,[u,m]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[h,I],[u,f]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[h,C],[u,m]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[h,C],[u,f]],[/(nexus 9)/i],[d,[h,"HTC"],[u,m]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[d,/_/g," "],[u,f]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[h,"Acer"],[u,m]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[h,"Meizu"],[u,f]],[/(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],[h,d,[u,f]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[h,d,[u,m]],[/(surface duo)/i],[d,[h,D],[u,m]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[h,"Fairphone"],[u,f]],[/(u304aa)/i],[d,[h,"AT&T"],[u,f]],[/\bsie-(\w*)/i],[d,[h,"Siemens"],[u,f]],[/\b(rct\w+) b/i],[d,[h,"RCA"],[u,m]],[/\b(venue[\d ]{2,7}) b/i],[d,[h,"Dell"],[u,m]],[/\b(q(?:mv|ta)\w+) b/i],[d,[h,"Verizon"],[u,m]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[h,"Barnes & Noble"],[u,m]],[/\b(tm\d{3}\w+) b/i],[d,[h,"NuVision"],[u,m]],[/\b(k88) b/i],[d,[h,"ZTE"],[u,m]],[/\b(nx\d{3}j) b/i],[d,[h,"ZTE"],[u,f]],[/\b(gen\d{3}) b.+49h/i],[d,[h,"Swiss"],[u,f]],[/\b(zur\d{3}) b/i],[d,[h,"Swiss"],[u,m]],[/\b((zeki)?tb.*\b) b/i],[d,[h,"Zeki"],[u,m]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],d,[u,m]],[/\b(ns-?\w{0,9}) b/i],[d,[h,"Insignia"],[u,m]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[h,"NextBook"],[u,m]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],d,[u,f]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],d,[u,f]],[/\b(ph-1) /i],[d,[h,"Essential"],[u,f]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[h,"Envizen"],[u,m]],[/\b(trio[-\w\. ]+) b/i],[d,[h,"MachSpeed"],[u,m]],[/\btu_(1491) b/i],[d,[h,"Rotor"],[u,m]],[/(shield[\w ]+) b/i],[d,[h,"Nvidia"],[u,m]],[/(sprint) (\w+)/i],[h,d,[u,f]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[h,D],[u,f]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[h,x],[u,m]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[h,x],[u,f]],[/smart-tv.+(samsung)/i],[h,[u,S]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[h,k],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,N],[u,S]],[/(apple) ?tv/i],[h,[d,v+" TV"],[u,S]],[/crkey/i],[[d,A+"cast"],[h,O],[u,S]],[/droid.+aft(\w)( bui|\))/i],[d,[h,R],[u,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[h,M],[u,S]],[/(bravia[\w ]+)( bui|\))/i],[d,[h,U],[u,S]],[/(mitv-\w{5}) bui/i],[d,[h,V],[u,S]],[/Hbbtv.*(technisat) (.*);/i],[h,d,[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,K],[d,K],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,d,[u,E]],[/droid.+; (shield) bui/i],[d,[h,"Nvidia"],[u,E]],[/(playstation [345portablevi]+)/i],[d,[h,U],[u,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[h,D],[u,E]],[/((pebble))app/i],[h,d,[u,g]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[h,v],[u,g]],[/droid.+; (glass) \d/i],[d,[h,O],[u,g]],[/droid.+; (wt63?0{2,3})\)/i],[d,[h,x],[u,g]],[/(quest( 2| pro)?)/i],[d,[h,F],[u,g]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[u,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,m]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,m]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,f]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,q,J]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,q,J]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,j],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,I]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,A+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},X=function(e,i){if(typeof e===s&&(i=e,e=n),!(this instanceof X))return new X(e,i).getResult();var E=typeof t!==o&&t.navigator?t.navigator:n,S=e||(E&&E.userAgent?E.userAgent:""),g=E&&E.userAgentData?E.userAgentData:n,T=i?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(z,i):z;return this.getBrowser=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.browser),e[c]=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[p]),E&&E.brave&&typeof E.brave.isBrave==r&&(e[l]="Brave"),e},this.getCPU=function(){var e={};return e[_]=n,Y.call(e,S,T.cpu),e},this.getDevice=function(){var e={};return e[h]=n,e[d]=n,e[u]=n,Y.call(e,S,T.device),!e[u]&&g&&g.mobile&&(e[u]=f),"Macintosh"==e[d]&&E&&typeof E.standalone!==o&&E.maxTouchPoints&&E.maxTouchPoints>2&&(e[d]="iPad",e[u]=m),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,S,T.os),!e[l]&&g&&"Unknown"!=g.platform&&(e[l]=g.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(S),this};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,h,u,E,f,S,m,g,T]),X.ENGINE=X.OS=G([l,p]),e.exports&&(i=e.exports=X),i.UAParser=X;var Q=typeof t!==o&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var $=new X;Q.ua=$.getResult(),Q.ua.get=function(){return $.getUA()},Q.ua.set=function(e){$.setUA(e);var t=$.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:t)}(My,My.exports);var Uy=i(My.exports),Vy=Bd.clear;wi({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==Vy},{clearImmediate:Vy});var xy=h,Fy=m,By=A,jy=Qn,Gy=ae,Wy=dd,Hy=ud,Ky=xy.Function,Yy=/MSIE .\./.test(Gy)||"BUN"===jy&&function(){var e=xy.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),qy=wi,Jy=h,zy=Bd.set,Xy=function(e,t){var i=t?2:1;return Yy?function(n,r){var o=Hy(arguments.length,1)>i,s=By(n)?n:Ky(n),a=o?Wy(arguments,i):[],c=o?function(){Fy(s,this,a)}:s;return t?e(c,r):e(c)}:e},Qy=Jy.setImmediate?Xy(zy,!1):zy;qy({global:!0,bind:!0,enumerable:!0,forced:Jy.setImmediate!==Qy},{setImmediate:Qy});var $y=i(Z.setImmediate),Zy=h,eA=fl,tA=Ne,iA=ud,nA=O;wi({global:!0,enumerable:!0,dontCallGetSet:!0,forced:n((function(){return nA&&1!==Object.getOwnPropertyDescriptor(Zy,"queueMicrotask").value.length}))},{queueMicrotask:function(e){iA(arguments.length,1),eA(tA(e))}});var rA=i(Z.queueMicrotask);function oA(e,t){return function(){return e.apply(t,arguments)}}const sA=Object.prototype.toString,aA=Object.getPrototypeOf,cA=Symbol.iterator,dA=Symbol.toStringTag,lA=(e=>{let t=Object.prototype.hasOwnProperty;return(e,i)=>t.call(e,i)})(),uA=e=>"string"==typeof e&&("__proto__"===e||"constructor"===e||"prototype"===e),hA=(e,t,i)=>e===Object.prototype||!i&&null===t,pA=(e,t)=>{let i=e;const n=[];for(;null!=i;){if(-1!==n.indexOf(i))return!1;n.push(i);const r=aA(i);if(hA(i,r,i===e))return!1;if(lA(i,t))return!0;i=r}return!1},_A=(EA=Object.create(null),e=>{const t=sA.call(e);return EA[t]||(EA[t]=t.slice(8,-1).toLowerCase())});var EA;const fA=e=>(e=e.toLowerCase(),t=>_A(t)===e),mA=e=>t=>typeof t===e,SA=Array.isArray,gA=mA("undefined");function TA(e){return null!==e&&!gA(e)&&null!==e.constructor&&!gA(e.constructor)&&CA(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const RA=fA("ArrayBuffer");const vA=mA("string"),CA=mA("function"),IA=mA("number"),yA=e=>null!==e&&"object"==typeof e,AA=e=>{if(!yA(e))return!1;const t=aA(e);return!(null!==t&&t!==Object.prototype&&null!==aA(t)||pA(e,dA)||pA(e,cA))},bA=fA("Date"),OA=fA("File"),wA=fA("Blob"),NA=fA("FileList"),DA=fA("Set");const PA=void 0!==ky?ky:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},LA=void 0!==PA.FormData?PA.FormData:void 0,kA=fA("URLSearchParams"),MA=HI(["ReadableStream","Request","Response","Headers"].map(fA),4),UA=MA[0],VA=MA[1],xA=MA[2],FA=MA[3];function BA(e,t){let i,n,r=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allOwnKeys,o=void 0!==r&&r;if(null!=e)if("object"!=typeof e&&(e=[e]),SA(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(TA(e))return;const n=o?Object.getOwnPropertyNames(e):Object.keys(e),r=n.length;let s;for(i=0;i<r;i++)s=n[i],t.call(null,e[s],s,e)}}function jA(e,t){if(TA(e))return null;t=t.toLowerCase();const i=Object.keys(e);let n,r=i.length;for(;r-- >0;)if(n=i[r],t===n.toLowerCase())return n;return null}const GA=void 0!==ky?ky:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,WA=e=>!gA(e)&&e!==GA;const HA=(KA="undefined"!=typeof Uint8Array&&aA(Uint8Array),e=>KA&&e instanceof KA);var KA;const YA=fA("HTMLFormElement"),qA=Object.prototype.propertyIsEnumerable,JA=fA("RegExp"),zA=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};BA(i,((i,r)=>{let o;!1!==(o=t(i,r,e))&&(n[r]=o||i)})),Object.defineProperties(e,n)};const XA=fA("AsyncFunction"),QA=($A="function"==typeof $y,ZA=CA(GA.postMessage),$A?$y:ZA?(eb="axios@".concat(Math.random()),tb=[],GA.addEventListener("message",(e=>{let t=e.source,i=e.data;t===GA&&i===eb&&tb.length&&tb.shift()()}),!1),e=>{tb.push(e),GA.postMessage(eb,"*")}):e=>setTimeout(e));var $A,ZA,eb,tb;const ib=void 0!==rA?rA.bind(GA):"undefined"!=typeof process&&process.nextTick||QA,nb=e=>null!=e&&CA(e[cA]);var rb={isArray:SA,isArrayBuffer:RA,isBuffer:TA,isFormData:e=>{if(!e)return!1;if(LA&&e instanceof LA)return!0;const t=aA(e);if(!t||t===Object.prototype)return!1;if(!CA(e.append))return!1;const i=_A(e);return"formdata"===i||"object"===i&&CA(e.toString)&&"[object FormData]"===e.toString()},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&RA(e.buffer),t},isString:vA,isNumber:IA,isBoolean:e=>!0===e||!1===e,isObject:yA,isPlainObject:AA,isEmptyObject:e=>{if(!yA(e)||TA(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:UA,isRequest:VA,isResponse:xA,isHeaders:FA,isUndefined:gA,isDate:bA,isFile:OA,isReactNativeBlob:e=>!(!e||void 0===e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:wA,isRegExp:JA,isFunction:CA,isStream:e=>yA(e)&&CA(e.pipe),isURLSearchParams:kA,isTypedArray:HA,isFileList:NA,forEach:BA,merge:function e(){const t=WA(this)&&this||{},i=t.caseless,n=t.skipUndefined,r={},o=(t,o)=>{if("__proto__"===o||"constructor"===o||"prototype"===o)return;const s=i&&"string"==typeof o&&jA(r,o)||o,a=lA(r,s)?r[s]:void 0;AA(a)&&AA(t)?r[s]=e(a,t):AA(t)?r[s]=e({},t):SA(t)?r[s]=t.slice():n&&gA(t)||(r[s]=t)};for(let e=0,t=arguments.length;e<t;e++){const t=e<0||arguments.length<=e?void 0:arguments[e];if(!t||TA(t))continue;if(BA(t,o),"object"!=typeof t||SA(t))continue;const i=Object.getOwnPropertySymbols(t);for(let e=0;e<i.length;e++){const n=i[e];qA.call(t,n)&&o(t[n],n)}}return r},extend:function(e,t,i){return BA(t,((t,n)=>{i&&CA(t)?Object.defineProperty(e,n,{__proto__:null,value:oA(t,i),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).allOwnKeys}),e},trim:e=>zg(e)?zg(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,n)=>{let r,o,s;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==i&&aA(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:_A,kindOfTest:fA,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return-1!==n&&n===i},toArray:e=>{if(!e)return null;if(SA(e))return e;let t=e.length;if(!IA(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[cA]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:YA,hasOwnProperty:lA,hasOwnProp:lA,hasOwnInPrototypeChain:pA,getSafeProp:(e,t)=>null!=e&&pA(e,t)?e[t]:void 0,toSafeFlatObject:e=>{if(null==e||"object"!=typeof e&&"function"!=typeof e)return e;const t=aA(e);if(null===t&&(e=>{if(!Object.isExtensible(e))return!1;const t=Object.getOwnPropertyNames(e);return Object.getOwnPropertySymbols&&t.push(...Object.getOwnPropertySymbols(e)),t.every((t=>{if(uA(t))return!1;const i=Object.getOwnPropertyDescriptor(e,t);return!!i&&i.configurable&&!0===i.writable}))})(e))return e;const i=Object.create(null),n=Object.create(null),r=[];let o=e;for(;null!=o&&-1===r.indexOf(o);){r.push(o);const s=o===e?t:aA(o);if(hA(o,s,o===e))break;const a=Object.getOwnPropertyNames(o);Object.getOwnPropertySymbols&&a.push(...Object.getOwnPropertySymbols(o));for(const t of a)uA(t)||lA(n,t)||(i[t]=e[t],n[t]=!0);o=s}return i},reduceDescriptors:zA,freezeMethods:e=>{zA(e,((t,i)=>{var n;if(CA(e)&&Un(n=["arguments","caller","callee"]).call(n,i))return!1;const r=e[i];CA(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))}))},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach((e=>{i[e]=!0}))};return SA(e)?n(e):n(String(e).split(t)),i},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,i){return t.toUpperCase()+i})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:jA,global:GA,isContextDefined:WA,isSpecCompliantForm:function(e){return!!(e&&CA(e.append)&&"FormData"===e[dA]&&e[cA])},toJSONObject:e=>{const t=new WeakSet,i=e=>{if(yA(e)){if(t.has(e))return;if(TA(e))return e;if(!("toJSON"in e)){let n;if(t.add(e),DA(e)){n=[];for(const t of e){const e=i(t);!gA(e)&&n.push(e)}}else n=SA(e)?[]:{},BA(e,((e,t)=>{const r=i(e);!gA(r)&&(n[t]=r)}));return t.delete(e),n}}return e};return i(e)},isAsyncFn:XA,isThenable:e=>e&&(yA(e)||CA(e))&&CA(e.then)&&CA(e.catch),setImmediate:QA,asap:ib,isIterable:nb,isSafeIterable:e=>null!=e&&pA(e,cA)&&nb(e)};const ob=rb.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 sb=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),ab=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function cb(e,t){return rb.isArray(e)?e.map((e=>cb(e,t))):function(e){let t=0,i=e.length;for(;t<i;){const i=e.charCodeAt(t);if(9!==i&&32!==i)break;t+=1}for(;i>t;){const t=e.charCodeAt(i-1);if(9!==t&&32!==t)break;i-=1}return 0===t&&i===e.length?e:e.slice(t,i)}(String(e).replace(t,""))}const db=e=>cb(e,sb),lb=e=>cb(e,ab);function ub(e){const t=Object.create(null);return rb.forEach(e.toJSON(),((e,i)=>{t[i]=lb(e)})),t}const hb=Symbol("internals");function pb(e){var t;return e&&zg(t=String(e)).call(t).toLowerCase()}function _b(e){return!1===e||null==e?e:rb.isArray(e)?e.map(_b):db(String(e))}const Eb=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function fb(e){let t=0,i=e.length;for(;t<i;){const i=e.charCodeAt(t);if(9!==i&&32!==i)break;t+=1}for(;i>t;){const t=e.charCodeAt(i-1);if(9!==t&&32!==t)break;i-=1}return 0===t&&i===e.length?e:e.slice(t,i)}function mb(e,t,i,n,r){return rb.isFunction(n)?n.call(this,t,i):(r&&(t=i),rb.isString(t)?rb.isString(n)?-1!==t.indexOf(n):rb.isRegExp(n)?n.test(t):void 0:void 0)}class Sb{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=pb(t);if(!r)return;const o=rb.findKey(n,r);(!o||void 0===n[o]||!0===i||void 0===i&&!1!==n[o])&&(n[o||t]=_b(e))}const o=(e,t)=>rb.forEach(e,((e,i)=>r(e,i,t)));if(rb.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(rb.isString(e)&&(e=zg(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(zg(s=e).call(s)))o((e=>{const t={};let i,n,r;return e&&e.split("\n").forEach((function(e){var o,s;r=e.indexOf(":"),i=zg(o=e.substring(0,r)).call(o).toLowerCase(),n=zg(s=e.substring(r+1)).call(s);const a=rb.hasOwnProp(t,i);!i||a&&rb.hasOwnProp(ob,i)||("set-cookie"===i?a?t[i].push(n):t[i]=[n]:t[i]=a?t[i]+", "+n:n)})),t})(e),t);else if(rb.isObject(e)&&rb.isSafeIterable(e)){let i,n,r=Object.create(null);for(const t of e){if(!rb.isArray(t))throw new TypeError("Object iterator must return a key-value pair");n=t[0],rb.hasOwnProp(r,n)?(i=r[n],r[n]=rb.isArray(i)?[...i,t[1]]:[i,t[1]]):r[n]=t[1]}o(r,t)}else null!=e&&r(t,e,i);var s;return this}get(e,t){if(e=pb(e)){const i=rb.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if(rb.isFunction(t))return t.call(this,e,i);if(rb.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=pb(e)){const i=rb.findKey(this,e);return!(!i||void 0===this[i]||t&&!mb(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=pb(e)){const r=rb.findKey(i,e);!r||t&&!mb(0,i[r],r,t)||(delete i[r],n=!0)}}return rb.isArray(e)?e.forEach(r):r(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!mb(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return rb.forEach(this,((n,r)=>{var o;const s=rb.findKey(i,r);if(s)return t[s]=_b(n),void delete t[r];const a=e?function(e){return zg(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):zg(o=String(r)).call(o);a!==r&&delete t[r],t[a]=_b(n),i[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return this.constructor.concat(this,...t)}toJSON(e){const t=Object.create(null);return rb.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&rb.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let t=HI(e,2);return t[0]+": "+t[1]})).join("\n")}getSetCookie(){const e=this.get("set-cookie");return rb.isArray(e)?e:null==e||!1===e?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return function(e){const t=Object.create(null),i=String(e);let n=0,r=!1,o=!1;function s(e){const r=fb(i.slice(n,e)),o=r.indexOf("=");if(o<1)return;const s=fb(r.slice(0,o));if(!Eb.test(s))return;const a=s.toLowerCase();if("__proto__"===a||"constructor"===a||"prototype"===a)return;const c=fb(r.slice(o+1));t[a]=function(e){const t=e.length-1;if(t<1||34!==e.charCodeAt(0)||34!==e.charCodeAt(t))return e;let i="";for(let n=1;n<t;n++){const r=e.charCodeAt(n);if(34===r)return e;if(92===r&&(n+=1,n>=t))return e;i+=e[n]}return i}(c)}for(let e=0;e<i.length;e++){const t=i.charCodeAt(e);r?o?o=!1:92===t?o=!0:34===t&&(r=!1):34===t?r=!0:44!==t&&59!==t||(s(e),n=e+1)}return s(i.length),t}(e)}static concat(e){const t=new this(e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n.forEach((e=>t.set(e))),t}static accessor(e){const t=(this[hb]=this[hb]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=pb(e);t[n]||(!function(e,t){const i=rb.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{__proto__:null,value:function(e,i,r){return this[n].call(this,t,e,i,r)},configurable:!0})}))}(i,e),t[n]=!0)}return rb.isArray(e)?e.forEach(n):n(e),this}}Sb.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),rb.reduceDescriptors(Sb.prototype,((e,t)=>{let i=e.value,n=t[0].toUpperCase()+t.slice(1);return{get:()=>i,set(e){this[n]=e}}})),rb.freezeMethods(Sb);var gb=Sb;const Tb="[REDACTED ****]";function Rb(e,t){const i=new Set(t.map((e=>String(e).toLowerCase()))),n=[],r=e=>{if(null===e||"object"!=typeof e)return e;if(rb.isBuffer(e))return e;if(-1!==n.indexOf(e))return;let t;if(e instanceof gb&&(e=e.toJSON()),n.push(e),rb.isArray(e))t=[],e.forEach(((e,i)=>{const n=r(e);rb.isUndefined(n)||(t[i]=n)}));else{if(!rb.isPlainObject(e)&&function(e){if(rb.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(rb.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}(e))return n.pop(),e;t=Object.create(null);for(const n of Object.entries(e)){var o=HI(n,2);const e=o[0],s=o[1],a=i.has(e.toLowerCase())?Tb:r(s);rb.isUndefined(a)||(t[e]=a)}}return n.pop(),t};return r(e)}function vb(e){try{return String(e)}catch(e){return""}}class Cb extends Error{static from(e,t,i,n,r,o){let s=e.message;!s&&rb.isArray(e.errors)&&e.errors.length&&(s=function(e){return e.errors.map((e=>{try{return e&&e.message?vb(e.message):vb(e)}catch(e){return""}})).filter(Boolean).join("; ")||e.name||"AggregateError"}(e));const a=new Cb(s,t||e.code,i,n,r);return Object.defineProperty(a,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),a.name=e.name,null!=e.status&&null==a.status&&(a.status=e.status),o&&Object.assign(a,o),a}constructor(e,t,i,n,r){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status)}toJSON(){const e=this.config,t=e&&rb.hasOwnProp(e,"redact")?e.redact:void 0,i=rb.isArray(t)&&t.length>0?Rb(e,t):rb.toJSONObject(e);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:i,code:this.code,status:this.status}}}Cb.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Cb.ERR_BAD_OPTION="ERR_BAD_OPTION",Cb.ECONNABORTED="ECONNABORTED",Cb.ETIMEDOUT="ETIMEDOUT",Cb.ECONNREFUSED="ECONNREFUSED",Cb.ERR_NETWORK="ERR_NETWORK",Cb.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Cb.ERR_DEPRECATED="ERR_DEPRECATED",Cb.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Cb.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Cb.ERR_CANCELED="ERR_CANCELED",Cb.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Cb.ERR_INVALID_URL="ERR_INVALID_URL",Cb.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var Ib=Cb;const yb=100;function Ab(e){return rb.isPlainObject(e)||rb.isArray(e)}function bb(e){return rb.endsWith(e,"[]")?e.slice(0,-2):e}function Ob(e,t,i){return e?e.concat(t).map((function(e,t){return e=bb(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}const wb=rb.toFlatObject(rb,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Nb(e,t,i){if(!rb.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(e,t)=>{const n=rb.getSafeProp(i,e);return rb.isUndefined(n)?t:n},r=n("metaTokens",!0),o=n("visitor")||_,s=n("dots",!1),a=n("indexes",!1),c=n("Blob")||"undefined"!=typeof Blob&&Blob,d=n("maxDepth",yb),l=c&&rb.isSpecCompliantForm(t),u=[];if(!rb.isFunction(o))throw new TypeError("visitor must be a function");function h(e){if(null===e)return"";if(rb.isDate(e))return e.toISOString();if(rb.isBoolean(e))return e.toString();if(!l&&rb.isBlob(e))throw new Ib("Blob is not supported. Use a Buffer instead.");if(rb.isArrayBuffer(e)||rb.isTypedArray(e)){if(l&&"function"==typeof c)return new c([e]);throw new Ib("Blob is not supported. Use a Buffer instead.",Ib.ERR_NOT_SUPPORT)}return e}function p(e){if(e>d)throw new Ib("Object is too deeply nested ("+e+" levels). Max depth: "+d,Ib.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _(e,i,n){let o=e;if(rb.isReactNative(t)&&rb.isReactNativeBlob(e))return t.append(Ob(n,i,s),h(e)),!1;if(e&&!n&&"object"==typeof e)if(rb.endsWith(i,"{}"))i=r?i:i.slice(0,-2),e=function(e,t){if(d===1/0)return JSON.stringify(e);const i=[];return JSON.stringify(e,(function(e,n){if(!rb.isObject(n))return n;for(;i.length&&i[i.length-1]!==this;)i.pop();return i.push(n),p(t+i.length-1),n}))}(e,1);else if(rb.isArray(e)&&function(e){return rb.isArray(e)&&!e.some(Ab)}(e)||(rb.isFileList(e)||rb.endsWith(i,"[]"))&&(o=rb.toArray(e)))return i=bb(i),o.forEach((function(e,n){!rb.isUndefined(e)&&null!==e&&t.append(!0===a?Ob([i],n,s):null===a?i:i+"[]",h(e))})),!1;return!!Ab(e)||(t.append(Ob(n,i,s),h(e)),!1)}const E=Object.assign(wb,{defaultVisitor:_,convertValue:h,isVisitable:Ab});if(!rb.isObject(e))throw new TypeError("data must be an object");return function e(i,n){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!rb.isUndefined(i)){if(p(r),-1!==u.indexOf(i))throw new Error("Circular reference detected in "+n.join("."));u.push(i),rb.forEach(i,(function(i,s){!0===(!(rb.isUndefined(i)||null===i)&&o.call(t,i,rb.isString(s)?zg(s).call(s):s,n,E))&&e(i,n?n.concat(s):[s],r+1)})),u.pop()}}(e),t}function Db(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,(function(e){return t[e]}))}function Pb(e,t){this._pairs=[],e&&Nb(e,this,t)}const Lb=Pb.prototype;function kb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Mb(e,t,i){if(!t)return e;e=e||"";const n=rb.isFunction(i)?{serialize:i}:i,r=rb.getSafeProp(n,"encode")||kb,o=rb.getSafeProp(n,"serialize");let s;if(s=o?o(t,n):rb.isURLSearchParams(t)?t.toString():new Pb(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Lb.append=function(e,t){this._pairs.push([e,t])},Lb.toString=function(e){const t=e?t=>e.call(this,t,Db):Db;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};const Ub=Symbol("internals");function Vb(e){return e?e.length:0}function xb(e){if(e)for(;e.length&&null===e[e.length-1];)e.pop()}function Fb(e,t){const i=e.handlers,n=Vb(i);i!==t.handlersRef?(t.handlersRef=i,t.handlerEntries.clear()):n!==t.handlersLength&&(n?t.handlerEntries.forEach((function(e,n){i[e.index]!==e.handler&&t.handlerEntries.delete(n)})):t.handlerEntries.clear()),t.handlersLength=n}var Bb=class{constructor(){this.handlers=[],this[Ub]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,i){const n={fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null},r=this[Ub];null==this.handlers&&(this.handlers=[]),Fb(this,r);const o=r.nextId++;return this.handlers.push(n),r.handlerEntries.set(o,{handler:n,index:this.handlers.length-1}),r.handlersLength=this.handlers.length,o}eject(e){const t=this[Ub];Fb(this,t);const i=t.handlerEntries.get(e);if(i){if(t.handlerEntries.delete(e),this.handlers[i.index]!==i.handler)return;this.handlers[i.index]=null,t.iterationDepth||(xb(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Fb(this,this[Ub]))}forEach(e){const t=this[Ub];Fb(this,t),t.iterationDepth++;try{rb.forEach(this.handlers,(function(t){null!==t&&e(t)}))}finally{--t.iterationDepth||(Fb(this,t),xb(this.handlers),t.handlersLength=Vb(this.handlers))}}},jb={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},Gb={exports:{}},Wb=wi,Hb=O,Kb=$t.f;Wb({target:"Object",stat:!0,forced:Object.defineProperty!==Kb,sham:!Hb},{defineProperty:Kb});var Yb=Z.Object,qb=Gb.exports=function(e,t,i){return Yb.defineProperty(e,t,i)};Yb.defineProperty.sham&&(qb.sham=!0);var Jb=i(Gb.exports),zb=i(HT.f("iterator"));function Xb(e){return Xb="function"==typeof cI&&"symbol"==typeof zb?function(e){return typeof e}:function(e){return e&&"function"==typeof cI&&e.constructor===cI&&e!==cI.prototype?"symbol":typeof e},Xb(e)}var Qb=i(HT.f("toPrimitive"));function $b(e){var t=function(e,t){if("object"!==Xb(e)||null===e)return e;var i=e[Qb];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==Xb(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===Xb(t)?t:String(t)}function Zb(e,t,i){return(t=$b(t))in e?Jb(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var eO=i(LE),tO={isBrowser:!0,classes:{URLSearchParams:void 0!==eO?eO:Pb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const iO="undefined"!=typeof window&&"undefined"!=typeof document,nO="object"==typeof navigator&&navigator||void 0,rO=iO&&(!nO||["ReactNative","NativeScript","NS"].indexOf(nO.product)<0),oO="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,sO=iO&&window.location.href||"http://localhost";function aO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aO(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var dO=cO(cO({},Object.freeze({__proto__:null,hasBrowserEnv:iO,hasStandardBrowserEnv:rO,hasStandardBrowserWebWorkerEnv:oO,navigator:nO,origin:sO})),tO);function lO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function uO(e,t){return Nb(e,new dO.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?lO(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):lO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({visitor:function(e,t,i,n){return dO.isNode&&rb.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}const hO=yb;function pO(e){if(e>hO)throw new Ib("FormData field is too deeply nested ("+e+" levels). Max depth: "+hO,Ib.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _O(e){function t(e,i,n,r){pO(r);let o=e[r++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=r>=e.length;if(o=!o&&rb.isArray(n)?n.length:o,a)return rb.hasOwnProp(n,o)?n[o]=rb.isArray(n[o])?n[o].concat(i):[n[o],i]:n[o]=i,!s;rb.hasOwnProp(n,o)&&rb.isObject(n[o])||(n[o]=[]);return t(e,i,n[o],r)&&rb.isArray(n[o])&&(n[o]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let o;for(n=0;n<r;n++)o=i[n],t[o]=e[o];return t}(n[o])),!s}if(rb.isFormData(e)&&rb.isFunction(e.entries)){const i={};return rb.forEachEntry(e,((e,n)=>{t(function(e){const t=[],i=/[^.[\]]+|\[([^.[\]]*)]/g;let n;for(;null!==(n=i.exec(e));)pO(t.length),t.push("[]"===n[0]?"":n[1]||n[0]);return t}(e),n,i,0)})),i}return null}var EO=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]);const fO=(e,t)=>null!=e&&rb.hasOwnProp(e,t)?e[t]:void 0;const mO={transitional:jb,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=rb.isObject(e);r&&rb.isHTMLForm(e)&&(e=new FormData(e));if(rb.isFormData(e))return n?JSON.stringify(_O(e)):e;if(rb.isArrayBuffer(e)||rb.isBuffer(e)||rb.isStream(e)||rb.isFile(e)||rb.isBlob(e)||rb.isReadableStream(e))return e;if(rb.isArrayBufferView(e))return e.buffer;if(rb.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){const t=fO(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return uO(e,t).toString();if((o=rb.isFileList(e))||i.indexOf("multipart/form-data")>-1){const i=fO(this,"env"),n=i&&i.FormData;return Nb(o?{"files[]":e}:e,n&&new n,t)}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if(rb.isString(e))try{return(t||JSON.parse)(e),zg(rb).call(rb,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=fO(this,"transitional")||mO.transitional,i=t&&t.forcedJSONParsing,n=fO(this,"responseType"),r="json"===n;if(rb.isResponse(e)||rb.isReadableStream(e))return e;if(e&&rb.isString(e)&&(i&&!n||r)){const i=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,fO(this,"parseReviver"))}catch(e){if(i){if("SyntaxError"===e.name)throw Ib.from(e,Ib.ERR_BAD_RESPONSE,this,null,fO(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dO.classes.FormData,Blob:dO.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rb.forEach(EO,(e=>{mO.headers[e]={}}));var SO=mO;function gO(e,t){const i=this||SO,n=t||i,r=gb.from(n.headers);let o=n.data;return rb.forEach(e,(function(e){o=e.call(i,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function TO(e){return!(!e||!e.__CANCEL__)}var RO=class extends Ib{constructor(e,t,i){super(null==e?"canceled":e,Ib.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}};function vO(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Ib("Request failed with status code "+i.status,i.status>=400&&i.status<500?Ib.ERR_BAD_REQUEST:Ib.ERR_BAD_RESPONSE,i.config,i.request,i)):e(i)}const CO=/[\t\n\r]/g;function IO(e){if("string"!=typeof e)return e;let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t).replace(CO,"")}function yO(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}const AO=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0;const r=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[s];r||(r=c),i[o]=a,n[o]=c;let l=s,u=0;for(;l!==o;)u+=i[l++],l%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-r<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let i,n,r=0,o=1e3/t;const s=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,i=null,n&&(clearTimeout(n),n=null),e(...t)};return[function(){const e=Date.now(),t=e-r;for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];t>=o?s(c,e):(i=c,n||(n=setTimeout((()=>{n=null,s(i)}),o-t)))},()=>i&&s(i),function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return s(t)}]}((i=>{if(!i||!rb.isNumber(i.loaded))return;const o=i.loaded,s=i.lengthComputable?i.total:void 0,a=Math.max(0,null!=s?Math.min(o,s):o),c=Math.max(0,a-n),d=r(c);n=Math.max(n,a);e({loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:d||void 0,estimated:d&&s?(s-a)/d:void 0,event:i,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),i)},bO=(e,t)=>{const i=null!=e;return[n=>t[0]({lengthComputable:i,total:e,loaded:n}),t[1]]},OO=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rb.asap;return function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return t((()=>e(...n)))}};var wO=dO.hasStandardBrowserEnv?((e,t)=>i=>(i=new xS(i,dO.origin),e.protocol===i.protocol&&e.host===i.host&&(t||e.port===i.port)))(new xS(dO.origin),dO.navigator&&/(msie|trident)/i.test(dO.navigator.userAgent)):()=>!0,NO=dO.hasStandardBrowserEnv?{write(e,t,i,n,r,o,s){if("undefined"==typeof document)return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];rb.isNumber(i)&&a.push("expires=".concat(new Date(i).toUTCString())),rb.isString(n)&&a.push("path=".concat(n)),rb.isString(r)&&a.push("domain=".concat(r)),!0===o&&a.push("secure"),rb.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(let i=0;i<t.length;i++){const n=t[i].replace(/^\s+/,""),r=n.indexOf("=");if(-1!==r&&n.slice(0,r)===e)try{return decodeURIComponent(n.slice(r+1))}catch(e){return n.slice(r+1)}}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};const DO=/^https?:(?!\/\/)/i;function PO(e){const t=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,"$1".concat(Tb,"@")),i=t.indexOf("#"),n=(-1===i?t:t.slice(0,i)).replace(/([?&][^=&#]*=)[^&#]*/g,"$1".concat(Tb));return-1===i?n:"".concat(n,"#").concat((r=t.slice(i+1))?r.replace(/(^|&)([^=&]*=)?[^&]+/g,(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return"".concat(t).concat(i).concat(Tb)})):r);var r}function LO(e,t){if("string"==typeof e){const i=IO(e);if(DO.test(i))throw new Ib("Invalid URL ".concat(JSON.stringify(PO(i)),': missing "//" after protocol'),Ib.ERR_INVALID_URL,t)}}function kO(e,t,i,n){LO(t,n);let r=!function(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(r||!1===i)?(LO(e,n),function(e,t){if(!t)return e;let i=e.length;for(;i>0&&47===e.charCodeAt(i-1);)i--;return e.slice(0,i)+"/"+t.replace(/^\/+/,"")}(e,t)):t}function MO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function UO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?MO(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):MO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const VO=e=>e instanceof gb?UO({},e):e,xO=e=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(e).concat(Object.getOwnPropertySymbols(e).filter((t=>Object.getOwnPropertyDescriptor(e,t).enumerable))):Object.keys(e);function FO(e,t){e=e||{},t=t||{};const i=Object.create(null);function n(e,t,i,n){return rb.isPlainObject(e)&&rb.isPlainObject(t)?rb.merge.call({caseless:n},e,t):rb.isPlainObject(t)?rb.merge({},t):rb.isArray(t)?t.slice():t}function r(e,t,i,r){return rb.isUndefined(t)?rb.isUndefined(e)?void 0:n(void 0,e,0,r):n(e,t,0,r)}function o(e,t){if(!rb.isUndefined(t))return n(void 0,t)}function s(e,t){return rb.isUndefined(t)?rb.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(i,r,o){return rb.hasOwnProp(t,o)?n(i,r):rb.hasOwnProp(e,o)?n(void 0,i):void 0}Object.defineProperty(i,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutErrorMessage: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,allowedSocketPaths:s,responseEncoding:s,validateStatus:a,headers:(e,t,i)=>r(VO(e),VO(t),0,!0)};return rb.forEach(xO(UO(UO({},e),t)),(function(n){if("__proto__"===n||"constructor"===n||"prototype"===n)return;const o=rb.hasOwnProp(c,n)?c[n]:r,s=o(rb.hasOwnProp(e,n)?e[n]:void 0,rb.hasOwnProp(t,n)?t[n]:void 0,n);rb.isUndefined(s)&&o!==a||(i[n]=s)})),rb.hasOwnProp(t,"validateStatus")&&rb.isUndefined(t.validateStatus)&&!1===function(i){const n=rb.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!rb.isUndefined(n)){if(!rb.isPlainObject(n))return;if(rb.hasOwnProp(n,i))return n[i]}const r=rb.hasOwnProp(e,"transitional")?e.transitional:void 0;if(rb.isPlainObject(r)&&rb.hasOwnProp(r,i))return r[i]}("validateStatusUndefinedResolves")&&(rb.hasOwnProp(e,"validateStatus")?i.validateStatus=n(void 0,e.validateStatus):delete i.validateStatus),i}const BO=["content-type","content-length"];const jO=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16))));function GO(e){const t=FO({},e),i=e=>rb.hasOwnProp(t,e)?t[e]:void 0,n=i("data");let r=i("withXSRFToken");const o=i("xsrfHeaderName"),s=i("xsrfCookieName");let a=i("headers");const c=i("auth"),d=i("baseURL"),l=i("allowAbsoluteUrls"),u=i("url");if(t.headers=a=gb.from(a),t.url=Mb(kO(d,u,l,t),i("params"),i("paramsSerializer")),c){const t=rb.getSafeProp(c,"username")||"",i=rb.getSafeProp(c,"password")||"";try{a.set("Authorization","Basic "+btoa(t+":"+(i?jO(i):"")))}catch(t){throw Ib.from(t,Ib.ERR_BAD_OPTION_VALUE,e)}}if(rb.isFormData(n)){const e=rb.getSafeProp(n,"getHeaders");dO.hasStandardBrowserEnv||dO.hasStandardBrowserWebWorkerEnv||rb.isReactNative(n)?a.setContentType(void 0):rb.isFunction(e)&&function(e,t,i){"content-only"===i?Object.entries(t||{}).forEach((t=>{let i=HI(t,2),n=i[0],r=i[1];Un(BO).call(BO,n.toLowerCase())&&e.set(n,r)})):e.set(t)}(a,e.call(n),i("formDataHeaderPolicy"))}if(dO.hasStandardBrowserEnv){rb.isFunction(r)&&(r=r(t));if(!0===r||null==r&&wO(t.url)){const e=o&&s&&NO.read(s);e&&a.set(o,e)}}return t}var WO="undefined"!=typeof XMLHttpRequest&&function(e){return new cp((function(t,i){var n;const r=GO(e);let o=r.data;const s=gb.from(r.headers).normalize();let a,c,d,l,u,h,p=r.responseType,_=r.onUploadProgress,E=r.onDownloadProgress;function f(){l&&l(),u&&u(),r.cancelToken&&r.cancelToken.unsubscribe(a),r.signal&&r.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function S(n){if(!m)return;if(!(0!==m.status||"file"===(yO(IO(r.url))||yO(dO.origin))||m.responseURL&&m.responseURL.startsWith("file:")))return i(new Ib("Request aborted",Ib.ECONNABORTED,e,m)),f(),void(m=null);try{n?h&&h(n):u&&u()}catch(e){setTimeout((()=>{throw e}))}if(!m)return;const o=gb.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());vO((function(e){t(e),f()}),(function(e){i(e),f()}),{data:p&&"text"!==p&&"json"!==p?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:o,config:e,request:m}),m=null}if(m.open(r.method.toUpperCase(),r.url,!0),m.timeout=r.timeout,"onloadend"in m?m.onloadend=S:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&m.responseURL.startsWith("file:"))&&setTimeout(S)},m.onabort=function(){m&&(i(new Ib("Request aborted",Ib.ECONNABORTED,e,m)),f(),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",r=new Ib(n,Ib.ERR_NETWORK,e,m);r.event=t||null,i(r),f(),m=null},m.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const n=r.transitional||jb;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),i(new Ib(t,n.clarifyTimeoutError?Ib.ETIMEDOUT:Ib.ECONNABORTED,e,m)),f(),m=null},void 0===o&&s.setContentType(null),"setRequestHeader"in m&&rb.forEach(ub(s),(function(e,t){m.setRequestHeader(t,e)})),rb.isUndefined(r.withCredentials)||(m.withCredentials=!!r.withCredentials),p&&"json"!==p&&(m.responseType=r.responseType),E){var g=HI(AO(E,!0),3);d=g[0],u=g[1],h=g[2],m.addEventListener("progress",d)}if(_&&m.upload){var T=HI(AO(_),2);c=T[0],l=T[1],m.upload.addEventListener("progress",c),m.upload.addEventListener("loadend",l)}(r.cancelToken||r.signal)&&(a=t=>{m&&(i(!t||t.type?new RO(null,e,m):t),m.abort(),f(),m=null)},r.cancelToken&&r.cancelToken.subscribe(a),r.signal&&(r.signal.aborted?a():r.signal.addEventListener("abort",a)));const R=yO(r.url);if(R&&!Un(n=dO.protocols).call(n,R))return i(new Ib("Unsupported protocol "+R+":",Ib.ERR_BAD_REQUEST,e)),void f();m.send(o||null)}))};var HO=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const i=new AbortController;let n=!1;const r=function(e){if(!n){n=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ib?t:new RO(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>{o=null,r(new Ib("timeout of ".concat(t,"ms exceeded"),Ib.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=>{n||(e.aborted?r.call(e):e.addEventListener("abort",r,{once:!0}))}));const a=i.signal;return a.unsubscribe=()=>rb.asap(s),a},KO=i(ap),YO=HT.f("asyncIterator"),qO=i(YO);function JO(e,t){this.v=e,this.k=t}function zO(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof JO;KO.resolve(a?s.v:s).then((function(i){if(a){var c="return"===t?"return":"next";if(!s.k||i.done)return n(c,i);i=e[c](i).value}r(o.done?"return":"normal",i)}),(function(e){n("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new KO((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function XO(e){return function(){return new zO(e.apply(this,arguments))}}function QO(e){return new JO(e,0)}function $O(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new JO(n=new KO((function(i){i(e[t](n))})),1)}}return t[void 0!==cI&&zb||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e)}),t}zO.prototype["function"==typeof cI&&qO||"@@asyncIterator"]=function(){return this},zO.prototype.next=function(e){return this._invoke("next",e)},zO.prototype.throw=function(e){return this._invoke("throw",e)},zO.prototype.return=function(e){return this._invoke("return",e)};var ZO=i(YO);function ew(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=ZO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new tw(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function tw(e){function t(e){if(Object(e)!==e)return cp.reject(new TypeError(e+" is not an object."));var t=e.done;return cp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return tw=function(e){this.s=e,this.n=e.next},tw.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?cp.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?cp.reject(e):t(i.apply(this.s,arguments))}},new tw(e)}const iw=function*(e,t){let i=e.byteLength;if(!t||i<t)return void(yield e);let n,r=0;for(;r<i;)n=r+t,yield e.slice(r,n),r=n},nw=function(){var e=XO((function*(e,t){var i,n=!1,r=!1;try{for(var o,s=ew(rw(e));n=!(o=yield QO(s.next())).done;n=!1){const e=o.value;yield*$O(ew(iw(e,t)))}}catch(e){r=!0,i=e}finally{try{n&&null!=s.return&&(yield QO(s.return()))}finally{if(r)throw i}}}));return function(t,i){return e.apply(this,arguments)}}(),rw=function(){var e=XO((function*(e){if(e[ZO])return void(yield*$O(ew(e)));const t=e.getReader();try{for(;;){const e=yield QO(t.read()),i=e.done,n=e.value;if(i)break;yield n}}finally{yield QO(t.cancel())}}));return function(t){return e.apply(this,arguments)}}(),ow=(e,t,i,n)=>{const r=nw(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const t=await r.next(),n=t.done,o=t.value;if(n)return a(),void e.close();let c=o.byteLength;if(i){let e=s+=c;i(e)}e.enqueue(new Uint8Array(o))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})},sw=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,aw=(e,t,i)=>t+2<i&&sw(e.charCodeAt(t+1))&&sw(e.charCodeAt(t+2)),cw=e=>e<=57?e-48:(223&e)-55,dw=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||43===e||47===e||45===e||95===e,lw=e=>{const t=e.length;let i=0,n=0,r=!1;for(let s=0;s<t;s++){let a=e.charCodeAt(s);37===a&&aw(e,s,t)&&(a=16*cw(e.charCodeAt(s+1))+cw(e.charCodeAt(s+2)),s+=2),9!==(o=a)&&10!==o&&12!==o&&13!==o&&32!==o&&(61!==a?!dw(a)||n>0?r=!0:i++:n++)}var o;return r||n>2||n>0&&(i+n)%4!=0||i%4==1?(e=>{const t=e.length;let i=0;return t>0&&61===e.charCodeAt(t-1)&&(i++,t>1&&61===e.charCodeAt(t-2)&&i++),Math.floor(3*(t-i)/4)})(e):(e=>{const t=e%4;return 3*Math.floor(e/4)+(2===t?1:3===t?2:0)})(i)},uw=(e,t)=>{if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;const i=e.indexOf(",");if(i<0)return 0;const n=e.slice(5,i),r=e.slice(i+1);if(/;base64/i.test(n))return t(r);let o=0;for(let e=0,t=r.length;e<t;e++){const i=r.charCodeAt(e);if(37===i&&aw(r,e,t))o+=1,e+=2;else if(i<128)o+=1;else if(i<2048)o+=2;else if(i>=55296&&i<=56319&&e+1<t){const t=r.charCodeAt(e+1);t>=56320&&t<=57343?(o+=4,e++):o+=3}else o+=3}return o};const hw="1.20.0",pw={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},_w=rb.isFunction,Ew=e=>{if(!rb.isString(e))return e;try{return decodeURIComponent(e)}catch(t){return e}},fw=function(e){try{for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return!!e(...i)}catch(e){return!1}},mw=e=>{const t=void 0!==rb.global&&null!==rb.global?rb.global:ky,i=t.ReadableStream,n=t.TextEncoder,r=e=rb.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e),o=r.fetch,s=r.Request,a=r.Response,c=o?_w(o):"function"==typeof fetch,d=_w(s),l=_w(a);if(!c)return!1;const u=c&&_w(i),h=c&&("function"==typeof n?(p=new n,e=>p.encode(e)):async e=>new Uint8Array(await new s(e).arrayBuffer()));var p;const _=d&&u&&fw((()=>{let e=!1;const t=new s(dO.origin,{body:new i,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n})),E=l&&u&&fw((()=>rb.isReadableStream(new a("").body))),f={stream:E&&(e=>e.body)};c&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!f[e]&&(f[e]=(t,i)=>{let n=t&&t[e];if(n)return n.call(t);throw new Ib("Response type '".concat(e,"' is not supported"),Ib.ERR_NOT_SUPPORT,i)})}));const m=async e=>{if(null==e)return 0;if(rb.isBlob(e))return e.size;if(rb.isSpecCompliantForm(e)){const t=new s(dO.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return rb.isArrayBufferView(e)||rb.isArrayBuffer(e)?e.byteLength:(rb.isURLSearchParams(e)&&(e+=""),rb.isString(e)?(await h(e)).byteLength:void 0)};return async e=>{let t=GO(e),i=t.url,r=t.method,c=t.data,l=t.signal,h=t.cancelToken,p=t.timeout,S=t.onDownloadProgress,g=t.onUploadProgress,T=t.responseType,R=t.headers,v=t.withCredentials,C=void 0===v?"same-origin":v,I=t.fetchOptions,y=t.maxContentLength,A=t.maxBodyLength,b=t.maxRedirects;const O=rb.isNumber(y)&&y>-1,w=rb.isNumber(A)&&A>-1;let N=o||fetch;T=T?(T+"").toLowerCase():"text";let D=HO([l,h&&h.toAbortSignal()],p),P=null;const L=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let k,M=null;const U=()=>new Ib("Request body larger than maxBodyLength limit",Ib.ERR_BAD_REQUEST,e,P);try{let t;const o=(x="auth",rb.hasOwnProp(e,x)?e[x]:void 0);if(o){const e=rb.getSafeProp(o,"username")||"";t={username:e,password:rb.getSafeProp(o,"password")||""}}if((e=>{const t=e.indexOf("://");let i=e;return-1!==t&&(i=i.slice(t+3)),Un(i).call(i,"@")||Un(i).call(i,":")})(i)){const e=new xS(i,dO.origin);if(!t&&(e.username||e.password)){const i=Ew(e.username);t={username:i,password:Ew(e.password)}}(e.username||e.password)&&(e.username="",e.password="",i=e.href)}if(t&&(R.delete("authorization"),R.set("Authorization","Basic "+btoa((V=(t.username||"")+":"+(t.password||""),encodeURIComponent(V).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16)))))))),O&&"string"==typeof i&&i.startsWith("data:")){const t=function(e){const t="string"==typeof e?e.indexOf("#"):-1;return uw(-1===t?e:e.slice(0,t),lw)}(i);if(t>y)throw new Ib("maxContentLength size of "+y+" exceeded",Ib.ERR_BAD_RESPONSE,e,P)}if(w&&"get"!==r&&"head"!==r){const e=await m(c);if("number"==typeof e&&isFinite(e)&&(k=e,e>A))throw U()}const l=w&&(rb.isReadableStream(c)||rb.isStream(c)),h=(e,t,i)=>ow(e,65536,(e=>{if(w&&e>A)throw M=U();t&&t(e)}),i);if(_&&"get"!==r&&"head"!==r&&(g||l)){if(k=null==k?await(async(e,t)=>{const i=rb.toFiniteNumber(e.getContentLength());return null==i?m(t):i})(R,c):k,0!==k||l){let e,t=new s(i,{method:"POST",body:c,duplex:"half"});if(rb.isFormData(c)&&(e=t.headers.get("content-type"))&&R.setContentType(e),t.body){const e=HI(g&&bO(k,AO(OO(g)))||[],2),i=e[0],n=e[1];c=h(t.body,i,n)}}}else if(l&&!d&&u&&"get"!==r&&"head"!==r)c=h(c);else if(l&&d&&!_&&"get"!==r&&"head"!==r)throw new Ib("Stream request bodies are not supported by the current fetch implementation",Ib.ERR_NOT_SUPPORT,e,P);rb.isString(C)||(C=C?"include":"omit");const p=d&&"credentials"in s.prototype;if(rb.isFormData(c)){const e=R.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&R.delete("content-type")}R.set("User-Agent","axios/"+hw,!1);const v=null==I?I:Object.assign(Object.create(null),I);v&&(delete v.body,delete v.headers,delete v.method,delete v.signal,delete v.duplex,delete v.credentials);const F=Object.assign(Object.create(null),v,{signal:D,method:r.toUpperCase(),headers:ub(R.normalize()),body:c,duplex:"half",credentials:p?C:void 0});d&&(rb.forEach(pw,((e,t)=>{void 0===F[t]&&(F[t]=e)})),void 0===F.signal&&(F.signal=null),void 0===F.body&&(F.body=null)),0===b&&(F.redirect="manual",v&&(v.redirect="manual")),P=d&&new s(i,F);let B=await(d?N(P,v):N(i,F));const j=gb.from(B.headers);if(O){const t=rb.toFiniteNumber(j.getContentLength());if(null!=t&&t>y)throw new Ib("maxContentLength size of "+y+" exceeded",Ib.ERR_BAD_RESPONSE,e,P)}const G=E&&("stream"===T||"response"===T);if(E&&B.body&&(S||O||G&&L)){const t={};["status","statusText","headers"].forEach((e=>{t[e]=B[e]}));const i=rb.toFiniteNumber(j.getContentLength()),n=HI(S&&bO(i,AO(OO(S),!0))||[],2),r=n[0],o=n[1];let s=0;const c=t=>{if(O&&(s=t,s>y))throw new Ib("maxContentLength size of "+y+" exceeded",Ib.ERR_BAD_RESPONSE,e,P);r&&r(t)};B=new a(ow(B.body,65536,c,(()=>{o&&o(),L&&L()})),t)}T=T||"text";let W=await f[rb.findKey(f,T)||"text"](B,e);if(O&&!E&&!G){let t;if(null!=W&&("number"==typeof W.byteLength?t=W.byteLength:"number"==typeof W.size?t=W.size:"string"==typeof W&&(t="function"==typeof n?(new n).encode(W).byteLength:W.length)),"number"==typeof t&&t>y)throw new Ib("maxContentLength size of "+y+" exceeded",Ib.ERR_BAD_RESPONSE,e,P)}return!G&&L&&L(),await new cp(((t,i)=>{vO(t,i,{data:W,headers:gb.from(B.headers),status:B.status,statusText:B.statusText,config:e,request:P})}))}catch(t){if(L&&L(),D&&D.aborted&&D.reason instanceof Ib){const i=D.reason;throw i.config=e,P&&(i.request=P),t!==i&&Object.defineProperty(i,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),i}if(M)throw P&&!M.request&&(M.request=P),M;if(t instanceof Ib)throw P&&!t.request&&(t.request=P),t;if(t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message)){const i=new Ib("Network Error",Ib.ERR_NETWORK,e,P,t&&t.response);throw Object.defineProperty(i,"cause",{__proto__:null,value:t.cause||t,writable:!0,enumerable:!1,configurable:!0}),i}throw Ib.from(t,t&&t.code,e,P,t&&t.response)}var V,x}},Sw=new Map,gw=e=>{let t=e&&e.env||{};const i=t.fetch,n=[t.Request,t.Response,i];let r,o,s=n.length,a=Sw;for(;s--;)r=n[s],o=a.get(r),void 0===o&&a.set(r,o=s?new Map:mw(t)),a=o;return o};gw();const Tw={http:null,xhr:WO,fetch:{get:gw}};rb.forEach(Tw,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(e){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}}));const Rw=e=>"- ".concat(e),vw=e=>rb.isFunction(e)||null===e||!1===e;var Cw={getAdapter:function(e,t){const i=(e=rb.isArray(e)?e:[e]).length;let n,r;const o={};for(let s=0;s<i;s++){let i;if(n=e[s],r=n,!vw(n)&&(r=Tw[(i=String(n)).toLowerCase()],void 0===r))throw new Ib("Unknown adapter '".concat(i,"'"));if(r&&(rb.isFunction(r)||(r=r.get(t))))break;o[i||"#"+s]=r}if(!r){const e=Object.entries(o).map((e=>{let t=HI(e,2),i=t[0],n=t[1];return"adapter ".concat(i," ")+(!1===n?"is not supported by the environment":"is not available in the build")}));let t=i?e.length>1?"since :\n"+e.map(Rw).join("\n"):" "+Rw(e[0]):"as no adapter specified";throw new Ib("There is no suitable adapter to dispatch the request "+t,Ib.ERR_NOT_SUPPORT)}return r},adapters:Tw};function Iw(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new RO(null,e)}function yw(e){const t=rb.toSafeFlatObject(e);Iw(t),t.headers=gb.from(rb.getSafeProp(t,"headers")),t.data=gO.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1);return Cw.getAdapter(t.adapter||SO.adapter,t)(t).then((function(e){Iw(t),t.response=e;try{e.data=gO.call(t,t.transformResponse,e)}finally{delete t.response}return e.headers=gb.from(e.headers),e}),(function(e){if(!TO(e)&&(Iw(t),e&&e.response)){t.response=e.response;try{e.response.data=gO.call(t,t.transformResponse,e.response)}finally{delete t.response}e.response.headers=gb.from(e.response.headers)}return cp.reject(e)}))}const Aw={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Aw[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const bw={};Aw.transitional=function(e,t,i){function n(e,t){return"[Axios v"+hw+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,r,o)=>{if(!1===e)throw new Ib(n(r," has been removed"+(t?" in "+t:"")),Ib.ERR_DEPRECATED);return t&&!bw[r]&&(bw[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,o)}},Aw.spelling=function(e){return(t,i)=>(console.warn("".concat(i," is likely a misspelling of ").concat(e)),!0)};var Ow={assertOptions:function(e,t,i){if("object"!=typeof e||null===e)throw new Ib("options must be an object",Ib.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-- >0;){const o=n[r],s=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(s){const t=e[o],i=void 0===t||s(t,o,e);if(!0!==i)throw new Ib("option "+o+" must be "+i,Ib.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new Ib("Unknown option "+o,Ib.ERR_BAD_OPTION)}},validators:Aw};const ww=Ow.validators;let Nw=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Bb,response:new Bb}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error)try{let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const i=t.stack;let n="";if("string"==typeof i){const e=i.indexOf("\n");n=-1===e?"":i.slice(e+1)}if(e.stack){if(n){const t=n.indexOf("\n"),i=-1===t?-1:n.indexOf("\n",t+1),r=-1===i?"":n.slice(i+1);String(e.stack).endsWith(r)||(e.stack+="\n"+n)}}else e.stack=n}catch(e){}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};const i=t=FO(this.defaults,t),n=i.transitional,r=i.paramsSerializer,o=i.headers;void 0!==n&&Ow.assertOptions(n,{silentJSONParsing:ww.transitional(ww.boolean),forcedJSONParsing:ww.transitional(ww.boolean),clarifyTimeoutError:ww.transitional(ww.boolean),legacyInterceptorReqResOrdering:ww.transitional(ww.boolean),advertiseZstdAcceptEncoding:ww.transitional(ww.boolean),validateStatusUndefinedResolves:ww.transitional(ww.boolean)},!1),null!=r&&(rb.isFunction(r)?t.paramsSerializer={serialize:r}:Ow.assertOptions(r,{encode:ww.function,serialize:ww.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ow.assertOptions(t,{baseUrl:ww.spelling("baseURL"),withXsrfToken:ww.spelling("withXSRFToken")},!0),t.method=(rb.getSafeProp(t,"method")||rb.getSafeProp(this.defaults,"method")||"get").toLowerCase();let s=o&&rb.merge(o.common,o[t.method]);o&&rb.forEach(EO.concat("common"),(e=>{delete o[e]})),t.headers=gb.concat(s,o);const a=[];let c=!0;this.interceptors.request.forEach((function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;c=c&&e.synchronous;const i=t.transitional||jb;i&&i.legacyInterceptorReqResOrdering?a.unshift(e.fulfilled,e.rejected):a.push(e.fulfilled,e.rejected)}));const d=[];let l;this.interceptors.response.forEach((function(e){d.push(e.fulfilled,e.rejected)}));let u,h=0;if(!c){const e=[yw.bind(this),void 0];for(e.unshift(...a),e.push(...d),u=e.length,l=cp.resolve(t);h<u;)l=l.then(e[h++],e[h++]);return l}u=a.length;let p=t;for(;h<u;){const e=a[h++],t=a[h++];try{p=e?e(p):p}catch(e){if(!t){l=cp.reject(e);break}try{const i=t.call(this,e);rb.isThenable(i)&&(l=cp.resolve(i).then((()=>yw.call(this,p))))}catch(e){l=cp.reject(e)}break}}if(!l)try{l=yw.call(this,p)}catch(e){l=cp.reject(e)}for(h=0,u=d.length;h<u;)l=l.then(d[h++],d[h++]);return l}getUri(e){return Mb(kO((e=FO(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls,e),e.params,e.paramsSerializer)}};rb.forEach(["delete","get","head","options"],(function(e){Nw.prototype[e]=function(t,i){return this.request(FO(i||{},{method:e,url:t,data:i&&rb.hasOwnProp(i,"data")?i.data:void 0}))}})),rb.forEach(["post","put","patch","query"],(function(e){function t(t){return function(i,n,r){return this.request(FO(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}Nw.prototype[e]=t(),"query"!==e&&(Nw.prototype[e+"Form"]=t(!0))}));var Dw=Nw;class Pw{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new cp((function(e){t=e}));const i=this;this.promise.then((e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new cp((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new RO(e,n,r),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}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 Pw((function(t){e=t}));return{token:t,cancel:e}}}var Lw=Pw;const kw={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(kw).forEach((e=>{let t=HI(e,2),i=t[0],n=t[1];void 0===kw[n]&&(kw[n]=i)}));var Mw=kw;const Uw=function e(t){const i=new Dw(t),n=oA(Dw.prototype.request,i);return rb.extend(n,Dw.prototype,i,{allOwnKeys:!0}),rb.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(FO(t,i))},n}(SO);Uw.Axios=Dw,Uw.CanceledError=RO,Uw.CancelToken=Lw,Uw.isCancel=TO,Uw.VERSION=hw,Uw.toFormData=Nb,Uw.AxiosError=Ib,Uw.Cancel=Uw.CanceledError,Uw.all=function(e){return cp.all(e)},Uw.spread=function(e){return function(t){return e.apply(null,t)}},Uw.isAxiosError=function(e){return rb.isObject(e)&&!0===e.isAxiosError},Uw.mergeConfig=FO,Uw.AxiosHeaders=gb,Uw.formToJSON=e=>_O(rb.isHTMLForm(e)?new FormData(e):e),Uw.getAdapter=Cw.getAdapter,Uw.HttpStatusCode=Mw,Uw.default=Uw;var Vw=Uw;Vw.Axios,Vw.AxiosError,Vw.CanceledError,Vw.isCancel,Vw.CancelToken,Vw.VERSION,Vw.all,Vw.Cancel,Vw.isAxiosError,Vw.spread,Vw.toFormData,Vw.AxiosHeaders,Vw.HttpStatusCode,Vw.formToJSON,Vw.getAdapter,Vw.mergeConfig,Vw.create;const xw=()=>{};function Fw(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:xw};return e.promise=new cp(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const Bw=new Map,jw=new Map,Gw=new Map;let Ww=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}({}),Hw=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 Kw=new Uy;let Yw=Kw.getResult(),qw=null;function Jw(e){if(!qw){e&&Kw.setUA(e),Yw=Kw.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return Hw.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return Hw.CHROME;case"Safari":case"Mobile Safari":return Hw.SAFARI;case"Edge":return Hw.EDGE;case"Firefox":return Hw.FIREFOX;case"QQ":case"QQBrowser":return Hw.QQ;case"Opera":return Hw.OPERA;case"WeChat":return Hw.WECHAT;default:return e.browser.name||""}}(Yw),i=zw(Yw),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(Yw),r=Yw.os.version,o=zw(Yw,!1),s=Yw.device.type;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s};qw={name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s}}return qw}function zw(e){let t,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",i?t.split(".")[0]:t}function Xw(){return Jw().os}function Qw(){const e=Jw();return"".concat(e.os," ").concat(e.osVersion)}function $w(){const e=Jw();return!!("WebKit"===Yw.engine.name&&e.os===Ww.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Hw.SAFARI||oN()&&e.name!==Hw.SAFARI)}function Zw(){return"WebKit"===Yw.engine.name}function eN(){return Jw().name===Hw.CHROME}function tN(){return Jw().name===Hw.SAFARI}function iN(){const e=Jw();if(e.name!==Hw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}function nN(){return Jw().name===Hw.EDGE}function rN(){return Jw().name===Hw.FIREFOX}function oN(){return Jw().os===Ww.IOS}function sN(e){const t=Jw();return!(t.name!==Hw.CHROME||!t.osVersion)&&Number(t.version)>=e}function aN(e){const t=Jw();return!(t.name!==Hw.CHROME||!t.osVersion)&&Number(t.version)<e}function cN(e,t,i){const n=Jw();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}function dN(e){const t=Jw();return!(t.name!==Hw.EDGE||!t.osVersion)&&Number(t.version)>=e}function lN(e){const t=Jw();return!(t.name!==Hw.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function uN(e){const t=Jw();return!(t.name!==Hw.SAFARI||!t.osVersion)&&Number(t.version)>=e}function hN(e,t,i){const n=Jw();if(n.os!==Ww.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])>t||Number(r[0])>e:t?Number(r[0])===e&&Number(r[1])>=t||Number(r[0])>e:Number(r[0])>=e}function pN(e,t,i){const n=Jw();if(n.os!==Ww.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function _N(e,t,i){const n=Jw();if(n.name!==Hw.SAFARI||!n.osVersion||!n.browserVersion)return!1;const r=n.browserVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function EN(e){const t=Jw();return!(t.name!==Hw.OPERA||!t.osVersion)&&Number(t.version)>=e}function fN(){const e=Jw();if(e.os!==Ww.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function mN(){const e=Jw();if(e.os!==Ww.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function SN(){const e=Jw();if(e.os!==Ww.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function gN(){const e=Jw();if(e.os!==Ww.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function TN(){return tN()&&navigator.maxTouchPoints>0}function RN(){return Jw().name===Hw.WECHAT}function vN(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function CN(){const e=Xw();return function(){const e=Jw().deviceType;return"mobile"===e||"tablet"===e}()||e===Ww.ANDROID||e===Ww.IOS||e===Ww.HARMONY_OS}function IN(){const e=Jw();return e.name!==Hw.EDGE&&e.name!==Hw.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function yN(){return Xw()===Ww.ANDROID}function AN(){const e=Jw();return yN()&&(e.name===Hw.CHROME||e.name===Hw.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function bN(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function ON(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function wN(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function NN(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?wN(Object(i),!0).forEach((function(t){ON(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):wN(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function DN(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,o,s,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=o.call(i)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return bN(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?bN(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}let PN=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}({}),LN=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),ON(this,"code",void 0),ON(this,"message",void 0),ON(this,"data",void 0),ON(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"".concat(this.message,"\ndata: ").concat(JSON.stringify(this.data)):this.message}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function kN(e,t){if("boolean"!=typeof e)throw new LN(PN.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function MN(e,t,i){if(!Un(i).call(i,e))throw new LN(PN.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function UN(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<i||e>n||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new LN(PN.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function VN(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new LN(PN.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&UN(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&UN(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&UN(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&UN(e.ideal,"".concat(t,".ideal"),1,1/0)}else UN(e,t,1,1/0)}function xN(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new LN(PN.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!jN(e,i,n,r))throw new LN(PN.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function FN(e,t){if(!Array.isArray(e))throw new LN(PN.INVALID_PARAMS,"".concat(t," should be an array"))}function BN(e){return null==e}function jN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return!1}return!0}(e))}var GN=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(GN||{}),WN=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(WN||{});const HN=new class{constructor(){ON(this,"_clientSize",null),ON(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),ON(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),ON(this,"getStyle",(e=>window.getComputedStyle(e,null))),ON(this,"checkCssVisibleProperty",(e=>{var t;let i=!0;const n=this.getStyle(e),r=n.display,o=n.visibility,s=n.opacity,a=n.filter;return("none"===r||Un(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter((e=>{var t;const i=e.split("(")[0];return Un(t=["brightness","blur","opacity"]).call(t,i)})).map((e=>{const t=DN(e.split(/\(|\)/),2),i=t[0],n=t[1];return[i,Number(n.match(/^[0-9\.]+/))]})).forEach((e=>{const t=DN(e,2),n=t[0],r=t[1];switch(n){case"brightness":(r<.1||r>3)&&(i=!1);break;case"blur":r>3&&(i=!1);break;case"opacity":r<.1&&(i=!1)}})),i)})),ON(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let i=!0,n=!0;const r=e=>t(e);let o=e;for(;o&&n;)r(o)||(i=!1,n=!1),o=o.parentElement,o||(n=!1);return i})),ON(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),ON(this,"getSizeAboutClient",(e=>{const t=e.getBoundingClientRect(),i=t.width,n=t.height,r=t.left,o=t.right,s=t.top,a=t.bottom,c=this.getClientWidth(),d=this.getClientHeight();return{width:i,height:n,left:r,right:o,top:s,bottom:a,clientWidth:c,clientHeight:d,clientMin:Math.min(c,d)}})),ON(this,"checkActualSize",(()=>{const e=this._clientSize,t=e.width,i=e.height,n=e.clientMin;return this.checkSizeIsVisible(t,i,n)})),ON(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),ON(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),ON(this,"getPointPositionList",(()=>{const e=this._clientSize,t=e.width,i=e.height,n=e.left,r=e.top,o=t/6,s=i/6,a=[],c=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const i=(n*c+(0===e?.1:4===e?(o*e*c-1e5)/c:o*e)*c)/c,d=(r*c+(0===t?.1:4===t?(s*t*c-1e5)/c:s*t)*c)/c;a.push({x:i,y:d})}return[...a]})),ON(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),ON(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),ON(this,"checkSizeOfPartInClient",(()=>{const e=this._clientSize,t=e.left,i=e.right,n=e.top,r=e.bottom,o=e.clientHeight,s=e.clientWidth,a=e.clientMin;let c,d,l,u;if(t<0)c=0;else{if(!(t<s))return!1;c=t}if(i<0)return!1;if(d=i<s?i:s,n<0)l=0;else{if(!(n<o))return!1;l=n}if(r<0)return!1;u=r<o?r:o;const h=d-c,p=u-l;return this.checkSizeIsVisible(h,p,a)})),ON(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),ON(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(GN.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(GN.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(GN.SIZE)}}return this.returnHiddenResult(GN.STYLE)}return this.returnHiddenResult(WN.UNMOUNTED)}return this.returnHiddenResult(WN.INVALID_HTML_ELEMENT)})),ON(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function KN(e){return(new TextEncoder).encode(e)}const YN=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i};const qN=async e=>function(e,t){let i="";return new Uint8Array(e).forEach((e=>{i+=e.toString(t).padStart(2,"0")})),i}(await crypto.subtle.digest("SHA-256",KN(e)),16);let JN=class{constructor(){ON(this,"_events",{}),ON(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[])}}safeEmit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}};let zN=null;function XN(){if(zN)return zN;if(window.electron)return zN=window.electron;if(!window.require)return null;try{return zN=window.require("electron"),zN}catch(e){return null}}let QN=function(e){return e.CREATE_CLIENT="createClient",e.CREATE_CLIENT_PRECONNECT="createClientPreconnect",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}({}),$N=function(e){return e.TRACER="tracer",e}({});function ZN(e){return UN(e.timeout,"config.timeout",0,1e5),UN(e.timeoutFactor,"config.timeoutFactor",0,100,!1),UN(e.maxRetryCount,"config.maxRetryConfig",0,1/0),UN(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let eD=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}({}),tD=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 iD(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 nD(e){return xN(e.turnServerURL,"turnServerURL"),xN(e.username,"username"),xN(e.password,"password"),e.udpport&&UN(e.udpport,"udpport",1,99999,!0),e.forceturn&&kN(e.forceturn,"forceturn"),e.security&&kN(e.security,"security"),e.tcpport&&UN(e.tcpport,"tcpport",1,99999,!0),!0}let rD=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 oD(e){return void 0!==e.level&&MN(e.level,"level",[1,2,3]),void 0!==e.delay&&UN(e.delay,"delay",0,3e3,!0),!0}let sD=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}({}),aD=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}),cD=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}({}),dD=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),lD=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function uD(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?cp.reject(new LN(PN.UNEXPECTED_ERROR,"can not emit promise")):new cp(((i,r)=>{e.emit(t,...n,i,r)}))}function hD(e,t){if(0===e.getListeners(t).length)return cp.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return uD(e,t,...n)}function pD(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return _D(e,t,...n)}function _D(e,t){let i=null,n=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,(e=>{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new LN(PN.UNEXPECTED_ERROR,"handler is not sync");return i}const ED=new class extends JN{set networkState(e){this.emit(lD.NETWORK_STATE_CHANGE,e,this._networkState),e===dD.ONLINE?this.emit(lD.ONLINE):e===dD.OFFLINE&&(this.onlineWaiter=new cp((e=>{this.once(lD.ONLINE,(()=>{this.onlineWaiter=void 0,e(dD.ONLINE)}))})),this.emit(lD.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===dD.ONLINE}constructor(){super(),ON(this,"_moduleName","network-indicator"),ON(this,"_networkState",dD.ONLINE),ON(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=dD.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=dD.OFFLINE}))}},fD=[];for(let e=0;e<256;++e)fD.push((e+256).toString(16).slice(1));const mD="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let SD;const gD=new Uint8Array(16);function TD(){return mD?mD():function(e,t,i){var n,r,o,s;const a=null!==(n=null!==(r=(e=e||{}).random)&&void 0!==r?r:null===(o=(s=e).rng)||void 0===o?void 0:o.call(s))&&void 0!==n?n:function(){if(!SD){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");SD=crypto.getRandomValues.bind(crypto)}return SD(gD)}();if(a.length<16)throw new Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((i=i||0)<0||i+16>t.length)throw new RangeError("UUID byte range ".concat(i,":").concat(i+15," is out of buffer bounds"));for(let e=0;e<16;++e)t[i+e]=a[e];return t}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(fD[e[t+0]]+fD[e[t+1]]+fD[e[t+2]]+fD[e[t+3]]+"-"+fD[e[t+4]]+fD[e[t+5]]+"-"+fD[e[t+6]]+fD[e[t+7]]+"-"+fD[e[t+8]]+fD[e[t+9]]+"-"+fD[e[t+10]]+fD[e[t+11]]+fD[e[t+12]]+fD[e[t+13]]+fD[e[t+14]]+fD[e[t+15]]).toLowerCase()}(a)}(e,t,undefined);var e,t}function RD(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function vD(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function CD(e){void 0!==cp?cp.resolve().then(e):setTimeout(e,0)}function ID(e){return JSON.parse(JSON.stringify(e))}function yD(e){try{return ID(e)}catch(t){return e}}const AD={};function bD(e,t){AD[t]||(AD[t]=!0,e())}function OD(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}function wD(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}function ND(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=sr(t).call(t,((e,t)=>e+t.length),0),r=new Uint8Array(new ArrayBuffer(n));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function DD(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function PD(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?DD(e):e.size})),t+138}function LD(e){const t=new LN(PN.TIMEOUT,"timeout");return new cp(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function kD(e){return new cp((t=>{window.setTimeout(t,e)}))}function MD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+MD(e-i.length,"")}function UD(){let e,t=!1;try{var i;e=Py(i=TD()).call(i,"-","")}catch(e){t=!0}return!t&&e&&32===e.length||(e=MD(32,"")),e.toUpperCase()}const VD=()=>{},xD=new class{constructor(){ON(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const s=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:s,args:o,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,NN(NN({},r),{},{fn:e,args:o,skipFn:n}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:o,skipFn:n})}}},FD=xD.throttleByKey.bind(xD);function BD(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function jD(e,t){if(!BD(e)||!BD(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n<t.length;n++)i[n]=jD(e[n],t[n]);return i}{const i=NN({},e);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)?i[n]=jD(e[n],t[n]):i[n]=t[n]);return i}}function GD(e,t){let i=[0];if(t&&(i=new Array(t).fill(0)),0===e)return i;let n=0;for(;e>0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i}function WD(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function HD(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function KD(e){return sr(e).call(e,((e,t)=>e+t),0)}let YD=1,qD=console,JD=class{static setLogger(e){qD=e}constructor(e,t){ON(this,"id",void 0),ON(this,"lockingPromise",cp.resolve()),ON(this,"locks",0),ON(this,"name",""),ON(this,"lockId",void 0),this.lockId=YD++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const i=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),n="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");qD.debug("".concat(i," ").concat(n))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const i=new cp((i=>{t=()=>{this.locks-=1,this.logger("unlocked",e),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}};function zD(e,t){return function(i,n,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{r()}},r}}const XD={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function QD(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function $D(e,t,i,n){const r=Object.assign({},XD,n);let o=r.timeout;const s=async()=>{await function(e){return new cp((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new cp((async(n,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new LN(PN.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await s()}catch(e){if(!i(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}}));return c.cancel=()=>a=!0,c}let ZD,eP=0,tP=0;function iP(e,t,i,n){return new cp(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),eP+=DD(t.data)):i&&(t.data.size?eP+=t.data.size:t.data instanceof FormData?eP+=PD(t.data):eP+=DD(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Vw.request(t).then((e=>{"string"==typeof e.data?tP+=DD(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?tP+=e.data.byteLength:tP+=DD(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Vw.isCancel(e)?o(new LN(PN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new LN(PN.NETWORK_TIMEOUT,e.message)):e.response?o(new LN(PN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new LN(PN.NETWORK_ERROR,e.message))}))}))}async function nP(e,t){const i=new Blob([t.data],{type:"buffer"});return await iP(e,NN(NN({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const rP=()=>void 0!==window.isSecureContext;function oP(e){if(Array.isArray(e))return e.map((e=>e));if(!sP(e))return e;const t={};for(const i in e){const n=e[i];sP(n)||Array.isArray(n)?t[i]=oP(n):t[i]=n}return t}function sP(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let aP=class{constructor(e){ON(this,"input",[]),ON(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 cP={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},dP={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:cP,remoteCandidate:cP},updateInterval:0},lP={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},uP={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},hP={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},pP={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 _P=class{constructor(e,t){ON(this,"onFirstVideoReceived",void 0),ON(this,"onFirstVideoDecoded",void 0),ON(this,"onFirstAudioReceived",void 0),ON(this,"onFirstVideoDecodedTimeout",void 0),ON(this,"onFirstAudioDecoded",void 0),ON(this,"onSelectedLocalCandidateChanged",void 0),ON(this,"onSelectedRemoteCandidateChanged",void 0),ON(this,"videoIsReady",!1),ON(this,"videoIsReady2",{}),ON(this,"pc",void 0),ON(this,"options",void 0),ON(this,"intervalTimer",void 0),ON(this,"stats",oP(dP)),ON(this,"isFirstVideoReceived",{}),ON(this,"isFirstVideoDecoded",{}),ON(this,"isFirstAudioReceived",{}),ON(this,"isFirstAudioDecoded",{}),ON(this,"isFirstVideoDecodedTimeout",{}),ON(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 cp((e=>{e({local:NN({},cP),remote:NN({},cP)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,o=0,s=0;for(const a of i)e[a].forEach(((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=n<=0||o<=0?0:o/(n+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},EP=class extends _P{constructor(){super(...arguments),ON(this,"_stats",dP),ON(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=oP(dP);const i=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(i);const n=t.find((e=>"VideoBwe"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=Un(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=oP(uP);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=oP(lP),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:NN({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=oP(pP);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=oP(hP);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 cp(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}},fP=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),mP=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}({}),SP=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}({}),gP=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 TP=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(TP||{});function RP(e,t,i,n){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:TP.kNone;if(!t)return;const o=Number(t[i]);if("number"!=typeof o)return;const s=Number(t[n]);if("number"!=typeof s)return;if(!e)return s?o/s*r:void 0;const a=Number(e[i]);if("number"!=typeof a)return;const c=Number(e[n]);if("number"!=typeof c)return;const d=s-c;return d?(o-a)/d*r:void 0}let vP=class extends _P{constructor(){super(...arguments),ON(this,"_stats",dP),ON(this,"report",void 0),ON(this,"lastDecodeVideoReceiverStats",new Map),ON(this,"lastVideoFramesRecv",new Map),ON(this,"lastVideoFramesSent",new Map),ON(this,"lastVideoFramesDecode",new Map),ON(this,"lastVideoFramesOutput",new Map),ON(this,"lastVideoJBDelay",new Map),ON(this,"lastAudioJBDelay",new Map),ON(this,"mediaBytesSent",new Map),ON(this,"mediaBytesRetransmit",new Map),ON(this,"mediaBytesTargetEncode",new Map),ON(this,"lastDecodeAudioReceiverStats",new Map),ON(this,"lastAudioConcealment",new Map),ON(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=oP(dP),this.report.forEach((e=>{switch(e.type){case gP.OUTBOUND:case gP.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===gP.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===gP.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case gP.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case gP.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:NN({},cP),remote:NN({},cP)};return e.forEach((i=>{let n;if(i.type===gP.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===gP.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r)}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===gP.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===gP.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===gP.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(NN({},t),NN({},this.stats.selectedCandidatePair.localCandidate)),e.type===gP.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(NN({},t),NN({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=oP(pP),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const i=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=RP(i,t,"totalProcessingDelay","jitterBufferEmittedCount",TP.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,i,e),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,NN({},t))}calculateAudioFreeze(e,t,i){const n=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=n){const r=n.lts,o=i.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=n.nonSilent+a,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;const l=80*d/s,u=200*d/s,h=s/d;let p=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>l&&(n.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*h)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*h)),p=n.plc80+1);let _=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>u&&(n.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*h)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*h)),_=n.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:_})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:i.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=oP(lP),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,r=o-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<n.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(i.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=RP(null==i?void 0:i.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=RP(null==i?void 0:i.stats,t,"totalProcessingDelay","framesDecodeCount",TP.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=RP(null==i?void 0:i.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",TP.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=RP(null==i?void 0:i.stats,t,"totalInterFrameDelay","framesDecodeCount",TP.kMillisecondsFromSeconds),n&&o-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"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:NN({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=oP(uP),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new aP(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 aP(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 aP(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"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 i=this.findRemoteStatsId(e.ssrc,gP.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=oP(hP),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,gP.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var i;const n=Array.from(mp(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,i){var n,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,o,s,a,c,d,l,u;const h=t?this.report.get(t):void 0,p=null!==(n=null==h?void 0:h.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,_=null!==(r=null==h?void 0:h.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,E=null!==(o=null==h?void 0:h.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,f=null!==(s=null==h?void 0:h.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,m=null!==(a=null==h?void 0:h.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,S=null!==(c=null==h?void 0:h.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,g=null!==(d=null==h?void 0:h.concealedSamples)&&void 0!==d?d:e.concealedSamples,T=null!==(l=null==h?void 0:h.silentConcealedSamples)&&void 0!==l?l:e.silentConcealedSamples,R=null!==(u=null==h?void 0:h.concealmentEvents)&&void 0!==u?u:e.concealmentEvents;if("number"==typeof _&&(i.totalSamplesReceived=_),"number"==typeof T&&(i.silentConcealedSamples=T),"number"==typeof R&&(i.concealmentEvents=R),"number"==typeof g&&(i.concealedSamples=g),p&&_&&(i.accelerateRate=p/_),E&&f){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=f-e.jitterBufferEmittedCount;n>0&&(t=1e3*(E-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:f,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=m;let v=1920;S&&_&&(v=_/S/50,i.receivedFrames=Math.round(_/v)),g&&(i.droppedFrames=Math.round(g/v))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}},CP=class extends _P{updateStats(){return cp.resolve()}};function IP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return o?o<76?new EP(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new vP(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof cp||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new vP(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new CP(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}const yP="websdk_ng_install_id";function AP(){try{if(VP("INSTALL_ID"))return VP("INSTALL_ID");let e=window.localStorage.getItem(yP);return e||(e=UD(),window.localStorage.setItem(yP,e)),UP("INSTALL_ID",e),e}catch(e){return}}const bP=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}return"4.0.0.999"}("4.24.9"),OP=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let wP=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const NP=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=n,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=NP;const DP={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:!0,ENABLE_INSTANT_VIDEO:!0,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_AP_COMPRESS:!0},PP={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},LP="v4.24.9-0-g2319458dd(10/13/2026, 12:41:26 PM)",kP={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,ENABLE_CREATE_CLIENT_PRECONNECT:!0,CREATE_CLIENT_PRECONNECT_MODE:"report",CREATE_CLIENT_PRECONNECT_KEEPALIVE:!1,CREATE_CLIENT_PRECONNECT_INTERVAL_MS:55e3,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,ENABLE_DECODE_RECOVERY:!1,DECODE_RECOVERY_MAX_ATTEMPTS:5,DECODE_RECOVERY_BASE_INTERVAL:1e4,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,ENABLE_ICE_EARLY_JOIN:!0,ENABLE_DUAL_STREAM_RESOLUTION_CORRECTION:!0},MP=NN(NN(NN(NN({},kP),{},{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:["sdp-ap-web-1.rtnsvc.com","sdp-ap-web-1.rtesvc.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,ENABLE_WECHAT_AUTOPLAY_RECOVERY:!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:PP,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},DP),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,AP_REQUEST_DETAIL_EXTEND: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:!0,FLEXIBLE_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_JOIN_V4:!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 UP(e,t,i){var n,r,o;Un(n=Object.keys(MP)).call(n,e)&&(!i&&Un(r=Object.keys(FP)).call(r,e)||(MP[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(MP.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,MP.USE_NEW_NETWORK_CONFIG=o,o&&(MP.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],MP.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],MP.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],MP.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],MP.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",MP.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",MP.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(MP.ENABLE_INSTANT_VIDEO=!0,MP.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(MP.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(MP.NEW_TURN_MODE||(MP.NEW_TURN_MODE=4))))}function VP(e){if("TURN_DOMAINS"===e){const e=MP.TURN_DOMAINS;return Un(e).call(e,VP("TURN_DOMAIN"))?e:[VP("TURN_DOMAIN")].concat(e)}return MP[e]}OP||(MP.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],MP.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],MP.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],MP.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],MP.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],MP.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],MP.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",MP.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",MP.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",MP.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",MP.AREAS=["NORTH_AMERICA","OVERSEA"]);let xP=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const FP={};var BP=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}(BP||{});let jP=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 GP=128,WP=96,HP=1e3,KP=10;let YP=0;var qP=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>v,Printer:()=>b,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),o=" ";let s;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>="€"&&e<="ÿ"}function l(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function u(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return h(e)||a(e)||"+"===e||"/"===e}function f(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function m(e){return h(e)||a(e)||"+"===e||"/"===e}function S(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function g(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?S(Object(i),!0).forEach((function(t){T(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):S(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function T(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(s||(s={}));class R{consumeText(e,t){let i=t;for(;i<e.length;){const t=e[i];if("\0"===t||"\r"===t||t===n)break;i+=1}if(i-t==0)throw new Error("Invalid text, at ".concat(e));return i}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,i){let n=t;for(;i(e[n]);)n++;if(n-t==0)throw new Error("Invalid rule at ".concat(t,"."));return n}consumeSpace(e,t){if(e[t]===o)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let i=t;for(let t=0;t<4;t++)if(i=this.consumeDecimalUChar(e,i),3!==t){if("."!==e[i])throw new Error("Invalid IP4 address.");i++}return i}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw new Error("Invalid decimal uchar.");const n=parseInt(e.slice(t,i));if(n>=0&&n<=255)return i;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i)}return"/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n<i.length;n++){if(t+n>=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n<e.length&&("string"!=typeof i||e[n]!==i)&&("function"!=typeof i||!i(e[n]));)n++;return n}}class 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=>!!zg(e).call(e))).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:n,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===n)return"\r"===e[t-1]?r:n;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new I;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(t,(e=>l(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(e,(e=>l(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const i=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const n=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:n}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==s.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==s.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const o=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:n,nettype:r,addrtype:o,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===s.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==s.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===s.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===s.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:n}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,i+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const n=[];for(n.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,n.push(this.extract(e,this.consumeToken));if(0===n.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:n,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),i=this.parseRepeat(),n=this.parseZone();e.push({time:t,repeats:i,zones:n})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),i=this.parseInformation(),n=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:n,bandwidths:r,key:o,attributes:s})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];const o=t.call(this,e.value,e.cur,...n),s=e.value.slice(e.cur,o);return e.cur=o,s}extractOneOrMore(e,t){const i=this.consumeOneOrMore(e.value,e.cur,t),n=e.value.slice(e.cur,i);return e.cur=i,n}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class C extends R{constructor(){super(...arguments),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,i){const n=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,n),o=HI(i||[],2),s=o[0],a=o[1];if("number"==typeof s&&r.length<s)throw new Error("error in length, should be more or equal than ".concat(s," characters."));if("number"==typeof a&&r.length>a)throw new Error("error in length, should be less or equal than ".concat(a," characters."));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error("Nothing to extract from attValue.");for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];const o=t.call(this,e.attValue,e._cur,...n),s=e.attValue.slice(e._cur,o);return e._cur=o,s}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;i<t.length;i++)if(t[i]!==e.attValue[e._cur+i])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let i;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),i=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,o),r=g(g({entry:parseInt(t,10)},i&&{direction:i}),{},{extensionName:n});this.peekChar(e)===o&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class I extends C{constructor(){super(...arguments),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,f)}parseIdentity(e){const t=this.extractOneOrMore(e,m),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const n=this.extractOneOrMore(e,(e=>e!==o&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,o);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends C{constructor(e){super(),T(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach((e=>{let t=HI(e.split("="),2),i=t[0],r=t[1];i=zg(i).call(i);const o="string"==typeof r?zg(r).call(r):null;"string"==typeof i&&i.length>0&&(n[i]=o)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),n=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,"eol",r)}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new w(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class O{constructor(e){A(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class w extends O{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 O{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(o).concat(t).concat(o).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return i}printFmtp(e,t){if(!t)return"";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(o).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(o).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(o),n=t;return"trr-int"===n.type?i+="ttr-int".concat(o).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(o).concat(n.parameter),n.additional&&(i+="".concat(o).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(o).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new v).parse(e)}function P(e,t){return(new b).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(8)})();function JP(e){return qP.parse(e)}function zP(e,t){return qP.print(e,t)}var XP=tn("Array","keys"),QP=Sn,$P=Ze,ZP=l,eL=XP,tL=Array.prototype,iL={DOMTokenList:!0,NodeList:!0},nL=function(e){var t=e.keys;return e===tL||ZP(tL,e)&&t===tL.keys||$P(iL,QP(e))?eL:t},rL=i(nL);function oL(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function sL(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function aL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aL(Object(i),!0).forEach((function(t){sL(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function dL(e,t){return dL=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},dL(e,t)}function lL(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,o,s,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=o.call(i)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return oL(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?oL(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function uL(){uL=function(e,t){return new i(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function i(e,n,r){var o=RegExp(e,n);return t.set(o,r||t.get(e)),dL(o,i.prototype)}function n(e,i){var n,r=t.get(i);return sr(n=Object.keys(r)).call(n,(function(t,i){var n=r[i];if("number"==typeof n)t[i]=e[n];else{for(var o=0;void 0===e[n[o]]&&o+1<n.length;)o++;t[i]=e[n[o]]}return t}),Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dL(e,t)}(i,RegExp),i.prototype.exec=function(t){var i=e.exec.call(this,t);if(i){i.groups=n(i,this);var r=i.indices;r&&(r.groups=n(r,this))}return i},i.prototype[Symbol.replace]=function(i,r){if("string"==typeof r){var o=t.get(this);return e[Symbol.replace].call(this,i,r.replace(/\$<([^>]+)(>|$)/g,(function(e,t,i){if(""===i)return e;var n=o[t];return Array.isArray(n)?"$"+n.join("$"):"number"==typeof n?"$"+n:""})))}if("function"==typeof r){var s=this;return e[Symbol.replace].call(this,i,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(n(e,s)),r.apply(this,e)}))}return e[Symbol.replace].call(this,i,r)},uL.apply(this,arguments)}const hL=new class extends JN{constructor(){super(...arguments),sL(this,"currentUploadLogID",0)}reportLogUploadError(e){const t=e.errorRange;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};class pL{constructor(e){sL(this,"logger",void 0),sL(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}function _L(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function EL(){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 fL={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},mL=Date.now(),SL=e=>{for(const t in fL)if(Object.prototype.hasOwnProperty.call(fL,t)&&fL[t]===e)return t;return"DEFAULT"};const gL=new class{constructor(){sL(this,"proxyServerURL",void 0),sL(this,"logLevel",fL.DEBUG),sL(this,"uploadState","collecting"),sL(this,"uploadStartTimer",void 0),sL(this,"uploadLogWaitingList",[]),sL(this,"uploadLogUploadingList",[]),sL(this,"uploadErrorCount",0),sL(this,"currentLogID",0),sL(this,"url",void 0),sL(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[fL.DEBUG].concat(t);this.log.apply(this,n)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[fL.INFO].concat(t);this.log.apply(this,n)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[fL.WARNING].concat(t);this.log.apply(this,n)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[fL.ERROR].concat(t);this.log.apply(this,n)}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[fL.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){UP("UPLOAD_LOG",!0)}disableLogUpload(){UP("UPLOAD_LOG",!1),this.uploadState="collecting",void 0!==this.uploadStartTimer&&(window.clearTimeout(this.uploadStartTimer),this.uploadStartTimer=void 0),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new pL(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-mL<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-mL);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=_L()+" Agora-SDK [".concat(SL(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=_L()+" %cAgora-SDK [".concat(SL(n),"]:");let o=[];if(!VP("USE_NEW_LOG"))switch(n){case fL.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case fL.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case fL.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case fL.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-mL<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-mL);const n=Math.max(0,Math.min(4,t[0]));t[0]=_L()+" Agora-SDK [".concat(SL(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!VP("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=EL()+" Agora-SDK [".concat(SL(e),"]:"):i[0]=EL()+" Agora-SDK [".concat(SL(e),"]:");let r="";i.forEach((e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",void 0!==this.uploadStartTimer&&(window.clearTimeout(this.uploadStartTimer),this.uploadStartTimer=void 0),0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}scheduleUploadStart(){"uploading"!==this.uploadState&&void 0===this.uploadStartTimer&&(this.uploadStartTimer=window.setTimeout((()=>{this.uploadStartTimer=void 0,VP("UPLOAD_LOG")&&this.startUpload()}),5e3))}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:bP,process_id:VP("PROCESS_ID"),payload:JSON.stringify(e)};return $D((async()=>{const e=await Vw.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(VP("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(VP("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(t=>{const i={status:-1,message:t.message,errorRange:e.map((e=>e.log_item_id))};return t.response?(i.status=t.response.status,i.data=t.response.data,i.headers=t.response.headers):t.request&&(i.status=t.request.status),hL.reportLogUploadError(i),!0}),{timeout:VP("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:VP("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,VP("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),VP("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),VP("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),VP("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var TL;function RL(e){return xN(e.reportId,"params.reportId",0,100,!1),xN(e.category,"params.category",0,100,!1),xN(e.event,"params.event",0,100,!1),xN(e.label,"params.label",0,100,!1),UN(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(TL={}).FREE="free",TL.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 vL=function(e){return e[e.RECOVER=0]="RECOVER",e[e.WARNING=1]="WARNING",e[e.ERROR=2]="ERROR",e}({}),CL=function(e){return e.CONFIG_DISTRIBUTE="config-distribute-error",e}({});const IL={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let yL=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}({}),AL=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 bL=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 OL="[config-restore]",wL="websdk_ng_",NL=wL+"blocked_config_hashes",DL=wL+"api_failure_records",PL=wL+"global_parameter",LL=wL+"config_restore_state";function kL(e){var t;return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map((e=>kL(e))).join(",")+"]":"{"+t_(t=Object.keys(e)).call(t).map((t=>JSON.stringify(t)+":"+kL(e[t]))).join(",")+"}"}function ML(e){return function(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(36)}(kL(e))}function UL(){try{const e=window.localStorage.getItem(LL);if(e)return JSON.parse(e)}catch(e){}return{currentConfigHash:"",configVerified:!1}}function VL(e){try{window.localStorage.setItem(LL,JSON.stringify(e))}catch(e){}}function xL(){try{const e=window.localStorage.getItem(DL);return e?JSON.parse(e):[]}catch(e){return gL.debug("[error] ".concat(OL," error getting API failure records:"),e),[]}}function FL(){var e;return sr(e=xL()).call(e,((e,t)=>e+t.count),0)}function BL(){try{window.localStorage.removeItem(DL)}catch(e){gL.debug("[error] ".concat(OL," error clearing API failure records:"),e)}}function jL(){try{const e=FL(),t=VP("MAX_CONFIG_RETRY");if(e<t)return;const i=UL().currentConfigHash;gL.debug("[warning] ".concat(OL," restoring config due to ").concat(e," API failures")),i&&function(e){try{const t=window.localStorage.getItem(NL);let i=[];t&&(i=JSON.parse(t).configHashes);const n=[...new Set([...i,e])];window.localStorage.setItem(NL,JSON.stringify({configHashes:n,timestamp:Date.now()})),gL.debug("[warning] ".concat(OL," blocked config hash: ").concat(e))}catch(e){gL.debug("[error] ".concat(OL," error blocking config hash:"),e)}}(i),window.localStorage.removeItem(PL);const n=xL().slice(-5);(function(e,t){YL.reportAlarm(e,t)})(null,{status:vL.ERROR,type:CL.CONFIG_DISTRIBUTE,message:"Config cache cleared due to API failures",extend:{failureCount:e,maxRetry:t,blockedConfigHash:i,recentFailures:n.map((e=>({api:e.apiName,error:e.errorCode||e.errorMessage,count:e.count,lastTime:e.lastTimestamp})))}}),BL()}catch(e){gL.debug("[error] ".concat(OL," error restoring config:"),e)}}function GL(e,t){try{if(!VP("ENABLE_CONFIG_RESTORE"))return;if(t&&"AgoraRTCException"===t.name){const e=VP("CONFIG_ERROR_MONITOR");if(!Array.isArray(e)||!Un(e).call(e,t.code))return}const i=window.localStorage.getItem(PL);if(!i||i.length<20)return;if(UL().configVerified)return;const n=VP("CONFIG_RESTORE_ERROR_API");if(!Array.isArray(n)||!Un(n).call(n,e))return;let r,o;t&&(t.code&&(r=t.code),o=t.message?t.message:"string"==typeof t?t:t.toString()),function(e,t,i){try{const n=xL(),r="".concat(e,":").concat(t||""),o=n.find((e=>"".concat(e.apiName,":").concat(e.errorCode||"")===r)),s=UL().currentConfigHash;if(o)o.count++,o.lastTimestamp=Date.now(),i&&(o.errorMessage=i),s&&(o.configHash=s);else{const r=Date.now();n.push({apiName:e,errorCode:t,errorMessage:i,count:1,firstTimestamp:r,lastTimestamp:r,configHash:s||void 0})}const a=n.length>20?n.slice(-20):n;window.localStorage.setItem(DL,JSON.stringify(a))}catch(e){gL.debug("[error] ".concat(OL," error saving API failure record:"),e)}}(e,r,o);const s=FL(),a=VP("MAX_CONFIG_RETRY");gL.debug("".concat(OL," API failure count: ").concat(s,"/").concat(a,", API: ").concat(e,", Error: ").concat(r||o)),s>=a&&jL()}catch(e){}}function WL(){try{window.localStorage.removeItem(NL)}catch(e){gL.debug("[error] ".concat(OL," error resetting blocked config:"),e)}}function HL(e,t){try{return JSON.stringify(e)}catch(e){return void gL.warning("[report] failed to serialize ApiInvoke.".concat(t,": ").concat(e instanceof Error?e.message:String(e)))}}function KL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t,n,s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];let d=a;if(e.argsMap)try{d=e.argsMap(this,...a)}catch(e){gL.warning(e),d=[]}try{JSON.stringify(d)}catch(e){gL.warning("arguments for method ".concat(o,".").concat(String(i)," not serializable for apiInvoke.")),d=[]}const l=(e.report||YL).reportApiInvoke(this._sessionId||null,{id:this._clientId||(null===(t=this.store)||void 0===t?void 0:t.clientId)||this._ID,clientId:"Client"===o?this._clientId||(null===(n=this.store)||void 0===n?void 0:n.clientId):void 0,name:"".concat(o,".").concat(String(i)),options:d,tag:$N.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,a);return t instanceof cp?t.then((t=>(l.onSuccess(e.reportResult&&t),t))).catch((e=>{throw l.onError(e),e})):(l.onSuccess(e.reportResult&&t),t)}catch(e){throw l.onError(e),e}}}return n}}const YL=new class{constructor(){sL(this,"baseInfoMap",new Map),sL(this,"proxyServer",void 0),sL(this,"eventUploadTimer",void 0),sL(this,"setSessionIdTimer",void 0),sL(this,"url",void 0),sL(this,"sids",new Set),sL(this,"backupUrl",void 0),sL(this,"_appId",void 0),sL(this,"_aid",0),sL(this,"keyEventUploadPendingItems",[]),sL(this,"normalEventUploadPendingItems",[]),sL(this,"apiInvokeUploadPendingItems",[]),sL(this,"apiInvokeCount",0),sL(this,"apiInvokeLoggedCount",0),sL(this,"ltsList",[]),sL(this,"lastSendNormalEventTime",Date.now()),sL(this,"customReportCounterTimer",void 0),sL(this,"customReportCount",0),sL(this,"extApiInvoke",(async e=>{for(const t of e){const e=cL(cL({},t),{},{sid:null,invokeId:++this.apiInvokeCount,processId:VP("PROCESS_ID"),tag:$N.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),VP("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),VP("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=lL(e,2);return t[0]+t[1]})),16)||0}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!VP("SHOW_REPORT_INVOKER_LOG"),s=!!VP("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(e,i){if(a){let n="[apiInvoke-".concat(c,"]");if(t.id&&(n+="[".concat(t.id,"]")),t.name&&(n+="[".concat(t.name,"]"),t.name===QN.JOIN))return gL.info("".concat(n," ").concat(e));gL.info("".concat(n," ").concat(e),"start"===e?t.options:i||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,processId:VP("PROCESS_ID"),clientId:t.clientId,apiInvokeTime:n,options:t.options,states:t.states||null});d("start");let u=!1;kD(t.timeout).then((()=>{u||(this.sendApiInvoke(cL(cL({},l()),{},{error:PN.API_INVOKE_TIMEOUT,success:!1})),d("timeout"),GL(t.name,new LN(PN.API_INVOKE_TIMEOUT)))}));const h=new LN(PN.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(cL(cL({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return i?FD(n,t.name+"Success",i,(()=>u=!0)):n()},onError:e=>{const n=()=>{if(u)throw e;u=!0,this.sendApiInvoke(cL(cL({},l()),{},{success:!1,error:e})),GL(t.name,e),d("onFailure",e.toString())};return i?FD(n,t.name+"Error",i,(()=>u=!0)):n()}}}_send(e,t,i){this.send({type:e,data:t},i)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname,n.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:VP("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:OP?"global":"oversea",areas:VP("AREAS")&&VP("AREAS").join(",")},t.extend),o=t.stringUid,s=t.channelProfile,a=t.channelMode,c=t.isABTestSuccess,d=t.lsid,l=t.clientRole,u=Date.now(),h=cL(cL({},n),{},{eventType:yL.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:LP,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:VP("PROCESS_ID"),appType:VP("APP_TYPE"),success:!0,version:bP,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:Un(p=window.navigator.userAgent).call(p,"AgoraWebView")?42:20,clientRole:l,serviceId:VP("PROCESS_ID"),extensionID:VP("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid,installId:AP()});var p;this.send({type:AL.SESSION,data:h},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const i=t.info,n=Date.now(),r=cL(cL({},i),{},{eventType:yL.RTE_DETAIL,lts:n,success:!0,elapse:n-t.startTime,vid:void 0===i.vid?0:Number(i.vid),ua:navigator.userAgent});this.send({type:AL.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid);const r=Date.now(),o=cL(cL({},n),{},{role:t.role,eventType:yL.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:AL.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{eventType:yL.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:AL.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){var i;const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info;t.vid&&(r.vid=t.vid),r.uid=t.uid,r.cid=t.cid;const o=Date.now(),s=null!==(i=t.reportAt)&&void 0!==i?i:o,a=t.firstSuccess,c=t.addr,d=t.isProxy,l=t.iceConnectedAt,u=t.joinResponseAt,h=!0===t.succ&&"2"===t.signalChannel&&void 0!==t.reportAt&&void 0!==t.winner&&void 0!==t.winnerAt&&void 0!==l&&void 0!==u,p=t.winnerAt,_=null!=p?p:o,E=cL(cL({},t.winner?{winner:t.winner}:{}),h?{iceConnectedElapse:Math.max(l-n.startTime,0),joinResponseElapse:Math.max(u-n.startTime,0)}:{}),f=void 0===p?o-n.startTime:Math.max(_-n.startTime,0),m=cL(cL({},r),{},{eventType:yL.JOIN_GATEWAY,lts:o,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:f,eventElapse:o-t.lts,firstSuccess:a,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:AP(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:d?1:0},E),S=m.success?1:0;if(t.succ&&(n.lastJoinSuccessTime=s),c)if("1"===m.signalChannel){const e=uL(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),t=c.match(e);m.gatewayIp=t&&t.groups?t.groups.ip:"",m.gatewayPort=t&&t.groups?t.groups.port:""}else if(d){const e=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),t=c.match(/p=[0-9]{1,6}/g);m.gatewayIp=e&&e.length?e[0].split("=")[1].replace(/-/g,"."):"",m.gatewayPort=t&&t.length?t[0].split("=")[1]:""}else{const e=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),t=c.match(/(:|p=)[0-9]{1,6}/g);m.gatewayIp=e&&e.length?e[0].split("//")[1].replace(/-/g,"."):"",m.gatewayPort=t&&t.length?t[0].split(/:|p=/g)[1]:""}if(a||h)this.send({type:AL.JOIN_GATEWAY,data:m},!0);else{const e={isSuccess:S,port:m.gatewayPort};delete m.success,delete m.eventType,delete m.firstSuccess,delete m.gatewayPort,m.vid=Number(m.vid);const t=Object.assign({},m,e,{eventType:yL.REJOIN_GATEWAY});this.send({type:AL.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=cL(cL({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:AL.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{eventType:yL.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:AL.PUBLISH,data:o},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,o=Date.now(),s=cL(cL({},r),{},{eventType:yL.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:AL.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...rL(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const o=r.info,s=Date.now(),a=cL(cL({},o),{},{eventType:yL.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:AL.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=t.peerPubStatusMs-(i.lastJoinSuccessTime||r),s=cL(cL({},n),{},{elapse:r-i.startTime,eventType:yL.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:AL.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=cL(cL(cL({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((n.firstFrame||s)-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=cL(cL(cL({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:i,data:a},!0)}abTest(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:yL.AB_TEST,lts:r});this.send({type:AL.AB_TEST,data:o},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:yL.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:AL.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:yL.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:AL.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=cL(cL(cL({},o),n),{},{eventType:t,lts:s});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{eventType:yL.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:AL.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{eventType:yL.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:AL.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{eventType:yL.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:AL.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?gL.debug("reportProxyServerurl: ".concat(e)):gL.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:AL.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now();(function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return[e];e[t]="";const r=DD(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(s[s.length]=NN(NN({},e),{},{[t]:n.substring(o,c)}),o=c,a=n.charCodeAt(c)<=127?1:3);return o!==n.length-1&&(s[s.length]=NN(NN({},e),{},{[t]:n.substring(o)})),s})(cL(cL(cL({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach((e=>this.send({type:AL.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:AL.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:AL.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:AL.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>VP("CUSTOM_REPORT_LIMIT"))throw new LN(PN.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:AL.USER_ANALYTICS,data:cL(cL({sid:e},t),{},{lts:i})})));try{VP("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw gL.error("send custom report message failed",e.toString()),new LN(PN.CUSTOM_REPORT_SEND_FAILED,e.message)}}reportAlarm(e,t){const i=e?this.baseInfoMap.get(e):void 0,n=null==i?void 0:i.info,r=Date.now(),o=cL(cL(cL({},n),t),{},{vid:void 0===(null==n?void 0:n.vid)?0:Number(n.vid),elapse:i?r-i.startTime:0,eventType:yL.ALARM_STATUS_NOTIFY,lts:r,installId:AP(),processId:VP("PROCESS_ID")});this.send({type:AL.ALARM_STATUS_NOTIFY,data:o},!0)}reportCreateClientPreconnect(e){const t=Date.now(),i=VP("PROCESS_ID"),n={invokeId:++this.apiInvokeCount,process:i,sid:i.replace(/^process-/,"").replace(/-/g,""),cname:null,cid:null,uid:null,lts:t,success:!0,elapse:0,execElapse:0,apiName:QN.CREATE_CLIENT_PRECONNECT,options:JSON.stringify({targets:e.targets,mode:e.mode,origin:e.origin})};this.send({type:AL.API_INVOKE,data:n},!0)}sendApiInvoke(e){const t=VP("NOT_REPORT_EVENT");if(e.tag&&Un(t)&&Un(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const n=i.info,r=n.cname,o=n.uid,s=n.cid;let a;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof LN){const t=e.error,i=t.code,n=t.message;a=i||n||e.error.toString()}else a=e.error.toString();const c={invokeId:e.invokeId,process:e.processId||VP("PROCESS_ID"),clientId:e.clientId,sid:e.sid,cname:r,cid:s,uid:o,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?HL(e.options,"options"):void 0,execStates:e.states?HL(e.states,"states"):void 0,execResult:e.result?HL(e.result,"result"):void 0,errorCode:e.error?a:void 0,errorMsg:e.error?HL(e.error,"error"):void 0};return this.send({type:AL.API_INVOKE,data:c},!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=>{if(e)try{e.sid=t,this.sendApiInvoke(Object.assign({},e))}catch(e){gL.warning("[report] failed to flush pending ApiInvoke: ".concat(e instanceof Error?e.message:String(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>VP("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),t_(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),VP("ENABLE_EVENT_REPORT")?(i.length&&(VP("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{VP("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>VP("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-VP("NORMAL_EVENT_QUEUE_CAPACITY")),gL.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){ED.networkState===dD.OFFLINE&&await cp.race([ED.onlineWaiter,kD(2*XD.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=KN(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(AL).forEach((i=>{let n=lL(i,2),r=n[0];n[1]===e.type&&(t=bL[r])})),t})(e),o=new DataView(n);o.setUint16(0,i.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=YN(t,new Uint8Array(n)),t=YN(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(VP("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(VP("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(VP("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(VP("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await iP(n,{timeout:1e4,data:t(e),headers:cL(cL({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),n=i?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:i,aid:n};ED.networkState===dD.OFFLINE&&await cp.race([ED.onlineWaiter,kD(2*XD.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(VP("EVENT_REPORT_DOMAIN"),"&p=").concat(VP("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(VP("EVENT_REPORT_DOMAIN"),":").concat(VP("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(VP("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(VP("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(VP("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(VP("STATS_COLLECTOR_PORT")).concat(o)));try{t?await nP(s,{timeout:1e4,data:r}):await iP(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},IL);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t,i){const n=performance.getEntriesByName(e),r=n[n.length-1];r&&this.reportApiInvoke(t,{clientId:i,name:"Client.resourceTiming",options:r,tag:$N.TRACER}).onSuccess()}};hL.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=ED.networkState,YL.reportApiInvoke(null,{name:"logUploadError",options:e,tag:$N.TRACER}).onSuccess("logUploadError")}));let qL=class extends LN{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),sL(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,gL)}throw(){super.throw(gL)}};const JL={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 zL(){return JL}function XL(){return"setSinkId"in HTMLAudioElement.prototype&&(!VP("RESTRICTION_SET_PLAYBACK_DEVICE")||(eN()||nN())&&!CN())}function QL(){return!JL.supportUnifiedPlan||VP("CHROME_FORCE_PLAN_B")&&IN()}function $L(e){return!(rN()||aN(87)||QL()||!VP("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||VP("FORCE_DISABLE_AUTO_SUB")))}function ZL(e){return VP("ENABLE_INSTANT_VIDEO")?VP("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||VP("FORCE_DISABLE_AUTO_SUB"))}function ek(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function tk(){if(ek()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return sN(141)||dN(141)||EN(141)}function ik(){if(ek()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return sN(141)||dN(141)||EN(125)}let nk=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 rk(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function ok(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function sk(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function ak(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const ck={"90p":ok(160,90),"90p_1":ok(160,90),"120p":ok(160,120,15,30,65),"120p_1":ok(160,120,15,30,65),"120p_3":ok(120,120,15,30,50),"120p_4":ok(212,120),"180p":ok(320,180,15,30,140),"180p_1":ok(320,180,15,30,140),"180p_3":ok(180,180,15,30,100),"180p_4":ok(240,180,15,30,120),"240p":ok(320,240,15,40,200),"240p_1":ok(320,240,15,40,200),"240p_3":ok(240,240,15,40,140),"240p_4":ok(424,240,15,40,220),"360p":ok(640,360,15,80,400),"360p_1":ok(640,360,15,80,400),"360p_3":ok(360,360,15,80,260),"360p_4":ok(640,360,30,80,600),"360p_6":ok(360,360,30,80,400),"360p_7":ok(480,360,15,80,320),"360p_8":ok(480,360,30,80,490),"360p_9":ok(640,360,15,80,800),"360p_10":ok(640,360,24,80,800),"360p_11":ok(640,360,24,80,1e3),"480p":ok(640,480,15,100,500),"480p_1":ok(640,480,15,100,500),"480p_2":ok(640,480,30,100,1e3),"480p_3":ok(480,480,15,100,400),"480p_4":ok(640,480,30,100,750),"480p_6":ok(480,480,30,100,600),"480p_8":ok(848,480,15,100,610),"480p_9":ok(848,480,30,100,930),"480p_10":ok(640,480,10,100,400),"720p":ok(1280,720,15,120,1130),"720p_auto":ok(1280,720,30,900,3e3),"720p_1":ok(1280,720,15,120,1130),"720p_2":ok(1280,720,30,120,2e3),"720p_3":ok(1280,720,30,120,1710),"720p_5":ok(960,720,15,120,910),"720p_6":ok(960,720,30,120,1380),"1080p":ok(1920,1080,15,120,2080),"1080p_1":ok(1920,1080,15,120,2080),"1080p_2":ok(1920,1080,30,120,3e3),"1080p_3":ok(1920,1080,30,120,3150),"1080p_5":ok(1920,1080,60,120,4780),"1440p":ok(2560,1440,30,120,4850),"1440p_1":ok(2560,1440,30,120,4850),"1440p_2":ok(2560,1440,60,120,7350),"4k":ok(3840,2160,30,120,8910),"4k_1":ok(3840,2160,30,120,8910),"4k_3":ok(3840,2160,60,120,13500)},dk={auto:{},"480p":sk(640,480,5),"480p_1":sk(640,480,5),"480p_2":sk(640,480,30),"480p_3":sk(640,480,15),"720p":sk(1280,720,5),"720p_auto":ok(1280,720,30,900,3e3),"720p_1":sk(1280,720,5),"720p_2":sk(1280,720,30),"720p_3":sk(1280,720,15),"1080p":sk(1920,1080,5),"1080p_1":sk(1920,1080,5),"1080p_2":sk(1920,1080,30),"1080p_3":sk(1920,1080,15),"1440p":sk(2560,1440,15),"1440p_1":sk(2560,1440,5),"1440p_2":sk(2560,1440,30),"1440p_3":sk(2560,1440,15),"4k":sk(3840,2160,15),"4k_1":sk(3840,2160,5),"4k_2":sk(3840,2160,30),"4k_3":sk(3840,2160,15)},lk={"1SL1TL":ak(1,1),"3SL3TL":ak(3,3),"2SL3TL":ak(2,3)};function uk(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},ck[e]):e}function hk(e){return"string"==typeof e?Object.assign({},dk[e]):e}function pk(e){return"string"==typeof e?Object.assign({},lk[e]):e}const _k={speech_low_quality:rk(16e3,!1),speech_standard:rk(32e3,!1,18),music_standard:rk(48e3,!1),standard_stereo:rk(48e3,!0,56),high_quality:rk(48e3,!1,128),high_quality_stereo:rk(48e3,!0,192)};function Ek(e){return"string"==typeof e?Object.assign({},_k[e]):e}const fk=[];function mk(e){return MN(e,"mediaSource",["screen","window","application"]),!0}let Sk=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.VIDEO_RESOLUTION_UPDATED="@video_resolution_updated",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),gk=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 Tk=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),Rk=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}({}),vk=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}({}),Ck=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}({}),Ik=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}({}),yk=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}({}),Ak=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),bk=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 Ok={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},wk={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},Nk={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},Dk={uplinkNetworkQuality:0,downlinkNetworkQuality:0},Pk={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 Lk=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),kk=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),Mk=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),Uk=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),Vk=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}({}),xk=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 Fk={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};function Bk(e,t,i,n,r){var o,s,a={};return Object.keys(n).forEach((function(e){a[e]=n[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=sr(o=gr(s=i.slice()).call(s)).call(o,(function(i,n){return n(e,t,i)||i}),a),r&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(e,t,a),null):a}function jk(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function Gk(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Wk(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Hk(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Wk(Object(i),!0).forEach((function(t){Gk(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Wk(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Kk(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,o,s,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=o.call(i)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return jk(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?jk(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error"}({});class Yk extends JN{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Ck.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),Gk(this,"trackMediaType",void 0),Gk(this,"_ID",void 0),Gk(this,"_rtpTransceiver",void 0),Gk(this,"_lowRtpTransceiver",void 0),Gk(this,"_hints",[]),Gk(this,"_isClosed",!1),Gk(this,"_originMediaStreamTrack",void 0),Gk(this,"mediaStreamTrack",void 0),Gk(this,"_external",{}),this._ID=t||MD(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){Un(fk).call(fk,e)||fk.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||bD((()=>{var e;YL.reportApiInvoke(null,{name:QN.GET_MEDIA_STREAM_TRACK,options:[],tag:$N.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Tk.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=fk.indexOf(e);-1!==t&&fk.splice(t,1)}(this),this.emit(Ik.CLOSED),this.removeAllListeners(Ck.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Tk.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Ck.TRANSCEIVER_UPDATED,e,t)}}class qk extends Yk{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),Gk(this,"_enabled",!0),Gk(this,"_muted",!1),Gk(this,"_isExternalTrack",!1),Gk(this,"_isClosed",!1),Gk(this,"_enabledMutex",void 0),Gk(this,"processor",void 0),Gk(this,"_processorContext",void 0),Gk(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new JD("".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,gL.debug("[".concat(this.getTrackId(),"] close")),this.emit(Sk.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hD(this,Sk.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){gL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}stateCheck(e,t){if(gL.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),kN(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new LN(PN.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",gL);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new LN(PN.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",gL)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():cp.resolve([])}}const Jk=window.AudioContext||window.webkitAudioContext;let zk,Xk=null;const Qk=new class extends JN{constructor(){super(...arguments),Gk(this,"prevState",void 0),Gk(this,"curState",void 0),Gk(this,"currentTime",void 0),Gk(this,"currentTimeStuckAt",void 0),Gk(this,"interruptDetectorTrack",void 0),Gk(this,"onLocalAudioTrackMute",(()=>{gL.info("ios15-interruption-start"),this.emit(nk.IOS_15_16_INTERRUPTION_START)})),Gk(this,"onLocalAudioTrackUnmute",(async()=>{gL.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?gL.info("ios15-interruption-end-canceled"):(Xk&&await Xk.suspend(),this.emit(nk.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){gL.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){gL.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 $k(){if(!Xk){if(function(){if(!Jk)return void gL.error("your browser is not support web audio");gL.info("create audio context");const e=Hk({},VP("WEBAUDIO_INIT_OPTIONS"));gL.debug("audio context init option:",JSON.stringify(e)),Xk=new Jk(e),Qk.curState=Xk.state,Xk.onstatechange=()=>{Qk.prevState=Qk.curState,Qk.curState=Xk?Xk.state:void 0;const e=Qk.prevState,t=Qk.curState,i="running"===t,n="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=Jw().osVersion;(oN()||TN())&&r&&n&&(gL.info("ios".concat(a,"-interruption-start")),Qk.emit(nk.IOS_INTERRUPTION_START)),(oN()||TN())&&(o||s)&&i&&(gL.info("ios".concat(a,"-interruption-end")),Qk.emit(nk.IOS_INTERRUPTION_END)),e!==t&&Qk.emit(nk.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=Xk)||void 0===e?void 0:e.currentTime;Qk.currentTime!==t?(Qk.currentTimeStuckAt&&(gL.debug("AudioContext current time resume at ".concat(t)),Qk.currentTimeStuckAt=void 0),Qk.currentTime=t):(t!==Qk.currentTimeStuckAt&&(YL.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:$N.TRACER}).onSuccess(),gL.warning("AudioContext current time stuck at ".concat(t))),Qk.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n,r=!1,o=!1,s=!1;function a(t){"running"===e.state?c(!1):oN()||TN()?"suspended"===e.state&&(c(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(c(!0),t&&e.resume().then(d,d))}function c(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function d(){a(!1)}function l(){a(!0)}function u(){let e;try{e=i.play(),e?e.then(_,_):(i.addEventListener("playing",_),i.addEventListener("abort",_),i.addEventListener("error",_))}catch(e){_()}}function h(e){s||(i.paused?e?(p(!1),s=!0,u()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,E,{capture:!0,passive:!0}):window.removeEventListener(t,E,{capture:!0,passive:!0})}}}function _(){i.removeEventListener("playing",_),i.removeEventListener("abort",_),i.removeEventListener("error",_),s=!1,h(!1)}function E(){h(!0)}if(oN()&&VP("IOS_BG_TAG")){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=r.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,n=()=>{if(VP("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!s&&(!i.paused||!0!==o)){i.paused||i.pause();try{s=!0,u()}catch(e){s=!1}return!0}},h(!0)}return Qk.on(nk.STATE_CHANGE,(function(){a(!0)})),a(!1),n}(Xk).then((e=>{zk=e}))}(),!Xk)throw new LN(PN.NOT_SUPPORTED,"can not create audio context");return Xk}return Xk}function Zk(e){if(function(){if(null!==eM)return eM;const e=$k(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),eM=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Un(o=e._inputNodes).call(o,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,o)=>{i.call(e),n?RD(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let eM=null;function tM(e,t){let i=!1;const n=1/t;if(VP("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=$k();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(i)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+n),e(t.currentTime)};o()}return()=>{i=!0}}class iM{constructor(){Gk(this,"context",void 0),Gk(this,"analyserNode",void 0),Gk(this,"sourceNode",void 0),this.context=$k(),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||oN()||TN()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=sr(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){gL.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class nM extends JN{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),Gk(this,"outputNode",void 0),Gk(this,"outputTrack",void 0),Gk(this,"isPlayed",!1),Gk(this,"sourceNode",void 0),Gk(this,"context",void 0),Gk(this,"audioBufferNode",void 0),Gk(this,"destNode",void 0),Gk(this,"audioOutputLevel",0),Gk(this,"volumeLevelAnalyser",void 0),Gk(this,"_processedNode",void 0),Gk(this,"playNode",void 0),Gk(this,"isDestroyed",!1),Gk(this,"onNoAudioInput",void 0),Gk(this,"isNoAudioInput",!1),Gk(this,"_noAudioInputCount",0),this.context=$k(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Zk(this.outputNode),this.volumeLevelAnalyser=new iM}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(bk.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!zL().webAudioMediaStreamDest)throw new LN(PN.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&&CD((()=>{Qk.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;oN()||TN()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await kD(200),await this.checkHasAudioInput(e?e+1:1)&&n)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}}class rM extends nM{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),Gk(this,"sourceNode",void 0),Gk(this,"track",void 0),Gk(this,"clonedTrack",void 0),Gk(this,"audioElement",void 0),Gk(this,"isCurrentTrackCloned",!1),Gk(this,"isRemoteTrack",!1),Gk(this,"originVolumeLevelAnalyser",void 0),Gk(this,"rebuildWebAudio",(async()=>{if(gL.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 gL.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>gL.info("resume success"))),gL.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),Zk(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Zk(this.outputNode),this.emit(bk.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new LN(PN.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),Zk(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,gL.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Zk(t),this.originVolumeLevelAnalyser=new iM,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=Jw();t&&o.os===Ww.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(Qk.on(nk.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),Zk(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(bk.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Qk.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),gL.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));Zk(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function oM(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function sM(e,t){const i=await aM(e.mediaSource),n=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new cp(((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border:  solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e)};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(o),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{n.getSize().width>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t),r=n.sourceId,o=n.audio;return await oM(r,e,o)}async function aM(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=XN();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new LN(PN.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new cp(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new LN(PN.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const cM=new JD("safari");let dM=!1,lM=!1;async function uM(e,t){let i=0,n=null;for(;i<2;)try{n=await hM(e,t,i>0);break}catch(e){if(e instanceof LN)throw gL.error("[".concat(t,"] ").concat(e.toString())),e;const n=pM(e.name||e.code||e,e.message);if(n.code===PN.MEDIA_OPTION_INVALID){gL.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await kD(500);continue}throw gL.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new LN(PN.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function hM(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new LN(PN.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=zL(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return gL.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(XN())e.screen.sourceId?_M(r,await oM(e.screen.sourceId,e.screen,!!e.screenAudio)):_M(r,await sM(e.screen,!!e.screenAudio));else if(eN()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new LN(PN.NOT_SUPPORTED,"This browser does not support screen sharing");gL.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(s=e.screen.extensionId,a=t,new cp(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(i=>{if(!i||!i.streamId)return gL.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new LN(PN.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){gL.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new LN(PN.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,_M(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&mk(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},n=e.screen,s=n.selfBrowserSurface,a=n.surfaceSwitching,c=n.systemAudio,d=n.preferCurrentTab,l=n.windowAudio,u=n.monitorTypeSurfaces,h={selfBrowserSurface:s,surfaceSwitching:a,systemAudio:c,preferCurrentTab:d,windowAudio:l,monitorTypeSurfaces:u};!s&&delete h.selfBrowserSurface,!a&&delete h.surfaceSwitching,!c&&delete h.systemAudio,!d&&delete h.preferCurrentTab,!l&&delete h.windowAudio,!u&&delete h.monitorTypeSurfaces,gL.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:e.screenAudio,controls:h})),_M(r,await navigator.mediaDevices.getDisplayMedia(Hk({video:i,audio:e.screenAudio},h)))}else{if(!rN())throw gL.error("[".concat(t,"] This browser does not support screenSharing")),new LN(PN.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&mk(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};gL.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),_M(r,await navigator.mediaDevices.getUserMedia(i))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=VP("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=jD(c,d)}catch(e){}gL.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),Jw();let l,u=null;(tN()||oN()||$w())&&(u=await cM.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(dM=!0),c.video&&(lM=!0),_M(r,l),u&&u(),r}function pM(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new LN(PN.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new LN(PN.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new LN(PN.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new LN(PN.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new LN(PN.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new LN(PN.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return gL.error("getUserMedia unexpected error",e),new LN(PN.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function _M(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(n&&e.removeTrack(n),e.addTrack(o)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const EM=new class extends JN{get state(){return this._state}set state(e){e!==this._state&&(this.emit(Uk.STATE_CHANGE,e),this._state=e)}constructor(){super(),Gk(this,"_state",Mk.IDLE),Gk(this,"isAccessMicrophonePermission",!1),Gk(this,"isAccessCameraPermission",!1),Gk(this,"lastAccessMicrophonePermission",!1),Gk(this,"lastAccessCameraPermission",!1),Gk(this,"checkdeviceMatched",!1),Gk(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(VP("ENUMERATE_DEVICES_INTERVAL")||(yN()||Xw()===Ww.HARMONY_OS)&&IN())&&this.updateDevicesInfo()}),VP("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>gL.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new LN(PN.NOT_SUPPORTED,"enumerateDevices() not supported.");const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!i&&(o||s)){if(cM.isLocked&&(gL.debug("[device manager] wait GUM lock"),(await cM.lock())(),gL.debug("[device manager] GUM unlock")),dM&&(o=!1,this.isAccessMicrophonePermission=!0),lM&&(s=!1,this.isAccessCameraPermission=!0),gL.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=pM(e.name||e.code||e,e.message);if(t.code===PN.PERMISSION_DENIED)throw t;gL.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=pM(e.name||e.code||e,e.message);if(t.code===PN.PERMISSION_DENIED)throw t;gL.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=pM(e.name||e.code||e,e.message);if(t.code===PN.PERMISSION_DENIED)throw t;gL.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}gL.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 LN(PN.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new LN(PN.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=Mk.INITING;try{await this.updateDevicesInfo(),this.state=Mk.INITEND}catch(e){if(this.state=Mk.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 LN(PN.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw gL.warning("Device Detection functionality cannot start properly.",e.toString()),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?gL.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):gL.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):gL.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==Mk.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Uk.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(Uk.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Uk.PLAYOUT_DEVICE_CHANGED,e)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let fM=!1;const mM=new class extends JN{constructor(){super(...arguments),Gk(this,"onAutoplayFailed",void 0),Gk(this,"onAudioAutoplayFailed",void 0)}};function SM(){if(fM)return VP("FLS_AUTOPLAY_EMITS")?(mM.onAutoplayFailed&&mM.onAutoplayFailed(),mM.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),function(){try{const e=$k();"running"!==e.state&&e.resume().catch((e=>{var t;gL.warning("resume web audio context on autoplay gesture failed",(null==e||null===(t=e.toString)||void 0===t?void 0:t.call(e))||e)}))}catch(t){var e;gL.warning("create web audio context on autoplay gesture failed",(null==t||null===(e=t.toString)||void 0===e?void 0:e.call(t))||t)}}(),fM=!1,AN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};fM=!0,AN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),gL.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),mM.onAutoplayFailed?mM.onAutoplayFailed():mM.onAudioAutoplayFailed?gL.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 ."):gL.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 ."),mM.emit("autoplay-failed")}}function gM(e,t,i,n){if(!e)return;const r=YL.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=Hk(Hk({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:mM.onAutoplayFailed||mM.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});YL.send({type:AL.AUTOPLAY_FAILED,data:a},!0)}const TM=1e3,RM="RemoteTrack.wechatAutoplayRecovery",vM=new WeakSet,CM=new WeakMap;let IM;function yM(){return VP("ENABLE_WECHAT_AUTOPLAY_RECOVERY")&&yN()&&RN()}function AM(e){if(!yM())return;const t=window.WeixinJSBridge;return t?new cp(((i,n)=>{let r=!1;const o=window.setTimeout((()=>{r||(r=!0,n())}),TM),s=()=>!r&&(r=!0,window.clearTimeout(o),!0),a=e=>n(e);try{t.invoke("getNetworkType",{},(()=>{if(s())if(yM())try{cp.resolve(e()).then((()=>i()),a)}catch(e){a(e)}else n()}))}catch(e){s()&&n()}})):void 0}function bM(e,t){if(t)try{const i=YL.reportApiInvoke(t,{name:RM,options:{},tag:$N.TRACER});e.then((()=>i.onSuccess()),(()=>i.onError(function(e,t){return new LN(PN.UNEXPECTED_ERROR,e,t)}("WeChat autoplay recovery failed")))).catch((()=>{}))}catch(e){}}function OM(e,t,i,n){return e.catch((e=>{if("NotAllowedError"!==e.name)throw e;if(!i())throw e;const r=AM((()=>{if(!i())throw e;return t()}));if(!r)throw e;return bM(r,n),r.catch((t=>{throw t instanceof Error?t:e}))}))}const wM=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],NM=new class{constructor(){Gk(this,"onAutoplayFailed",void 0),Gk(this,"elementMap",new Map),Gk(this,"elementStateMap",new Map),Gk(this,"elementsNeedToResume",[]),Gk(this,"sinkIdMap",new Map),Gk(this,"elementIdMap",new WeakMap),Gk(this,"autoResumeAfterInterruption",(e=>cp.all(Array.from(this.elementMap.entries()).map((async t=>{let i=Kk(t,2),n=i[0],r=i[1];const o=this.elementStateMap.get(n),s=r.srcObject.getAudioTracks()[0],a=s&&s.readyState;if(gL.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return r.pause(),r.play();if("running"===Qk.curState)return mN()?(r.pause(),r.play()):o&&"paused"===o?r.play():void 0}}))))),Gk(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let t=Kk(e,2);t[0];let i=t[1];const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(gL.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),Qk.on(nk.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qk.on(nk.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Qk.on(nk.STATE_CHANGE,(()=>{oN()&&"suspended"===Qk.prevState&&"running"===Qk.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new LN(PN.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){var r;if(this.elementMap.has(t))return;const o=document.createElement("audio");o.autoplay=!0,o.srcObject=new MediaStream([e]),this.elementIdMap.set(o,{id:t}),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,Vk.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{o.setSinkId(s).catch((e=>{gL.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){gL.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();if(!a||!a.then)return;const c=null!==(r=function(e,t,i,n,r){var o;if(!yM())return;if((null===(o=IM)||void 0===o?void 0:o.track)!==e)return;const s=IM.recover;return OM(i,(()=>s(t)),n,r)}(e,o,a,(()=>this.elementMap.get(t)===o),n))&&void 0!==r?r:a;c.catch((e=>{n&&gM(n,"audio",e.message,t),gL.warning("audio element play warning",e.toString()),this.elementMap.get(t)===o&&"NotAllowedError"===e.name&&(gL.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(o),CD((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),SM()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);-1!==i&&this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}reuseTrackId(e,t){if(e===t)return;const i=this.elementMap.get(e);if(!i)return;this.elementMap.has(t)&&this.stop(t),this.elementMap.delete(e),this.elementMap.set(t,i);const n=this.elementStateMap.get(e);this.elementStateMap.delete(e),void 0!==n&&this.elementStateMap.set(t,n);const r=this.sinkIdMap.get(e);void 0!==r&&(this.sinkIdMap.delete(e),this.sinkIdMap.set(t,r));const o=this.elementIdMap.get(i);o&&(o.id=t)}bindAudioElementEvents(e,t){wM.forEach((i=>{t.addEventListener(i,(i=>{var n,r;const o=null!==(n=null===(r=this.elementIdMap.get(t))||void 0===r?void 0:r.id)&&void 0!==n?n:e,s=this.elementStateMap.get(o),a="pause"===i.type?"paused":i.type;if(gL.debug("[".concat(o,"] audio-element-status change ").concat(s," => ").concat(a)),"error"===i.type){const e=null==t?void 0:t.error;e&&gL.error("[".concat(o,"] media error, code: ").concat(e.code,", message: ").concat(e.message))}this.elementStateMap.set(o,a)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{gL.debug("Auto resume audio element success")})).catch((e=>{gL.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new cp((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{AN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function DM(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new LN(PN.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",gL);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof cp?new cp(((e,t)=>{r.then(e).catch(t)})):r}),i}}class PM extends JN{constructor(e){super(),Gk(this,"name","VideoProcessorDestination"),Gk(this,"ID","0"),Gk(this,"_source",void 0),Gk(this,"videoContext",void 0),Gk(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new LN(PN.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new LN(PN.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(Lk.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Lk.ON_TRACK,void 0)}}class LM extends JN{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),Gk(this,"constraintsMap",new Map),Gk(this,"statsRegistry",[]),Gk(this,"usageRegistry",[]),Gk(this,"trackId",void 0),Gk(this,"direction",void 0),Gk(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await uD(this,kk.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return gL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),hD(this,kk.REQUEST_UPDATE_CONSTRAINTS,Array.from(mp(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return gL.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),hD(this,kk.REQUEST_UPDATE_CONSTRAINTS,Array.from(mp(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const i=t.processorID,n=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:n,type:r,stats:t})}catch(e){gL.error(new LN(PN.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof cp&&(t=await t),e.push(Hk(Hk({},t),{},{direction:this.direction}))}catch(e){gL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class kM extends JN{constructor(e){super(),Gk(this,"name","AudioProcessorDestination"),Gk(this,"ID","0"),Gk(this,"inputTrack",void 0),Gk(this,"inputNode",void 0),Gk(this,"audioProcessorContext",void 0),Gk(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new LN(PN.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new LN(PN.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(Lk.ON_TRACK,void 0),this.emit(Lk.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(Lk.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Lk.ON_NODE,this.inputNode))}}class MM extends JN{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),Gk(this,"constraintsMap",new Map),Gk(this,"statsRegistry",[]),Gk(this,"audioContext",void 0),Gk(this,"trackId",void 0),Gk(this,"direction",void 0),Gk(this,"usageRegistry",[]),Gk(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return uD(this,kk.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return gL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),hD(this,kk.REQUEST_UPDATE_CONSTRAINTS,Array.from(mp(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),hD(this,kk.REQUEST_UPDATE_CONSTRAINTS,Array.from(mp(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const i=t.processorID,n=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:n,type:r,stats:t})}catch(e){gL.error(new LN(PN.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof cp&&(t=await t),e.push(Hk(Hk({},t),{},{direction:this.direction}))}catch(e){gL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class UM extends JN{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),Gk(this,"context",void 0),Gk(this,"processSourceNode",void 0),Gk(this,"outputTrack",void 0),Gk(this,"processedNode",void 0),Gk(this,"clonedTrack",void 0),Gk(this,"outputNode",void 0),this.outputNode=new VM}setVolume(){}createOutputTrack(){throw new LN(PN.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class VM{disconnect(){}connect(){}}function xM(e){return new cp(((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=oN()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&rN()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(VD),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function FM(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=uk(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!vN()&&i.frameRate&&(t.frameRate=i.frameRate),nN()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),rN()&&(t.frameRate={ideal:30,max:30}),t}function BM(e){const t={};return vN()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,eN()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function jM(e){const t=BM(e);if(e.encoderConfig){const i=Ek(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),yN()&&(t.sampleRate=void 0),t}const GM=e=>{const t=e._encoderConfig;if(!t)return;const i=e.getMediaStreamTrackSettings(),n=i.frameRate,r=i.width,o=i.height;let s=t.frameRate,a=void 0===s?n:s,c=t.width,d=void 0===c?r:c,l=t.height,u=void 0===l?o:l;if(!a||!d||!u)return;d=WD(d),u=WD(u),a=WD(a);const h=function(e,t,i){const n=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(n),max:Math.floor(4*n)}}(d,u,a),p=h.max,_=h.min,E=t||{},f=E.bitrateMax,m=E.bitrateMin,S=E.minDownscaleWidth,g=E.minDownscaleHeight;f||gL.debug("calculate bitrate: [w: ".concat(d,", h: ").concat(u,", fps: ").concat(a,"] => [brMax: ").concat(f,", brMin: ").concat(m,"]"));const T=VP("ENCODER_CONFIG_LIMIT").maxFramerate;return T&&"number"==typeof T&&(a=Math.min(a,T)),{width:d,height:u,frameRate:a,bitrateMax:f||p,bitrateMin:m||_,scaleResolutionDownBy:1,scale:0,minDownscaleWidth:S,minDownscaleHeight:g}},WM=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new cp(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await HM(e);i({buffer:n,width:t.width,height:t.height})}else n(new LN(PN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},HM=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var KM,YM,qM,JM,zM,XM,QM,$M,ZM,eU,tU,iU,nU,rU,oU,sU,aU,cU,dU,lU,uU,hU,pU,_U,EU,fU,mU,SU,gU,TU,RU,vU,CU,IU,yU,AU,bU,OU,wU,NU;let DU=(KM=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),YM=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),qM=DM(),JM=zD("LocalAudioTrack","_enabledMutex"),zM=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),XM=DM(),QM=zD("LocalAudioTrack","_enabledMutex"),$M=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),ZM=DM(),eU=DM(),tU=DM(),iU=KL({argsMap:e=>[e.getTrackId()]}),nU=DM(),rU=KL({argsMap:e=>[e.getTrackId()]}),oU=DM(),sU=KL({argsMap:e=>[e.getTrackId()]}),aU=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),cU=KL({argsMap:e=>[e.getTrackId()]}),Bk((dU=class extends qk{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?NM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n){super(e,i),Gk(this,"trackMediaType",Ak.AUDIO),Gk(this,"_encoderConfig",void 0),Gk(this,"_trackSource",void 0),Gk(this,"metadata",[]),Gk(this,"_enabled",!0),Gk(this,"_volume",100),Gk(this,"_useAudioElement",!0),Gk(this,"_bypassWebAudio",!1),Gk(this,"processor",void 0),Gk(this,"_processorContext",void 0),Gk(this,"_processorDestination",void 0),Gk(this,"_getOriginVolumeLevel",void 0),Gk(this,"_usePipeMode",!1),Gk(this,"_useExtensionMode",!1),Gk(this,"_extensionManager",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new UM,VP("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),VP("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),tN()&&!Xk?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){UN(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&NM.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void gL.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,hD(this,Sk.NEED_REPLACE_TRACK,this).then((()=>{gL.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{gL.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||!XL())throw new LN(PN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await NM.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(gL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await hD(this,Sk.NEED_ENABLE_TRACK,this),gL.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),gL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await hD(this,Sk.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),gL.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,gL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await hD(this,Sk.NEED_MUTE_TRACK,this):await hD(this,Sk.NEED_UNMUTE_TRACK,this))}getStats(){bD((()=>{gL.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return pD(this,Sk.GET_STATS)||Hk({},Ok)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(bk.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(bk.ON_AUDIO_BUFFER),this._source.on(bk.ON_AUDIO_BUFFER,(t=>e(t)))}play(){gL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(gL.debug("[".concat(this.getTrackId(),"] start audio playback in element")),NM.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){gL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?NM.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._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];gL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&NM.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 hD(this,Sk.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return cp.resolve(void 0)}_ensureExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,hD(this,Sk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,hD(this,Sk.NEED_REPLACE_TRACK,this))}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new LN(PN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&gL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new LN(PN.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),gL.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new LN(PN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this._bypassWebAudio)throw new LN(PN.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new LN(PN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(e){e.on(Lk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await hD(this,Sk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hD(this,Sk.NEED_REPLACE_TRACK,this))})),e.on(Lk.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(Lk.ON_TRACK),e.removeAllListeners(Lk.ON_NODE)}bindProcessorContextEvents(e){e.on(kk.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(kk.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof UM&&(this._trackSource=new rM(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new MM(this._source.context,this.getTrackId(),"local"),t=new kM(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(bk.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(NM.stop(this.getTrackId()),this._source.play()),hD(this,Sk.NEED_REPLACE_MIXING_TRACK,this).then((()=>{gL.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{gL.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[KM],Object.getOwnPropertyDescriptor(dU.prototype,"setVolume"),dU.prototype),Bk(dU.prototype,"setPlaybackDevice",[YM,qM],Object.getOwnPropertyDescriptor(dU.prototype,"setPlaybackDevice"),dU.prototype),Bk(dU.prototype,"setEnabled",[JM,zM,XM],Object.getOwnPropertyDescriptor(dU.prototype,"setEnabled"),dU.prototype),Bk(dU.prototype,"setMuted",[QM,$M,ZM],Object.getOwnPropertyDescriptor(dU.prototype,"setMuted"),dU.prototype),Bk(dU.prototype,"getStats",[eU],Object.getOwnPropertyDescriptor(dU.prototype,"getStats"),dU.prototype),Bk(dU.prototype,"setAudioFrameCallback",[tU],Object.getOwnPropertyDescriptor(dU.prototype,"setAudioFrameCallback"),dU.prototype),Bk(dU.prototype,"play",[iU,nU],Object.getOwnPropertyDescriptor(dU.prototype,"play"),dU.prototype),Bk(dU.prototype,"stop",[rU,oU],Object.getOwnPropertyDescriptor(dU.prototype,"stop"),dU.prototype),Bk(dU.prototype,"close",[sU],Object.getOwnPropertyDescriptor(dU.prototype,"close"),dU.prototype),Bk(dU.prototype,"pipe",[aU],Object.getOwnPropertyDescriptor(dU.prototype,"pipe"),dU.prototype),Bk(dU.prototype,"unpipe",[cU],Object.getOwnPropertyDescriptor(dU.prototype,"unpipe"),dU.prototype),dU),PU=(lU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),uU=DM(),hU=zD("MicrophoneAudioTrack","_enabledMutex"),pU=KL({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),_U=DM(),EU=KL({argsMap:e=>[e.getTrackId()]}),Bk((fU=class extends DU{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?Ek(t.encoderConfig):{},n,VP("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),Gk(this,"_config",void 0),Gk(this,"_deviceName","default"),Gk(this,"_constraints",void 0),Gk(this,"_originalConstraints",void 0),Gk(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(mN()||SN())&&Qk.bindInterruptDetectorTrack(this)}async setDevice(e){if(gL.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await EM.getDeviceById(e),i={};i.audio=Hk({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await uM(i,this.getTrackId())}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await uM({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await EM.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}gL.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return gL.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(gL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),VP("AUTO_RESET_AUDIO_ROUTE")&&(oN()||TN())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await hD(this,Sk.NEED_DISABLE_TRACK,this)}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=Hk({},this._constraints),o=EM.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await uM({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await hD(this,Sk.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),gL.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}gL.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(mN()||SN())&&Qk.unbindInterruptDetectorTrack(this),fk.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))||zk&&zk()&&(YL.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:$N.TRACER}).onSuccess(),gL.debug("restart background audio tag success"))}onTrackEnded(){if((oN()||TN())&&this._enabled&&!this._isClosed&&Qk.duringInterruption){const e=async()=>{Qk.off(nk.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(gL.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Qk.on(nk.IOS_INTERRUPTION_END,e)}else gL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=EM.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await uM({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(kk.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(kk.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[lU,uU],Object.getOwnPropertyDescriptor(fU.prototype,"setDevice"),fU.prototype),Bk(fU.prototype,"setEnabled",[hU,pU,_U],Object.getOwnPropertyDescriptor(fU.prototype,"setEnabled"),fU.prototype),Bk(fU.prototype,"close",[EU],Object.getOwnPropertyDescriptor(fU.prototype,"close"),fU.prototype),fU),LU=(mU=KL({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),SU=DM(),gU=KL({argsMap:e=>[e.getTrackId()]}),TU=DM(),RU=KL({argsMap:e=>[e.getTrackId()]}),vU=DM(),CU=KL({argsMap:e=>[e.getTrackId()]}),IU=DM(),yU=KL({argsMap:e=>[e.getTrackId()]}),AU=DM(),bU=KL({argsMap:e=>[e.getTrackId()]}),OU=KL({argsMap:e=>[e.getTrackId()]}),wU=DM(),Bk((NU=class extends DU{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),Gk(this,"source",void 0),Gk(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(bk.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Ik.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){UN(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[mU,SU],Object.getOwnPropertyDescriptor(NU.prototype,"startProcessAudioBuffer"),NU.prototype),Bk(NU.prototype,"pauseProcessAudioBuffer",[gU,TU],Object.getOwnPropertyDescriptor(NU.prototype,"pauseProcessAudioBuffer"),NU.prototype),Bk(NU.prototype,"seekAudioBuffer",[RU,vU],Object.getOwnPropertyDescriptor(NU.prototype,"seekAudioBuffer"),NU.prototype),Bk(NU.prototype,"resumeProcessAudioBuffer",[CU,IU],Object.getOwnPropertyDescriptor(NU.prototype,"resumeProcessAudioBuffer"),NU.prototype),Bk(NU.prototype,"stopProcessAudioBuffer",[yU,AU],Object.getOwnPropertyDescriptor(NU.prototype,"stopProcessAudioBuffer"),NU.prototype),Bk(NU.prototype,"close",[bU],Object.getOwnPropertyDescriptor(NU.prototype,"close"),NU.prototype),Bk(NU.prototype,"setAudioBufferPlaybackSpeed",[OU,wU],Object.getOwnPropertyDescriptor(NU.prototype,"setAudioBufferPlaybackSpeed"),NU.prototype),NU);class kU extends DU{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=$k().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,MD(8,"track-mix-")),Gk(this,"trackList",void 0),Gk(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)?(gL.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):gL.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){gL.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}RD(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof kU?t.emit(Ck.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class MU extends nM{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(bk.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(),Gk(this,"audioBuffer",void 0),Gk(this,"sourceNode",void 0),Gk(this,"startPlayTime",0),Gk(this,"startPlayOffset",0),Gk(this,"pausePlayTime",0),Gk(this,"options",void 0),Gk(this,"currentLoopCount",0),Gk(this,"currentPlaybackSpeed",100),Gk(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):gL.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 UU=new Map;function VU(e,t){if(0===e.length||0===t.length)return 1/0;const i=KD(e),n=KD(t);return Math.floor(n/i)}class xU{get rendFrameRate(){const e=Math.max(1,VU(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:Vk.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(gL.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){Gk(this,"trackId",void 0),Gk(this,"config",void 0),Gk(this,"onFirstVideoFrameDecoded",void 0),Gk(this,"onFirstVideoFrameRender",void 0),Gk(this,"onVideoBufferReady",void 0),Gk(this,"onVideoStateChanged",void 0),Gk(this,"freezeTimeCounterList",[]),Gk(this,"renderFreezeAccTime",0),Gk(this,"renderFreezeAccTime2",0),Gk(this,"totalFreezeTime",0),Gk(this,"isKeepLastFrame",!1),Gk(this,"isDestroyed",!1),Gk(this,"timeUpdatedCount",0),Gk(this,"freezeTime",0),Gk(this,"playbackTime",0),Gk(this,"lastTimeUpdatedTime",0),Gk(this,"autoplayFailed",!1),Gk(this,"videoTrack",void 0),Gk(this,"videoElement",void 0),Gk(this,"cacheVideoElement",void 0),Gk(this,"cancelRVFId",void 0),Gk(this,"internal",!1),Gk(this,"_render_interframe_delays",[]),Gk(this,"_render_interframe_delays_sizes",[]),Gk(this,"_videoState",xk.VideoStateStopped),Gk(this,"videoElementCheckInterval",void 0),Gk(this,"videoElementFreezeTimeout",void 0),Gk(this,"_videoElementStatus",Vk.NONE),Gk(this,"_isInPage",!0),Gk(this,"isGettingVideoDimensions",!1),Gk(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return gL.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),Gk(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===Qk.curState&&(gL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Qw())),gN()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),Gk(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&gL.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=Vk.PLAYING;break;case"loadeddata":if(this.videoState=xk.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=Vk.CANPLAY;break;case"stalled":this.videoElementStatus=Vk.STALLED;break;case"suspend":this.videoElementStatus=Vk.SUSPEND;break;case"pause":this.videoElementStatus=Vk.PAUSED,oN()||TN()||tN()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(gL.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=Vk.WAITING;break;case"abort":this.videoElementStatus=Vk.ABORT;break;case"ended":this.videoElementStatus=Vk.ENDED;break;case"emptied":this.videoElementStatus=Vk.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=Vk.ERROR,gL.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>VP("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,KV.lastVisibleTime<KV.lastHiddenTime||i<KV.lastHiddenTime||i<KV.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())return;for(t>VP("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}}})),Gk(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(gL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Qw())),gN()?(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"),Qk.on(nk.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qk.on(nk.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){var t;const i=this.videoElement,n=i.play(),r=null!==(t=function(e,t,i,n){if(vM.delete(e)&&null!=i&&i.catch)return CM.set(e,i),OM(i,(()=>t.play()),(()=>CM.get(e)===i&&e.getVideoElement()===t),n)}(this,i,n,e))&&void 0!==t?t:n;null!=r&&r.catch&&r.catch((t=>{e&&gM(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(gL.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):gL.warning("[".concat(this.trackId,"] play warning: "),t)}));const o=Jw();if(("Safari"===o.name&&15===Number(o.version)||mN())&&r&&r.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(this.videoElement.style.transform="rotateY(180deg)")};r.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 gL.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new cp(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await HM(e);n({buffer:t,width:i.width,height:i.height})}else r(new LN(PN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await WM(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];CM.delete(this),this.isDestroyed=!0,Qk.off(nk.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qk.off(nk.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=xk.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==Vk.NONE&&this._videoElementStatus!==Vk.DESTROYED||(this.videoElementStatus=Vk.INIT),!this.videoElementCheckInterval&&(FU.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),VP("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,VP("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===xk.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=xk.VideoStateFrozen:document.addEventListener("visibilitychange",n))},o=(e,t)=>{if(this.videoElementStatus===Vk.PLAYING){if(i){const e=t.presentationTime-i.presentationTime,n=t.presentedFrames-i.presentedFrames;this._render_interframe_delays_sizes.push(n),this._render_interframe_delays.push(e);const o=KD(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===xk.VideoStateStarting&&(this.videoState=xk.VideoStateDecoding),this.videoState===xk.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,VP("VIDEO_FREEZE_DURATION"))),e<VP("VIDEO_FREEZE_DURATION")&&this.videoState===xk.VideoStateFrozen&&(this.videoState=xk.VideoStateDecoding),e>VP("VIDEO_FREEZE_DURATION")&&KV.lastVisibleTime>=KV.lastHiddenTime&&i.timestamp>KV.lastVisibleTime&&i.timestamp>KV.lastHiddenTime){const t=Math.min(66,VU(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,e-(n-1)*t),r=i>t?i:0;this.renderFreezeAccTime2+=r,this.totalFreezeTime+=r,this.renderFreezeAccTime+=e}}i=Hk(Hk({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(i=Hk(Hk({},t),{},{timestamp:e}));var n,s;VP("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(n=(s=this.videoElement).requestVideoFrameCallback)||void 0===n?void 0:n.call(s,o))};this.cancelRVFId=null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e?void 0:e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),yN()&&!VP("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const i=Jw();this.config.noStyle||("Safari"===i.name&&15===Number(i.version)||mN()||!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,rN()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,rN()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{gL.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;FU.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=Vk.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===Vk.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{gL.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{gL.error(e)})),this.autoplayFailed=!1,AN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};AN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),SM()}}const FU=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class BU extends xU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),Gk(this,"container",void 0),Gk(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var i;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(i=this.slot)||void 0===i||i.appendChild(this.container)):this.createElements())}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await WM(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",VP("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 jU,GU,WU,HU,KU,YU,qU,JU,zU,XU,QU,$U,ZU,eV,tV,iV,nV,rV,oV,sV,aV,cV,dV,lV,uV,hV,pV,_V,EV,fV,mV,SV,gV,TV,RV,vV,CV,IV;let yV=(jU=KL({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),GU=DM(),WU=KL({argsMap:e=>[e.getTrackId()]}),HU=zD("LocalVideoTrack","_enabledMutex"),KU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),YU=DM(),qU=zD("LocalVideoTrack","_enabledMutex"),JU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),zU=DM(),XU=KL({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),QU=DM(),$U=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),ZU=DM(),eV=DM(),tV=KL({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),iV=DM(),nV=DM(),rV=DM(),oV=KL({argsMap:e=>[e.getTrackId()]}),sV=DM(),aV=DM(),cV=DM(),dV=DM(),lV=DM(),uV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),hV=KL({argsMap:e=>[e.getTrackId()]}),pV=KL({argsMap:e=>[e.getTrackId()]}),_V=KL({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),EV=class e extends qk{get videoHeight(){if(tN()){const e=this._mediaStreamTrack.getSettings().height;return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(tN()){const e=this._mediaStreamTrack.getSettings().width;return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Vk.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,o){if(super(e,r),Gk(this,"trackMediaType",Ak.VIDEO),Gk(this,"_player",void 0),Gk(this,"isUseScaleResolutionDownBy",!1),Gk(this,"_videoVisibleTimer",null),Gk(this,"_previousVideoVisibleStatus",void 0),Gk(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Gk(this,"_encoderConfig",void 0),Gk(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),Gk(this,"_optimizationMode",void 0),Gk(this,"_saveEncodeBitrateRatio",1),Gk(this,"_videoHeight",void 0),Gk(this,"_videoWidth",void 0),Gk(this,"_forceBitrateLimit",void 0),Gk(this,"_enabled",!0),Gk(this,"_processorDestination",void 0),Gk(this,"_processorContext",void 0),Gk(this,"_usePipeMode",!1),Gk(this,"_useExtensionMode",!1),Gk(this,"_extensionManager",void 0),tN()){const t=e.getSettings(),i=t.width,n=t.height;this._videoWidth=i,this._videoHeight=n}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=i,this._optimizationMode=n,this._hints=o||[],t&&-1!==this._hints.indexOf(gk.CUSTOM_TRACK)?this._encoderConfig=ID(t):this._encoderConfig=t,-1===this._hints.indexOf(gk.SCREEN_TRACK))this.updateBitrateFromProfile();else if(cN(Hw.CHROME,115)&&-1!==Xw().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&zL().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,o,s=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),o=void 0,n.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{"live"===n.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(gL.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(gk.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new LM(this.getTrackId(),"local"),this._processorDestination=new PM(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:(gL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}gL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Hk(Hk(Hk({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new xU(i):this._player=new BU(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Ik.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),VP("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,gL.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(gL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await hD(this,Sk.NEED_DISABLE_TRACK,this)}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void gL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await hD(this,Sk.NEED_ENABLE_TRACK,this)}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}gL.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,gL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await hD(this,Sk.NEED_MUTE_TRACK,this):await hD(this,Sk.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),gL.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await hD(this,Sk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(gL)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new LN(PN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=uk(e),VP("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=FM({encoderConfig:e});(tN()||oN()||TN())&&(t.deviceId=void 0),gL.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 LN(PN.UNEXPECTED_ERROR,e.toString());throw gL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(gk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await hD(this,Sk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(gL)}}getStats(){bD((()=>{gL.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return pD(this,Sk.GET_STATS)||Hk({},wk)}async setBeautyEffect(e){gL.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 WM(e)}async findClosestProfile(){const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,n=e.frameRate,r=this._encoderConfig||{},o=r.width,s=r.height,a=r.frameRate,c=WD(this._videoWidth||t||o||0),d=WD(this._videoHeight||i||s||0),l=function(e,t,i){if(!Array.isArray(VP("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===VP("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const n=Math.min(e,t);return!(n>=480)&&Hk(Hk({},VP("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>n))),{},{frameRate:i})}(c,d,WD(n||a||15));if(l)return gL.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(c,"x").concat(d," => ").concat(JSON.stringify(l))),this.setEncoderConfiguration(l)}async setBitrateLimit(e){gL.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 gL.error(PN.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await hD(this,Sk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,gL.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}gL.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return gL.error(PN.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,gL.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){const e=this._originMediaStreamTrack;xM(e).then((t=>{let i=Kk(t,2),n=i[0],r=i[1];this._videoHeight=r,this._videoWidth=n,e===this._originMediaStreamTrack&&n>0&&r>0&&this.safeEmit(Sk.VIDEO_RESOLUTION_UPDATED,this)})).catch(VD)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new LN(PN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");gL.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=uk(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(gk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await hD(this,Sk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(gL)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,n=e.frameRate;if(!t||!i||!n)return;const r=this._encoderConfig,o=r.bitrateMax,s=r.bitrateMin;if(null==s||null==o){const e=function(e,t,i,n,r){const o=VP("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:n,max:r};if(void 0===r){const s=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*s:2*s,n=null!=n?n:s}else n=null!=n?n:Math.floor(r/10);return{min:n,max:r}}(t,i,n,s,o),r=e.max,a=e.min;if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=r,VP("VIDEO_STANDARD_BITRATE_VERSION")&&null==s&&null==o){const e=Kk(function(e,t,i){const n=4*Math.floor(2e5*Math.pow(i/15,.6)*Math.pow(e*t/230400,.75)),r=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),s=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=mp(o).call(o).next().value,c=1;if(o.has(r))a=o.get(r);else{var d;const e=t_(d=Array.from(o.entries())).call(d,((e,t)=>Kk(e,1)[0]-Kk(t,1)[0])),t=e.find((e=>Kk(e,1)[0]>r));if(t){const i=e.indexOf(t);if(i>0){const n=e[i-1],o=(r-n[0])/(t[0]-n[0]);a=n[1]+o*(t[1]-n[1])}else a=t[1]}else a=e[e.length-1][1]}if(s.has(r))c=s.get(r);else{var l;const e=t_(l=Array.from(s.entries())).call(l,((e,t)=>Kk(e,1)[0]-Kk(t,1)[0])),t=e.find((e=>Kk(e,1)[0]>r));if(t){const i=e.indexOf(t);if(i>0){const n=e[i-1],o=(r-n[0])/(t[0]-n[0]);c=n[1]+o*(t[1]-n[1])}else c=t[1]}else c=e[e.length-1][1]}const u=VP("VIDEO_NEW_BITRATE_RATIO");u&&u>0&&(a=u/100);const h=Math.floor(n*a),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(i/15,.69));let _=h;const E=VP("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=n:2===E?_=h:3===E&&(_=p)),[Math.floor(_/1e3),c]}(t,i,n),2),r=e[0],o=e[1];this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=a?Math.min(a,r):r,this._saveEncodeBitrateRatio=o,gL.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(n,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else gL.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(n,"] => [brMax: ").concat(r,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},r=n.element,o=n.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=HN.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=YL.reportApiInvoke(null,{tag:$N.TRACER,name:QN.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 LN(PN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),hD(this,Sk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),hD(this,Sk.NEED_REPLACE_TRACK,this))},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new LN(PN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&gL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new LN(PN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new LN(PN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=Hk(Hk({},n),uk(t))),n=yD(n);const r=MD(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,yD(this._scalabilityMode),this._optimizationMode,r,yD(this._hints));return t&&n&&o.setEncoderConfiguration(n),gL.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new LN(PN.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new LN(PN.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(bD((()=>{YL.reportApiInvoke(null,{name:QN.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:$N.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!VP("ENABLE_VIDEO_SEI")||!VP("ENABLE_ENCODED_TRANSFORM"))return void gL.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new LN(PN.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void gL.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===n||"video/h265"===n?this.safeEmit("sei-to-send",e):gL.warning("SEI is not supported by ".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(Lk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await hD(this,Sk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hD(this,Sk.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Lk.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(kk.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(kk.REQUEST_CONSTRAINTS)}},Bk(EV.prototype,"play",[jU,GU],Object.getOwnPropertyDescriptor(EV.prototype,"play"),EV.prototype),Bk(EV.prototype,"stop",[WU],Object.getOwnPropertyDescriptor(EV.prototype,"stop"),EV.prototype),Bk(EV.prototype,"setEnabled",[HU,KU,YU],Object.getOwnPropertyDescriptor(EV.prototype,"setEnabled"),EV.prototype),Bk(EV.prototype,"setMuted",[qU,JU,zU],Object.getOwnPropertyDescriptor(EV.prototype,"setMuted"),EV.prototype),Bk(EV.prototype,"setSaveEncodeBitrateRatio",[XU,QU],Object.getOwnPropertyDescriptor(EV.prototype,"setSaveEncodeBitrateRatio"),EV.prototype),Bk(EV.prototype,"setEncoderConfiguration",[$U,ZU],Object.getOwnPropertyDescriptor(EV.prototype,"setEncoderConfiguration"),EV.prototype),Bk(EV.prototype,"getStats",[eV],Object.getOwnPropertyDescriptor(EV.prototype,"getStats"),EV.prototype),Bk(EV.prototype,"setBeautyEffect",[tV,iV],Object.getOwnPropertyDescriptor(EV.prototype,"setBeautyEffect"),EV.prototype),Bk(EV.prototype,"getCurrentFrameData",[nV],Object.getOwnPropertyDescriptor(EV.prototype,"getCurrentFrameData"),EV.prototype),Bk(EV.prototype,"getCurrentFrameImage",[rV],Object.getOwnPropertyDescriptor(EV.prototype,"getCurrentFrameImage"),EV.prototype),Bk(EV.prototype,"findClosestProfile",[oV,sV],Object.getOwnPropertyDescriptor(EV.prototype,"findClosestProfile"),EV.prototype),Bk(EV.prototype,"setBitrateLimit",[aV],Object.getOwnPropertyDescriptor(EV.prototype,"setBitrateLimit"),EV.prototype),Bk(EV.prototype,"setOptimizationMode",[cV],Object.getOwnPropertyDescriptor(EV.prototype,"setOptimizationMode"),EV.prototype),Bk(EV.prototype,"setScalabiltyMode",[dV],Object.getOwnPropertyDescriptor(EV.prototype,"setScalabiltyMode"),EV.prototype),Bk(EV.prototype,"updateMediaStreamTrackResolution",[lV],Object.getOwnPropertyDescriptor(EV.prototype,"updateMediaStreamTrackResolution"),EV.prototype),Bk(EV.prototype,"pipe",[uV],Object.getOwnPropertyDescriptor(EV.prototype,"pipe"),EV.prototype),Bk(EV.prototype,"unpipe",[hV],Object.getOwnPropertyDescriptor(EV.prototype,"unpipe"),EV.prototype),Bk(EV.prototype,"close",[pV],Object.getOwnPropertyDescriptor(EV.prototype,"close"),EV.prototype),Bk(EV.prototype,"replaceTrack",[_V],Object.getOwnPropertyDescriptor(EV.prototype,"replaceTrack"),EV.prototype),EV),AV=(fV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),mV=DM(),SV=zD("CameraVideoTrack","_enabledMutex"),gV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),TV=DM(),RV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),vV=DM(),CV=KL({argsMap:e=>[e.getTrackId()]}),IV=class e extends yV{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,uk(t.encoderConfig),n,r,o),Gk(this,"_config",void 0),Gk(this,"_originalConstraints",void 0),Gk(this,"_constraints",void 0),Gk(this,"_enabled",!0),Gk(this,"_deviceName","default"),Gk(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(mN()||SN())&&!function(){const e=Jw();if(e.os!==Ww.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&RN()&&this._enabled&&!this._isClosed&&(gL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=uk(this._config.encoderConfig),Qk.on(nk.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Qk.on(nk.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(gL.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await EM.getDeviceById(e),i={};i.video=Hk({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await uM(i,this.getTrackId())}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await uM({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await EM.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}gL.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){gL.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Hk(Hk({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await uM(t,this.getTrackId())}catch(t){throw gL.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await uM({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=Hk({},t.video),gL.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(gL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await uM({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await hD(this,Sk.NEED_ENABLE_TRACK,this)}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),gL.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 hD(this,Sk.NEED_DISABLE_TRACK,this)}catch(e){throw gL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}gL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new LN(PN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=uk(e),VP("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=ID(this._config);i.encoderConfig=e;const n=FM(i);(tN()||oN()||TN())&&(n.deviceId=void 0),gL.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new LN(PN.UNEXPECTED_ERROR,e.toString());throw gL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(gk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await hD(this,Sk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(gL)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((oN()||TN())&&this._enabled&&!this._isClosed&&Qk.duringInterruption){const e=async()=>{Qk.off(nk.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(gL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Qk.on(nk.IOS_INTERRUPTION_END,e)}else gL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=EM.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await uM({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),Qk.off(nk.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Qk.off(nk.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=Hk(Hk({},n),uk(t))),n=yD(n);const r=MD(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,yD(Hk(Hk({},this._config),{},{encoderConfig:n})),yD(this._constraints),yD(this._scalabilityMode),this._optimizationMode,r);return t&&n&&o.setEncoderConfiguration(n),gL.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(kk.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(kk.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},Bk(IV.prototype,"setDevice",[fV,mV],Object.getOwnPropertyDescriptor(IV.prototype,"setDevice"),IV.prototype),Bk(IV.prototype,"setEnabled",[SV,gV,TV],Object.getOwnPropertyDescriptor(IV.prototype,"setEnabled"),IV.prototype),Bk(IV.prototype,"setEncoderConfiguration",[RV,vV],Object.getOwnPropertyDescriptor(IV.prototype,"setEncoderConfiguration"),IV.prototype),Bk(IV.prototype,"close",[CV],Object.getOwnPropertyDescriptor(IV.prototype,"close"),IV.prototype),IV);const bV=new Set(["auto","1440p","1440p_1","1440p_2","1440p_3","4k","4k_1","4k_2","4k_3"]);function OV(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=Hk(Hk({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?gL.debug("[".concat(e,"] set content hint to"),i.optimizationMode):gL.debug("[".concat(e,"] set content hint failed")))):gL.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var wV,NV,DV,PV,LV,kV,MV,UV,VV,xV,FV,BV,jV;class GV extends Yk{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(MD(5,""))),Gk(this,"_userId",void 0),Gk(this,"_uintId",void 0),Gk(this,"_isDestroyed",!1),Gk(this,"store",void 0),Gk(this,"processor",void 0),Gk(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=n}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,gL.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let WV=(wV=KL({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),NV=KL({argsMap:e=>[e.getTrackId()]}),DV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PV=KL({argsMap:e=>[e.getTrackId()]}),Bk((LV=class extends GV{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Vk.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n,r){super(e,t,i,n),Gk(this,"_videoVisibleTimer",null),Gk(this,"_previousVideoVisibleStatus",void 0),Gk(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Gk(this,"trackMediaType",Ak.VIDEO),Gk(this,"_videoWidth",void 0),Gk(this,"_videoHeight",void 0),Gk(this,"_player",void 0),Gk(this,"_prePlayer",void 0),Gk(this,"processorDestination",void 0),Gk(this,"processorContext",void 0),Gk(this,"_usePipeMode",!1),Gk(this,"_useExtensionMode",!1),Gk(this,"_extensionManager",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new LM(this.getTrackId(),"remote"),this.processorDestination=new PM(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return bD((()=>{gL.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),pD(this,Sk.GET_STATS)||Hk({},Pk)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(yk.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(gL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}gL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Hk(Hk({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(i);else{let t=!1,n=!1;const r=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!r&&(this._prePlayer.destroy(),n=!0),r?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(i)):this._player=e instanceof HTMLVideoElement?new xU(i):new BU(i),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(yk.FIRST_FRAME_DECODED),n&&this.safeEmit(yk.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(yk.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}const n=this._player;!function(e,t){if(yM()){CM.delete(e),vM.add(e);try{t()}finally{vM.delete(e)}}else t()}(n,(()=>n.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(yk.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),VP("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(yk.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,gL.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){xM(this._originMediaStreamTrack).then((e=>{let t=Kk(e,2),i=t[0],n=t[1];this._videoHeight=n,this._videoWidth=i})).catch(VD)}_updatePlayerSource(){gL.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},r=n.element,o=n.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=HN.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=YL.reportApiInvoke(null,{tag:$N.TRACER,name:QN.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 LN(PN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new LN(PN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&gL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new LN(PN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new LN(PN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Lk.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(Lk.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e,t){this.emit(Ck.SEI_RECEIVED,e,t)}}).prototype,"play",[wV],Object.getOwnPropertyDescriptor(LV.prototype,"play"),LV.prototype),Bk(LV.prototype,"stop",[NV],Object.getOwnPropertyDescriptor(LV.prototype,"stop"),LV.prototype),Bk(LV.prototype,"pipe",[DV],Object.getOwnPropertyDescriptor(LV.prototype,"pipe"),LV.prototype),Bk(LV.prototype,"unpipe",[PV],Object.getOwnPropertyDescriptor(LV.prototype,"unpipe"),LV.prototype),LV),HV=(kV=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),MV=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),UV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),VV=KL({argsMap:e=>[e.getTrackId()]}),xV=KL({argsMap:e=>[e.getTrackId()]}),FV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),BV=KL({argsMap:e=>[e.getTrackId()]}),Bk((jV=class extends GV{get isPlaying(){return this._useAudioElement?NM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),Gk(this,"trackMediaType",Ak.AUDIO),Gk(this,"_source",void 0),Gk(this,"_useAudioElement",!0),Gk(this,"_volume",100),Gk(this,"processorContext",void 0),Gk(this,"processorDestination",void 0),Gk(this,"_usePipeMode",!1),Gk(this,"_useExtensionMode",!1),Gk(this,"_extensionManager",void 0),Gk(this,"_played",!1),Gk(this,"_bypassWebAudio",!1),VP("DISABLE_WEBAUDIO")?(this._source=new UM,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new rM(e,!0),VP("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(bk.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(yk.FIRST_FRAME_DECODED)})),this.processorContext=new MM(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new kM(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(bk.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(bk.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(bk.ON_AUDIO_BUFFER),this._source.on(bk.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?NM.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(NM.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,VP("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!XL())throw new LN(PN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await NM.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?NM.getVolume(this.getTrackId()):this._source instanceof rM?this._source.getAudioVolume():0}getStats(){return bD((()=>{gL.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),pD(this,Sk.GET_STATS)||Hk({},Nk)}play(){var e;if(gL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement)return gL.debug("[".concat(this.getTrackId(),"] use audio element to play")),void function(e,t,i){if(!yM())return i();IM={track:e,recover:t};try{i()}finally{IM=void 0}}(this._mediaStreamTrack,(e=>this._resumeAudioElement(e)),(()=>NM.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)));gL.debug("[".concat(this.getTrackId(),"] use audio context to play"));const t=null===(e=this._source.context)||void 0===e?void 0:e.state;t&&"running"!==t&&gM(this.store.sessionId||null,"audio","AudioContext state is ".concat(t),this.getTrackId()),this._source.play(),yM()&&"suspended"===t&&this._retryWebAudioAutoplay()}_canSwitchAudioBackend(){return yM()&&!this._bypassWebAudio&&!this._usePipeMode&&!this._useExtensionMode&&!this.processor}_resumeAudioElement(e){var t;if(this._played&&!this._isDestroyed&&this._useAudioElement){if("running"!==(null===(t=this._source.context)||void 0===t?void 0:t.state)||!this._canSwitchAudioBackend())return e.play();this._source.setVolume(this._volume/100),this._source.play(),NM.stop(this.getTrackId()),this._useAudioElement=!1}}_retryWebAudioAutoplay(){const e=()=>this._played&&!this._isDestroyed&&!this._useAudioElement,t=AM((async()=>{var t;if(!e())return;const i=null===(t=this._source.context)||void 0===t?void 0:t.resume();i&&(bM(i,this.store.sessionId),await i)}));null==t||t.catch((()=>{}))}stop(){gL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?NM.stop(this.getTrackId()):this._source.stop()}_reusePreAudioElement(e,t){this._played=t,this._useAudioElement?(NM.reuseTrackId(e,this.getTrackId()),this._updatePlayerSource()):(NM.stop(e),this._updatePlayerSource(),t&&this._source.play()),this.setVolume(this._volume)}_destroy(){super._destroy(),this._played=!1,this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];gL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&NM.updateTrack(this.getTrackId(),this._mediaStreamTrack)}_ensureAudioExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this._extensionManager}useExtension(e){if(this._usePipeMode)throw new LN(PN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureAudioExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&gL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new LN(PN.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),gL.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new LN(PN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active.");if(this._bypassWebAudio)throw new LN(PN.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new LN(PN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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 LN(PN.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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Lk.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(Lk.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(Lk.ON_TRACK),this.processorDestination.removeAllListeners(Lk.ON_NODE)}}).prototype,"setVolume",[kV],Object.getOwnPropertyDescriptor(jV.prototype,"setVolume"),jV.prototype),Bk(jV.prototype,"setAmplifiedVolume",[MV],Object.getOwnPropertyDescriptor(jV.prototype,"setAmplifiedVolume"),jV.prototype),Bk(jV.prototype,"setPlaybackDevice",[UV],Object.getOwnPropertyDescriptor(jV.prototype,"setPlaybackDevice"),jV.prototype),Bk(jV.prototype,"play",[VV],Object.getOwnPropertyDescriptor(jV.prototype,"play"),jV.prototype),Bk(jV.prototype,"stop",[xV],Object.getOwnPropertyDescriptor(jV.prototype,"stop"),jV.prototype),Bk(jV.prototype,"pipe",[FV],Object.getOwnPropertyDescriptor(jV.prototype,"pipe"),jV.prototype),Bk(jV.prototype,"unpipe",[BV],Object.getOwnPropertyDescriptor(jV.prototype,"unpipe"),jV.prototype),jV);const KV=new class extends JN{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),Gk(this,"_lastHiddenTime",0),Gk(this,"_lastVisibleTime",0),Gk(this,"needUploadStats",[]),Gk(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),gL.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}};var YV=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}(YV||{});const qV=new Map;window.cache=qV,function(){const e=Jw();JL.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),JL.getStreamFromExtension=e.name===Hw.CHROME&&Number(e.version)>34,JL.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}(),JL.supportMinBitrate=e.name===Hw.CHROME||e.name===Hw.EDGE,JL.supportSetRtpSenderParameters=function(){const e=Jw();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!IN()||!(!tN()&&!$w())||e.name===Hw.FIREFOX&&Number(e.version)>=64)}(),e.name===Hw.SAFARI&&(Number(e.version)>=14?JL.supportDualStream=!0:JL.supportDualStream=!1),JL.webAudioMediaStreamDest=function(){const e=Jw();return!(e.name===Hw.SAFARI&&Number(e.version)<12)}(),JL.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,JL.supportWebGL="undefined"!=typeof WebGLRenderingContext,JL.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,IN()||(JL.webAudioWithAEC=!0),JL.supportShareAudio=function(){const e=Jw();return(e.os===Ww.WIN_10||e.os===Ww.WIN_81||e.os===Ww.WIN_7||e.os===Ww.LINUX||e.os===Ww.MAC_OS||e.os===Ww.CHROMIUM_OS)&&e.name===Hw.CHROME&&Number(e.version)>=74}(),JL.supportDataChannel=!!(sN(76)||lN(68)||uN(14)),JL.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!rN()&&!!e&&e.prototype.setConfiguration instanceof Function}(),JL.supportWebRTCEncodedTransform=sN(87)||iN()||lN(117),JL.supportWebRTCInsertableStream=function(){const e=Jw();return(e.name===Hw.CHROME||e.name===Hw.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),JL.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,JL.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,JL.supportSuppressLocalAudioPlayback=tk(),JL.supportRestrictOwnAudio=ik(),CD((()=>{JL.supportDualStreamEncoding=function(){const e=Jw();return!!VP("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&VP("CHROME_DUAL_STREAM_USE_ENCODING")))}(),gL.debug("browser ua: ",navigator.userAgent),gL.info("browser info: ",e),gL.info("browser compatibility: ",JL)}))}();const JV=["CHINA","GLOBAL"];const zV=[[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]],XV=[],QV=[];function $V(e,t){return!!t&&XV.some((i=>i.uid===e&&i.channelName===t))}function ZV(){return QV.length>0}var ex=dR.forEach,tx=Yn("forEach")?[].forEach:function(e){return ex(this,e,arguments.length>1?arguments[1]:void 0)};wi({target:"Array",proto:!0,forced:[].forEach!==tx},{forEach:tx});var ix=tn("Array","forEach"),nx=Sn,rx=Ze,ox=l,sx=ix,ax=Array.prototype,cx={DOMTokenList:!0,NodeList:!0},dx=function(e){var t=e.forEach;return e===ax||ox(ax,e)&&t===ax.forEach||rx(cx,nx(e))?sx:t},lx=i(dx),ux=Xe,hx=Eo;wi({target:"Object",stat:!0,forced:n((function(){hx(1)}))},{keys:function(e){return hx(ux(e))}});var px=i(Z.Object.keys),_x=i(or),Ex=i(Sr);function fx(e,t,i,n,r){var o,s,a,c={};return lx(o=px(n)).call(o,(function(e){c[e]=n[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=_x(s=Ex(a=BI(i).call(i)).call(a)).call(s,(function(i,n){return n(e,t,i)||i}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer&&(Jb(e,t,c),c=null),c}let mx=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}({}),Sx=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}({}),gx=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}({}),Tx=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}({}),Rx=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_TOO_MANY_MESSAGES=2033]="ERR_TOO_MANY_MESSAGES",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}({}),vx=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),Cx=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.SHOULD_ENTER_RECONNECTING="should_enter_reconnecting",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}({}),Ix=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}({}),yx=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}({}),Ax=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}({}),bx=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),Ox=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.SHOULD_ENTER_RECONNECTING="websocket:should_enter_reconnecting",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 wx(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw gL.error("Invalid Channel Name ".concat(e)),new qL(PN.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,")}function Nx(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||jN(e,1,255)))throw new qL(PN.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&&gL.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 Dx=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({}),Px=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({});function Lx(e){if(!e.channelName)throw new qL(PN.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new qL(PN.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&xN(e.token,"info.token",1,2047),Nx(e.uid),wx(e.channelName),!0}let kx=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}({}),Mx=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}({}),Ux=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}({}),Vx=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),xx=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}({}),Fx=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}({}),Bx=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}({}),jx=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 Gx=[jx.AFRICA,jx.ASIA,jx.CHINA,jx.EUROPE,jx.GLOBAL,jx.INDIA,jx.JAPAN,jx.NORTH_AMERICA,jx.OCEANIA,jx.OVERSEA,jx.SOUTH_AMERICA];let Wx=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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:Wx.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:{}};OP&&(Hx.CHINA={CODE:Wx.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 Kx=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 Yx(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class qx extends JN{constructor(e,t){super(),Zb(this,"onICEConnectionStateChange",void 0),Zb(this,"onConnectionStateChange",void 0),Zb(this,"onDTLSTransportStateChange",void 0),Zb(this,"onDTLSTransportError",void 0),Zb(this,"onICETransportStateChange",void 0),Zb(this,"onFirstAudioReceived",void 0),Zb(this,"onFirstVideoReceived",void 0),Zb(this,"onFirstAudioDecoded",void 0),Zb(this,"onFirstVideoDecoded",void 0),Zb(this,"onFirstVideoRender",void 0),Zb(this,"onFirstVideoBufferReady",void 0),Zb(this,"onFirstVideoDecodedTimeout",void 0),Zb(this,"onAudioMetadata",void 0),Zb(this,"onAudioPts",void 0),Zb(this,"onSelectedLocalCandidateChanged",void 0),Zb(this,"onSelectedRemoteCandidateChanged",void 0),Zb(this,"onICECandidateError",void 0),Zb(this,"getLocalVideoStats",void 0)}}class Jx extends qx{constructor(e,t){super(e,t),Zb(this,"establishPromise",void 0)}}let zx=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),Xx=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),Qx=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 $x=["disconnected","failed"];let Zx=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),eF=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),tF=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}({}),iF=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),nF=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}({}),rF=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}({}),oF=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),sF=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}({}),aF=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}({}),cF=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}({});const dF={[mx.ACCESS_POINT]:{[Tx.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[Tx.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[Tx.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[Tx.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[Tx.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[Tx.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[Tx.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[mx.UNILBS]:{[gx.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[gx.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[gx.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[gx.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[gx.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[gx.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[gx.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[gx.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[gx.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[gx.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[gx.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[gx.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[gx.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[mx.STRING_UID_ALLOCATOR]:{[Sx.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Sx.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Sx.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function lF(e){const t=dF[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===mx.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}const uF={[Rx.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Rx.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Rx.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Rx.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Rx.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Rx.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Rx.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Rx.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Rx.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Rx.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Rx.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Rx.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[Rx.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[Rx.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[Rx.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Rx.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Rx.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Rx.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Rx.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Rx.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Rx.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Rx.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Rx.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Rx.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Rx.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Rx.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Rx.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Rx.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Rx.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Rx.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Rx.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Rx.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Rx.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Rx.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Rx.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Rx.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Rx.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Rx.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Rx.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Rx.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Rx.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Rx.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Rx.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Rx.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Rx.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Rx.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Rx.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Rx.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Rx.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Rx.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Rx.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Rx.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Rx.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Rx.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Rx.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Rx.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Rx.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Rx.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Rx.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Rx.ERR_TOO_MANY_MESSAGES]:{desc:"ERR_TOO_MANY_MESSAGES",action:"tryNext"},[Rx.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Rx.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Rx.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Rx.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Rx.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Rx.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function hF(e){const t=uF[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function pF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _F(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pF(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function EF(e,t){if("string"==typeof e)return e;const i=e.proxy,n=e.host,r=e.port;if(t){const e=VP("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r)}const fF=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,mF=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,SF=/wss:\/\/(.+):([0-9]+)\/?/,gF=/wss:\/\/(.[^\/]+)\/?/;let TF=0;class RF{constructor(e,t){Zb(this,"id",0),Zb(this,"store",void 0),Zb(this,"recordIndex",void 0),Zb(this,"websockets",[]),Zb(this,"try443PortDuration",2e3),Zb(this,"forceCloseWSDuration",5e3),Zb(this,"try443PortTimeout",null),Zb(this,"forceCloseTimeout",null),Zb(this,"isTry443PortFailed",!1),Zb(this,"isNormalPortFailed",!1),Zb(this,"useDoubleDomain",!1),Zb(this,"useProxy",!1),Zb(this,"startTime",Date.now()),this.id=++TF,this.try443PortDuration=VP("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];gL.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=VP("GATEWAY_DOMAINS"),r=Date.now(),o=[],s=n.find((t=>{var i;return Un(i=e.host).call(i,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(EF(_F(_F({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=_F({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}a.push(EF(i,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new qL(PN.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=Fw();this.store&&this.store.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},this.recordIndex),o.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState));const n=o.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(n)),n&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:Fx.A_ROUND_WS_FAILED})):!t&&n&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=n:this.isNormalPortFailed=n},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...o);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();Jw().os===Ww.MAC_OS&&rN()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;var r=HI(e.match(fF)||[],4);if(t=r[1],i=r[2],n=r[3],!t){var o=HI(e.match(mF)||[],3);i=o[1],n=o[2]}if(!i||!n){var s=HI(e.match(SF)||[],3);i=s[1],n=s[2]}return i&&n||(i=HI(e.match(gF)||[],2)[1]),i||gL.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(gL.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function vF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class CF extends JN{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reportUrl(){return"connected"===this._state&&this.websocket?this.websocket.url:this._lastAttemptedUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Un(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get isFirstJoin(){return this.queryReconnectingWhenConnecting}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Ox.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Ox.CONNECTED):"closed"===this._state?this.emit(Ox.CLOSED):"failed"===this._state&&this.emit(Ox.FAILED))}resetReconnectCount(e){gL.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),Zb(this,"_websocketUrl",null),Zb(this,"_lastAttemptedUrl",null),Zb(this,"connectionID",0),Zb(this,"currentURLIndex",0),Zb(this,"urls",[]),Zb(this,"_reconnectMode","tryNext"),Zb(this,"reconnectReason",void 0),Zb(this,"_initMutex",void 0),Zb(this,"name",void 0),Zb(this,"_state","closed"),Zb(this,"reconnectInterrupter",void 0),Zb(this,"websocket",void 0),Zb(this,"retryConfig",void 0),Zb(this,"reconnectCount",0),Zb(this,"forceCloseTimeout",5e3),Zb(this,"queryReconnectingWhenConnecting",!1),Zb(this,"onlineReconnectListener",void 0),Zb(this,"useCompress",void 0),Zb(this,"tryDoubleDomain",!1),Zb(this,"use443PortOnly",!1),Zb(this,"wsInflateLength",0),Zb(this,"wsDeflateLength",0),Zb(this,"closeEstablishingWs",(()=>{})),Zb(this,"store",void 0),Zb(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?vF(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):vF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=r,this._initMutex=new JD("websocket",o?o.clientId:void 0);const s=t.timeout,a=t.timeoutFactor,c=Math.max(300,Math.floor(3*s/5)),d=Math.max(1.2,Math.floor(8*a)/10);dD.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),ED.on(lD.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===dD.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}disableQueryReconnectingWhenConnecting(){this.queryReconnectingWhenConnecting=!1}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=await this._initMutex.lock();this._lastAttemptedUrl=null,this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.queryReconnectingWhenConnecting=!0===i.queryReconnectingWhenConnecting,this.urls=e,this.state="connecting";try{var r;const e=Fw(),t=this.urls[this.currentURLIndex];null===(r=this.store)||void 0===r||r.beforeConnect(),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(Ox.CLOSED,(()=>{e.reject(new LN(PN.WS_DISCONNECT))})),this.once(Ox.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 gL.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),gL.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new LN(PN.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new LN(PN.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=Fw();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),gL.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(gL.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new LN(PN.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{const t=this.queryReconnectingWhenConnecting;this.disableQueryReconnectingWhenConnecting();const n=t&&("connecting"===this.state||"connected"===this.state)&&!0===pD(this,Ox.SHOULD_ENTER_RECONNECTING,e.reason);("connected"===this.state||n)&&(this.reconnectReason=e.reason,this.state="reconnecting");const r=pD(this,Ox.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,o=await this.reconnectWithAction(r);if("closed"===this.state)return void gL.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!o)return i.reject(new LN(PN.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},o=e=>{this.emit(Ox.ON_MESSAGE,e)},s=e=>{gL.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),VP("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=VP("GATEWAY_WSS_ADDRESS")),gL.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=EF(e);this._websocketUrl=t,this._lastAttemptedUrl=t;const i=await this.chooseBestWebsocketConnection(e);this.websocket=i,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=o,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,n=e instanceof LN,o=n&&e.code===PN.WS_ABORT,s=n&&e.code===PN.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());gL.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},a),t||s?(i.reject(t?new LN(PN.WS_DISCONNECT,"websocket is closed: ".concat(c)):new LN(PN.WS_ERR,"init websocket failed: ".concat(c))),s&&gL.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;gL.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||ED.isOnline||!ED.onlineWaiter||(this.onlineReconnectListener=ED.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=QD(this.reconnectCount,this.retryConfig);gL.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await cp.race([kD(t),this.onlineReconnectListener||new cp((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Ox.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);gL.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(gL.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await uD(this,Ox.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;gL.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;if(Array.isArray(n)){if(Un(n).call(n,"dynamic key expired"))return this.emit(Ox.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(Un(n).call(n,"request downgrade fallback"))return this.emit(Ox.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class IF extends CF{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=Fw(),n=function(e,t){return new RF(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{gL.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new LN(PN.WS_ABORT,"choose best websocket aborted"))};const r=VP("GATEWAY_DOMAINS");return gL.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class yF extends JN{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vx.CONNECTED?this.emit(Cx.WS_CONNECTED):e===vx.RECONNECTING?this.emit(Cx.WS_RECONNECTING,this._websocketReconnectReason):e===vx.CLOSED&&this.emit(Cx.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get reportUrl(){return this.websocket&&this.websocket.reportUrl||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),Zb(this,"__name__","AgoraRTCSignal"),Zb(this,"_disconnectedReason",void 0),Zb(this,"_websocketReconnectReason",void 0),Zb(this,"reconnectingFromConnecting",!1),Zb(this,"_connectionState",vx.CLOSED),Zb(this,"reconnectToken",void 0),Zb(this,"websocket",void 0),Zb(this,"openConnectionTime",void 0),Zb(this,"clientId",void 0),Zb(this,"lastMsgTime",Date.now()),Zb(this,"uploadCache",[]),Zb(this,"uploadCacheInterval",void 0),Zb(this,"rttRolling",new class{constructor(e){ON(this,"input",[]),ON(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:sr(e=this.input).call(e,((e,t)=>e+t))/this.input.length}}(5)),Zb(this,"pingpongTimer",void 0),Zb(this,"wsInflateDataTimer",void 0),Zb(this,"pingpongTimeoutCount",0),Zb(this,"ortc",void 0),Zb(this,"joinResponse",void 0),Zb(this,"multiIpOption",void 0),Zb(this,"initError",void 0),Zb(this,"spec",void 0),Zb(this,"store",void 0),Zb(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(Cx.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===Ax.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Ax.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(tD.UID_BANNED);break;case 15:this.close(tD.IP_BANNED);break;case 16:this.close(tD.CHANNEL_BANNED)}if(t._type===Ax.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case Rx.ERR_LICENSE_MISSING:this.close(tD.LICENSE_MISSING);break;case Rx.ERR_LICENSE_EXPIRED:this.close(tD.LICENSE_EXPIRED);break;case Rx.ERR_LICENSE_MINUTES_EXCEEDED:this.close(tD.LICENSE_MINUTES_EXCEEDED);break;case Rx.ERR_LICENSE_PERIOD_INVALID:this.close(tD.LICENSE_PERIOD_INVALID);break;case Rx.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(tD.LICENSE_MULTIPLE_SDK_SERVICE);break;case Rx.ERR_LICENSE_ILLEGAL:this.close(tD.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new IF("gateway-".concat(this.clientId),this.spec.retryConfig,!0,VP("JOIN_GATEWAY_USE_DUAL_DOMAIN"),VP("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===vx.CONNECTED&&this.reconnect("retry",cD.OFFLINE)}))}async request(e,t,i,n){const r=MD(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new cp(((t,i)=>{if(this.connectionState===vx.CONNECTED)return t();const n=()=>{this.off(Cx.WS_CLOSED,r),t()},r=()=>{this.off(Cx.WS_CONNECTED,n),i(new qL(PN.WS_ABORT))};this.once(Cx.WS_CONNECTED,n),this.once(Cx.WS_CLOSED,r),e!==Ix.PUBLISH&&e!==Ix.PUBLISH_DATASTREAM&&e!==Ix.SUBSCRIBE&&e!==Ix.SUBSCRIBE_DATASTREAM&&e!==Ix.UNSUBSCRIBE&&e!==Ix.UNSUBSCRIBE_DATASTREAM&&e!==Ix.UNPUBLISH&&e!==Ix.UNPUBLISH_DATASTREAM&&e!==Ix.CONTROL&&e!==Ix.RESTART_ICE||this.once(Cx.DISCONNECT_P2P,(()=>{i(new qL(PN.DISCONNECT_P2P))})),e!==Ix.PUBLISH&&e!==Ix.RESTART_ICE||this.once(Cx.ABORT_P2P_EXECUTION,(()=>{i(new qL(PN.DISCONNECT_P2P))}))}));if(this.connectionState!==vx.CONNECTING&&this.connectionState!==vx.RECONNECTING||e===Ix.JOIN||e===Ix.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new cp(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(Cx.WS_CLOSED,c),this.off(Cx.WS_RECONNECTING,c),this.emit(Cx.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new qL(PN.WS_ABORT,"type: ".concat(e))),this.off(Cx.WS_CLOSED,c),this.off(Cx.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(Cx.WS_CLOSED,c),this.once(Cx.WS_RECONNECTING,c),kD(VP("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(gL.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(Cx.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===vx.CLOSED||e===Ix.LEAVE)throw new qL(PN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ix.JOIN||e===Ix.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=hF(l),h=new qL(PN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(gL.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===Rx.ERR_TOO_MANY_BROADCASTERS?e===Ix.JOIN||e===Ix.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===Rx.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,gL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",cD.MULTI_IP)):this.reconnect(u.action,cD.SERVER_ERROR),e===Ix.JOIN||e===Ix.REJOIN?null:e===Ix.RESTART_ICE&&i?h.throw():await this.request(e,t)))}waitMessage(e,t){return new cp((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void gL.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(yx.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=VP("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==vx.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)}),VP("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,this.reconnectingFromConnecting=!1,new cp(((i,n)=>{this.once(Cx.WS_CONNECTED,(()=>i(this.joinResponse))),this.once(Cx.WS_CLOSED,(e=>n(this.initError||new qL(PN.WS_ABORT,e)))),this.connectionState=vx.CONNECTING,this.websocket.init(e,5e3,t).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||tD.LEAVE,this.connectionState=vx.CLOSED,gL.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.websocket.isFirstJoin&&!0===pD(this,Cx.SHOULD_ENTER_RECONNECTING,void 0)||this.emit(Cx.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await uD(this,Cx.REQUEST_JOIN_INFO);this.store.joinReq();const t=await this.request(Ix.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(Cx.REPORT_JOIN_GATEWAY,Fx.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(Cx.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.websocket.disableQueryReconnectingWhenConnecting(),this.connectionState=vx.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new qL(PN.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=_D(this,Cx.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Ix.REJOIN,e);return!!t&&(this.connectionState=vx.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Ax.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Ax.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Ax.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Ax.MUTE_AUDIO,{uid:e.uid}):this.emit(Ax.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Ax.MUTE_VIDEO,{uid:e.uid}):this.emit(Ax.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Ax.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Ax.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Ax.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Ax.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Ax.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(Ix.DOWNGRADE_CODEC,t)}handleNotification(e){gL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=hF(e.code);if(28===e.code&&"detail"in e&&(gL.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(Cx.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===Rx.ERR_REPEAT_JOIN_CHANNEL&&VP("IGNORE_UID_CHECK")?void this.close(tD.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(tD.UID_BANNED),void this.close()):e.code===Rx.K_VOS_FALLBACK&&"detail"in e?(gL.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&VP("ENABLE_QUALITY_FALLBACK")?void uD(this,Cx.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{gL.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&VP("ENABLE_FALLBACK_TO_HLS")?(this.emit(Cx.VOS_FALLBACK,e.detail),void this.close(tD.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,cD.SERVER_ERROR);gL.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=VP("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(gL.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>VP("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",cD.TIMEOUT):this.request(Ix.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),VP("REPORT_STATS")&&this.send(Ix.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const e=this.websocket.getWsInflateData(),t=e.wsInflateLength,i=e.wsDeflateLength;0!==t&&0!==i&&this.upload(yx.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:i,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(Ox.SHOULD_ENTER_RECONNECTING,((e,t)=>{const i=!0===pD(this,Cx.SHOULD_ENTER_RECONNECTING,e);this.reconnectingFromConnecting=i,t(i)})),this.websocket.on(Ox.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(Cx.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Ox.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Ox.CLOSED,(()=>{this.connectionState=vx.CLOSED})),this.websocket.on(Ox.FAILED,(()=>{this._disconnectedReason=tD.NETWORK_ERROR,this.connectionState=vx.CLOSED})),this.websocket.on(Ox.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vx.CONNECTED||this.reconnectingFromConnecting?this.connectionState=vx.RECONNECTING:this.connectionState=vx.CONNECTING,this.reconnectingFromConnecting=!1})),this.websocket.on(Ox.WILL_RECONNECT,((e,t,i)=>{const n=_D(this,Cx.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(gL.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=Fx.P2P_DISCONNECTED),r&&(gL.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(Cx.REPORT_JOIN_GATEWAY,t||Fx.UNKNOWN_REASON,this.reportUrl||""),this.reconnectToken=void 0,this.emit(Cx.DISCONNECT_P2P)),"retry"!==e&&this.store.flexiblePC&&(this.store.flexiblePC=!1),i(e)})),this.websocket.on(Ox.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{gL.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",cD.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(Cx.REPORT_JOIN_GATEWAY,e,this.reportUrl||""),e instanceof qL){if(e.code===PN.UNEXPECTED_RESPONSE&&e.data.code===Rx.ERR_NO_AUTHORIZED)return this.initError=new qL(PN.TOKEN_EXPIRE,"dynamic key expired"),void this.close(tD.TOKEN_EXPIRE);gL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",cD.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(Ox.REQUEST_NEW_URLS,((e,t)=>{uD(this,Cx.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Ox.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Ax.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(Ox.ON_FALLBACK,(()=>{VP("ENABLE_FALLBACK_TO_HLS")&&this.emit(Cx.VOS_FALLBACK,"fallback_hls")}))}}var AF=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}(AF||{});function bF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function OF(e,t){return typeof VP(e)===t?VP(e):void 0}function wF(){try{const e=VP("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?bF(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):bF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},e)}catch(e){return gL.debug("handle gateway attributes failed: ",e),{}}}function NF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function DF(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NF(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function PF(e,t,i,n){var r,o,s,a,c;let d=n.key,l=n.role,u=n.joinGatewayStartTime,h=n.hasChangeBGPAddress,p=n.isPreallocation,_=n.ortc,E=n.currentURLIndex;const f=Object.assign({},t.apResponse);"signalResponse"in f&&f.signalResponse&&(p=!1,delete f.signalResponse);let m=VP("REPORT_APP_SCENARIO");if("string"!=typeof m)try{m=JSON.stringify(m)}catch(e){m=void 0}m&&m.length>128&&(m=void 0);const S=$L(e),g=ZL(e),T=(null===(r=e.preSubOptions)||void 0===r?void 0:r.length)||0,R=T>0?null===(o=e.preSubOptions)||void 0===o?void 0:o.map((e=>e.uid)):void 0,v=OF("PRE_SUB_NUM","number")||1,C=T>v?T:v,I=wF(),y=sN(87)||iN()||lN(117),A=(function(){const e=Jw();if(e.name!==Hw.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}()||hN(18,4,!1))&&_N(18,6,!0)&&"h264"===i.codec&&VP("ENABLE_ABSSENDTIME_AS_SENTTS"),b=!("CN"!==(null===(s=f.detail)||void 0===s?void 0:s[3])||!VP("ENABLE_QUALITY_FALLBACK"))&&VP("ENABLE_QUALITY_FALLBACK"),O=!!VP("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(a=f.detail)||void 0===a?void 0:a[5]),w={license:t.license,p2p_id:e.p2pId,session_id:t.sid,app_id:t.appId,channel_key:d,channel_name:t.cname,sdk_version:bP,browser:navigator.userAgent,process_id:VP("PROCESS_ID"),mode:e.useP2P?"p2p":i.mode,codec:i.codec,role:l,has_changed_gateway:O||h,ap_response:f,extend:VP("JOIN_EXTEND"),details:{6:t.stringUid,cservice_map:"proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:t.optionalInfo,appScenario:m,attributes:{userAttributes:DF(DF({enableEncodedTransform:(!!VP("ENABLE_AUDIO_METADATA")||!!VP("ENABLE_AUDIO_PTS"))&&y||!!VP("ENABLE_AUDIO_TOPN")&&cN(Hw.CHROME,87,116)||void 0,enableAudioMetadata:!!VP("ENABLE_AUDIO_METADATA")&&y,enableAudioPts:!!VP("ENABLE_AUDIO_PTS")&&y,topnSmoothLevel:VP("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:VP("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:VP("TOPN_SWITCH_HOLD_MS"),topnAudioGain:VP("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:VP("ENABLE_PUBLISHED_USER_LIST"),enableUserList:VP("ENABLE_USER_LIST"),maxSubscription:VP("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:OF("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:OF("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:OF("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===VP("USE_PUB_RTX")||!0===VP("USE_SUB_RTX")||void 0,disableFEC:VP("DISABLE_FEC"),enableNTPReport:!!VP("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:g,enableFulllinkAvSync:!!VP("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:OF("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!VP("FORCE_ENABLE_AUT_CC")||!QL()&&(!!VP("ENABLE_AUT_FEEDBACK")||void 0),rtm2Flag:"number"==typeof t.rtmFlag?t.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!VP("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:OF("USE_XR","boolean"),enableLossbasedBwe:OF("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!VP("FORCE_ENABLE_AUT_CC")||!QL()&&(!!VP("ENABLE_AUT_CC")||void 0),enableCCFallback:OF("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:p,preSubUid:S?R:void 0,preSubNum:S?C:void 0,enablePubTWCC:OF("PUBLISH_TWCC","boolean"),enableSubTWCC:OF("SUBSCRIBE_TWCC","boolean"),enablePubRTX:OF("USE_PUB_RTX","boolean"),enableSubRTX:OF("USE_SUB_RTX","boolean"),enableSubSVC:VP("ENABLE_SVC")?VP("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(VP("SVC"))&&0!==VP("SVC").length?VP("SVC"):void 0,enableSvcExtended:VP("ENABLE_SVC")&&Array.isArray(VP("SVC_EXTENDED"))&&0!==VP("SVC_EXTENDED").length?VP("SVC_EXTENDED"):void 0,enableVosFallback:VP("ENABLE_VOS_FALLBACK"),enableQualityFallback:b,flexiblePC:e.flexiblePC||void 0},I),{},{audioDuplicate:OF("ENABLE_AUDIO_RED","boolean")?null!==(c=OF("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!A||void 0,enableDualStreamFlag:OF("ENABLE_DUAL_STREAM_FLAG","boolean"),enableAiClientMode:!!e.aiClientMode||void 0,enableAiClientBbrStrategy:!!e.aiClientMode||void 0,dcMediaStreamId:e.aiClientMode?e.mediaDcId:void 0})},join_ts:u,ortc:_||{}};return t.stringUid&&(w.string_uid=t.stringUid),t.aesmode&&t.aespassword&&(w.aes_mode=t.aesmode,VP("ENCRYPT_AES")?(w.aes_secret=t.aespassword,w.aes_encrypt=!0):w.aes_secret=t.aespassword,t.aessalt&&(w.aes_salt=t.aessalt)),f.addresses[E]&&(w.ap_response.ticket=f.addresses[E].ticket,delete f.addresses),void 0!==t.defaultVideoStream&&(w.default_video_stream=t.defaultVideoStream),w}function LF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function kF(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?LF(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):LF(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}sN(87)||iN()||lN(117);let MF=0;function UF(e){const t=VP("TURN_DOMAINS");MF=(MF+1)%t.length;const i=t[MF]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(i):(gL.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function VF(e){try{const t=VP("TURN_DOMAINS"),i=VP("GATEWAY_DOMAINS").concat(t).find((t=>Un(e).call(e,t)));if(i){return e.split(".".concat(i))[0].replace(/-/g,".")}return e}catch(t){return gL.debug("serverUrlToIp error, fallback to url",e),e}}function xF(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(VP("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let t=e.ip,i=e.port;return{address:"".concat(t,":").concat(i)}}));const i=VP("GATEWAY_DOMAINS");let n=i[1]&&Un(t).call(t,i[1])?1:0;return e.map((e=>{let t=e.domain_prefix,r=e.port,o=e.ip;if(t)return{address:"".concat(t,".").concat(i[n++%i.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(r):"".concat(o,":").concat(r);return s||gL.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{ip:o,port:r,address:a}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t<e.length;t++){var r;const n=zg(r=e[t]).call(r);i[t]&&n&&(i[t].ip6=n)}}const o=e.detail&&e.detail.candidate;let s;if(o){const e=HI(o.split(":"),2),t=e[0],i=e[1];t&&i&&(s={port:Number(i),ip:t,address:"".concat(t,":").concat(i)})}return{gatewayAddrs:i,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function FF(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function BF(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(FF(t.width),"x").concat(FF(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function jF(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 GF(e,t){let i,n,r;switch(t){case AF.CHOOSE_SERVER:n=4096,r="choose server";break;case AF.CLOUD_PROXY:n=1048576,r="proxy";break;case AF.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case AF.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new qL(PN.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>kF(kF({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:kF(kF({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})})),!i)throw new qL(PN.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function WF(e,t){return await cp.all(e.addresses.map((async e=>({address:UF(e.ip),tcpport:e.port,udpport:e.port,username:t&&VP("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():NP.username,password:t&&VP("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await qN(t.toString()):NP.password}))))}function HF(e,t){const i=t.getMediaStreamTrack(!0).getSettings(),n=t.videoHeight||i.height,r=t.videoWidth||i.width;return n&&r?Math.max(Math.min(n,r)/Math.min(FF(e.height),FF(e.width)),1):(gL.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function KF(e){let t=e.candidateType,i=e.relayProtocol,n=e.type,r=e.address,o=e.port;const s={candidateType:t,relayProtocol:i,protocol:e.protocol};if("local-candidate"!==n){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),s.address=e.join("."),s.port=o}return s}function YF(e){const t=e.split(":"),i=e.split(/[-.]/),n=Un(e).call(e,"-")?"-":".";let r=e;return t.length>1?i.length>1?(i[1]="**",r=i[0]+n+"**:"+t[t.length-1]):r=t.length>2?t[0]+n+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(r=i[0]+n+"**"),r}const qF=!1;function JF(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:VP("SVC_MODE");if(VP("ENABLE_SVC"))return function(e){return e in mP}(e)?e:mP.L1T3}const zF={[zx.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"}],[zx.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 XF(e,t,i){t.forEach((t=>{var n;const r=zF[e].find((e=>{var i;let n=e.key;return Un(i=t.extensionName).call(i,n)}));if(!r)return;const o=i.find((e=>{let t=e.extensionName;return Un(t).call(t,r.key)}));o&&Un(n=o.extensionName).call(n,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function QF(e,t){t.forEach((t=>{var i;const n=zF[e].find((e=>{var i;let n=e.key;return Un(i=t.extensionName).call(i,n)}));Un(i=t.extensionName).call(i,"gdpr_forbidden")&&n&&(t.extensionName=n.extensionName)}))}function $F(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Un(e).call(e,"abs-send-time")}function ZF(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Un(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function eB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function tB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?eB(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):eB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function iB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const r=t.filterRTX,o=t.filterVideoFec,s=t.filterAudioFec,a=t.filterAudioCodec,c=t.filterVideoCodec,d=t.unsupportedVideoUplinkCodec,l=t.unsupportedVideoDownlinkCodec,u=i.useXR;let h=[],p=[],_=[],E=[],f=!1,m=!1;if(JP(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||f||(p=e.attributes.payloads,E=e.attributes.extmaps,f=!0),"audio"!==e.media.mediaType||m||(h=e.attributes.payloads,_=e.attributes.extmaps,m=!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=mB(e,p).map((e=>e.payloadType)),i=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!Un(i).call(i,e.payloadType)))}if(s&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(h=h.filter((e=>{var t;return Un(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 Un(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(r?[]:mB(e,p))}const S=VP("UNSUPPORTED_VIDEO_CODEC");if(S&&S.length>0){const e=p.filter((e=>e.rtpMap&&Un(S).call(S,e.rtpMap.encodingName.toLowerCase()))),t=mB(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Un(i).call(i,e.payloadType))),gL.debug("unsupportedVideoCodec: ".concat(S,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===n){const e=p.filter((e=>e.rtpMap&&Un(d).call(d,e.rtpMap.encodingName.toLowerCase()))),t=mB(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Un(i).call(i,e.payloadType))),gL.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===n){const e=p.filter((e=>e.rtpMap&&Un(l).call(l,e.rtpMap.encodingName.toLowerCase()))),t=mB(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Un(i).call(i,e.payloadType))),gL.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function nB(e){const t=JP(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function rB(e,t,i){const n=e.cname;let r=[];t&&(r=sB(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:{}}))),gL.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:_B(e.rtpCapabilities),setup:a,cname:n,preSSRCs:oB(i)}}function oB(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach((e=>{t.push({kind:zx.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:zx.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),t}function sB(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:{}}],gL.debug("Using remote candidate from AP ".concat(YF(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:{}}),gL.debug("Using IPV6 remote candidate from AP ".concat(YF(e.ip6),":").concat(e.port)))),t}function aB(e,t,i){const n=[],r=[];return e.forEach((e=>{let o=e.ssrcId,s=e.rtx;const a=MD(8,"track-"),c={ssrcId:o,attributes:tB({label:a,mslabel:i=i||MD(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:tB({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:n,ssrcGroups:r}}function cB(e,t){t instanceof DU&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===n&&"number"==typeof VP("OPUS_PTIME")?e.fmtp.parameters.ptime=VP("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&("pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!rN()&&(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 PU&&"opus"===n&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function dB(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 lB(e,t){var i,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&&VP("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof yV&&t._encoderConfig))return;const r=t._encoderConfig;zL().supportMinBitrate&&r.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;Un(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(r.bitrateMin))})),Un(i=t._hints).call(i,gk.SCREEN_TRACK)||zL().supportMinBitrate&&!Un(n=t._hints).call(n,gk.LOW_STREAM)&&r.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;Un(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(VP("X_GOOGLE_START_BITRATE")||Math.floor(r.bitrateMax)))}))}function uB(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find((e=>ZF(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>ZF(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>ZF(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>$F(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===i))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>$F(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)}))}}async function hB(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=iB(i,e,t,"sendonly"),r=iB(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(pB(n,r,"videoExtensions",o,s,a),pB(n,r,"videoCodecs",o,s,a),pB(n,r,"audioExtensions",o,s,a),pB(n,r,"audioCodecs",o,s,a),VP("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(a.videoCodecs.forEach(((i,n)=>{var r;if("h264"===(null===(r=i.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){var o,s;const r=a.videoCodecs[n+1],c=r&&vB(i,r),d=null===(o=i.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(s=i.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==VP("FIRST_H264_PROFILE_LEVEL_ID")||VP("FIRST_PACKETIZATION_MODE")&&l!==VP("FIRST_PACKETIZATION_MODE")?c?t.push([i,r]):t.push([i]):c?e.push([i,r]):e.push([i])}})),e.length>0&&t.length>0){gL.debug("raising H264 baseline profile priority"),a.videoCodecs.forEach(((i,n)=>{var r;if("h264"===(null===(r=i.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){const r=vB(i,a.videoCodecs[n+1]),o=e.shift()||t.shift()||[];o.length>0&&(r?a.videoCodecs.splice(n,2,...o):a.videoCodecs.splice(n,1,...o))}}));const i=s.videoCodecs.filter((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==VP("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=mB(i,s.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!Un(t).call(t,e.payloadType)))}VP("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==VP("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:s,sendrecv:a}}return{send:o,recv:s,sendrecv:a}}(e,t,(await i.createOffer()).sdp),r=n.send,o=n.recv,s=n.sendrecv;try{i.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function pB(e,t,i,n,r,o){if("videoExtensions"===i||"audioExtensions"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}if("videoCodecs"===i||"audioCodecs"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}}function _B(e){const t=e.send,i=e.recv,n=e.sendrecv;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=ID(n),i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=ID(n),{send:r,recv:o}}function EB(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 fB(e,t,i,n){let r=[];if(e===zx.VIDEO){if(VP("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter((e=>{var t;return Un(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===VP("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Un(i).call(i,n)?e.push(t):Un(i).call(i,"vp9")?o.push(t):Un(i).call(i,"vp8")?s.push(t):Un(i).call(i,"h264")&&a.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==a.length&&(e=a,t="h264"),gL.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===r.length&&(gL.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),VP("USE_PUB_RTX")||VP("USE_SUB_RTX")){const e=mB(r,t.videoCodecs);r=[...r,...e]}}else{r=t.audioCodecs.filter((e=>{var t;return Un(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)}));const e=t.audioCodecs.filter((e=>{var t;return Un(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")}));0===r.length&&(gL.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Un(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")}))),VP("ENABLE_AUDIO_RED")&&0!==e.length&&(r=[...e,...r])}return r}function mB(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Un(i).call(i,e.fmtp&&e.fmtp.parameters.apt)))}async function SB(e,t,i){const n=t.toString(),r=TB(n,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:n});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=gB(s,i||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function gB(e,t,i){if(VP("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=JP(e),r=t.useXR;return n.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(i)&&!Un(i).call(i,e.attributes.mid)||("audio"===e.media.mediaType&&EB(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!VP("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&&Un(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"})}))))})),zP(n)}function TB(e,t,i,n){if(VP("SDP_LOGGING"))return gL.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{TB(e,"answer","local"===i?"remote":"local",n)}:void 0}function RB(e){const t=VP("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Un(e).call(e,t)))}function vB(e,t){try{var i;return(null===(i=e.fmtp)||void 0===i?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}var CB,IB;const yB={};function AB(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&gL.debug("install service ".concat(e.name)),yB[e.name]=e}function bB(e){const t=yB[e];if(!t)throw new LN(PN.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function OB(e){return!!yB[e]}function wB(e,t){return bB("DataStream").create(e,t)}const NB=null!==(IB=(CB=ky).__aiClientControllerCallbacks)&&void 0!==IB?IB:CB.__aiClientControllerCallbacks={onMute:null,onUnmute:null,onPlay:null,onStop:null},DB={registerCallbacks(e){NB.onMute=e.onMute,NB.onUnmute=e.onUnmute,NB.onPlay=e.onPlay,NB.onStop=e.onStop},unregisterCallbacks(){NB.onMute=null,NB.onUnmute=null,NB.onPlay=null,NB.onStop=null},mute(){var e;null===(e=NB.onMute)||void 0===e||e.call(NB)},unmute(){var e;null===(e=NB.onUnmute)||void 0===e||e.call(NB)},play(){var e;null===(e=NB.onPlay)||void 0===e||e.call(NB)},stop(){var e;null===(e=NB.onStop)||void 0===e||e.call(NB)}};function PB(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}function LB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function kB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?LB(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):LB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const MB=new Map;class UB extends JN{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(xx.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(xx.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){gL.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var i,n,r;super(),Zb(this,"store",void 0),Zb(this,"joinInfo",void 0),Zb(this,"key",void 0),Zb(this,"ntpOffset",0),Zb(this,"usingProxy",!1),Zb(this,"signal",void 0),Zb(this,"role",void 0),Zb(this,"isPreallocation",void 0),Zb(this,"isPreSub",void 0),Zb(this,"inChannelInfo",{joinAt:null,duration:0}),Zb(this,"spec",void 0),Zb(this,"_state","DISCONNECTED"),Zb(this,"_statsCollector",void 0),Zb(this,"_disconnectedReason",void 0),Zb(this,"isSignalRecover",!1),Zb(this,"hasChangeBGPAddress",!1),Zb(this,"trafficStatsInterval",void 0),Zb(this,"networkQualityInterval",void 0),Zb(this,"_joinGatewayStartTime",0),Zb(this,"_signalTimeout",!1),Zb(this,"_clientRoleOptions",void 0),Zb(this,"_isProactiveJoin",!1),Zb(this,"_sdpEndpointJoin",void 0),this.store=e,this.spec=t,this.signal=this.store.useP2P?(i={spec:kB(kB({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(n=(r=bB("P2PChannel")).createSubmodule)||void 0===n?void 0:n.call(r,i)):this.store.useDcSignal?function(e){return bB("DataChannelSignal").create(e)}({spec:kB(kB({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new yF(kB(kB({},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}join(e,t){return this.joinInternal(e,t)}joinWithSDPEndpoint(e,t,i){return this.joinInternal(e,t,i)}async joinInternal(e,t,i){if(this.store.useDcSignal){let t=!1;const i=e.apResponse.addresses[0],n=i.iceUfrag||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert),r=i.icePwd||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert);"disabled"!==e.cloudProxyServer?(gL.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):PB(n,r)?e.apResponse.addresses.some((e=>e.fingerprint))||VP("FINGERPRINT")||(gL.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0):(gL.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 n=Date.now();let r=MB.get(e.cname);if(r||(r=new Map,MB.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new qL(PN.UID_CONFLICT);throw YL.joinGateway(e.sid,{lts:n,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;const o=i?{attempt:i,startAt:n,initialRole:i.initialRole,roleReplaySent:!1,timingReported:!1}:void 0;this._sdpEndpointJoin=o,o&&i.channelReady.then((e=>{var t;let i=e.proof;this._sdpEndpointJoin===o&&(null!==(t=o.iceConnectedAt)&&void 0!==t||(o.iceConnectedAt=i.at),this.reportSDPEndpointJoinTiming())}));let s=0;this.joinGatewayStartTime=n;const a=e.proxyServer,c=this.store.useDcSignal?"datachannel":"websocket";try{gL.debug("[".concat(this.store.clientId,"] use ").concat(c," ").concat(o?"with sdpednpoint":""," join uid ").concat(s));const t=e.gatewayAddrs.map((t=>{const i=HI(t.address.split(":"),2),n={host:i[0],port:i[1]};return e.proxyServer&&(n.proxy=e.proxyServer),n}));let n;this.store.useDcSignal?n=await this.signal.init(e.apResponse.addresses):o?(this.handlePrePc(i),n=await this.initSDPEndpointSignal(t,o)):(function(e){return!(QL()||VP("USE_NEW_TOKEN")||!VP("ENABLE_PREALLOC_PC")&&(null==e||!e.autoSubscribe||VP("FORCE_DISABLE_AUTO_SUB")))}(this.store)&&this.handlePrePc(),n=await this.signal.init(t)),s=n.uid,gL.debug("[".concat(this.store.clientId,"] ").concat(c," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var d;if(t.code===PN.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else YL.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(d=t.data)||void 0===d?void 0:d.desc)||t.code,errorMsg:t.message,addr:this.signal.reportUrl,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload});if(t&&t.code===PN.INIT_DATACHANNEL_TIMEOUT)throw gL.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw gL.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(),gL.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{gL.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(xx.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(xx.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(xx.NETWORK_QUALITY,{uplinkNetworkQuality:jF(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:jF(this._statsCollector.trafficStats.B_dnq)}):this.emit(xx.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async initSDPEndpointSignal(e,t){var i;const n=this.signal.init(e,{queryReconnectingWhenConnecting:!0}).then((e=>{var i,n;const r=null!==(i=this.store.keyMetrics.joinRep)&&void 0!==i?i:Date.now();return null!==(n=t.joinResponseAt)&&void 0!==n||(t.joinResponseAt=r),this.reportSDPEndpointJoinTiming(),{kind:"joinres",response:e,at:r}})),r=VP("ENABLE_ICE_EARLY_JOIN")?await cp.race([n,t.attempt.channelReady]):await n;var o;return"ice"===r.kind?this._sdpEndpointJoin!==t?(await n).response:(null!==(o=t.iceConnectedAt)&&void 0!==o||(t.iceConnectedAt=r.proof.at),t.winner={type:"ice",at:r.proof.at},this.reportSDPEndpointJoinTiming(),t.attempt.preJoinResponse):(null!==(i=t.joinResponseAt)&&void 0!==i||(t.joinResponseAt=r.at),t.winner={type:"joinres",at:r.at},this.reportSDPEndpointJoinTiming(),r.response)}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!==tD.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==vx.CONNECTED||await function(e,t){return t===1/0?e:cp.race([e,LD(t)])}(this.signal.request(Ix.LEAVE,void 0,!0),3e3)}catch(e){gL.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==tD.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:VP("PUB_EXTEND"),twcc:!!VP("PUBLISH_TWCC"),rtx:!!VP("USE_PUB_RTX")};try{return(await this.signal.request(Ix.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Rx.ERR_PUBLISH_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(Ix.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===Rx.ERR_PUBLISH_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(Ix.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){gL.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cp.all(e.map((e=>this.signal.request(Ix.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){gL.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!VP("SUBSCRIBE_TWCC"),rtx:!!VP("USE_SUB_RTX")||void 0,extend:VP("SUB_EXTEND"),svc:Array.isArray(VP("SVC"))&&0!==VP("SVC").length?VP("SVC"):void 0,dc_media_stream_id:this.store.aiClientMode?this.store.mediaDcId:void 0};try{return await this.signal.request(Ix.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===Rx.ERR_SUBSCRIBE_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!VP("SUBSCRIBE_TWCC"),rtx:!!VP("USE_SUB_RTX"),extend:VP("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(VP("SVC"))&&0!==VP("SVC").length?VP("SVC"):void 0,dc_media_stream_id:this.store.aiClientMode?this.store.mediaDcId:void 0};try{return(await this.signal.request(Ix.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Rx.ERR_SUBSCRIBE_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(Ix.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===Rx.ERR_SUBSCRIBE_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!VP("USE_SUB_RTX"),twcc:!!VP("SUBSCRIBE_TWCC"),svc:Array.isArray(VP("SVC"))&&0!==VP("SVC").length?VP("SVC"):void 0};try{return await this.signal.request(Ix.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===Rx.ERR_SUBSCRIBE_REQUEST_INVALID)return gL.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e,t){const i=function(e,t){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let i=e.frameRate,n=e.width,r=e.height,o=!0;return"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(o=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,n||(o=!1)),"number"!=typeof r&&(r=r.exact||r.ideal||r.max||r.min||0,r||(o=!1)),o?kF({stream_type:0,width:n,height:r,fps:i,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax},t?{optimization_mode:t}:{}):void 0}(e,t);if(i)return this.signal.request(Ix.SET_VIDEO_PROFILE,i);gL.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(Ix.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){gL.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new qL(PN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cp.all(e.map((e=>this.signal.request(Ix.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){gL.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(Ix.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){gL.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const t=e.iceParameters,i=e.dtlsParameters,n=e.rtpCapabilities;return{gatewayEstablishParams:await this.signal.request(Ix.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(Ix.GATEWAY_INFO)}async renewToken(e){await this.signal.request(Ix.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),VP("CLIENT_ROLE_OPTIONS")&&(gL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(VP("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},VP("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),VP("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},VP("CLIENT_ROLE_OPTIONS")),gL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(VP("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0;const r=Object.assign({},t);delete r.delay,delete r.level,await this.signal.request(Ix.SET_CLIENT_ROLE,kB(kB({role:e,level:n,delay:i},r),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,i){await this.signal.request(Ix.SET_DUAL_STREAM_MODE,{mode:e},i,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(Ix.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(Ix.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(Ix.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(Ix.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(Ix.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),kB({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(Ix.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(Ix.GATEWAY_INFO)).version}reset(){if(this._sdpEndpointJoin=void 0,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=MB.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:NP.username,password:NP.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(kB(kB({},NP),{},{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(Ix.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&&CD((()=>{this.emit(xx.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,i;if(!this.joinInfo||!this.key)throw new qL(PN.UNEXPECTED_ERROR,"can not generate join message, no join info");this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(xx.UPDATE_GATEWAY_CONFIG),i=this.store.clientId,Un(QV).call(QV,i)||QV.push(i);return PF(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})}getRejoinMessage(){if(!this.joinInfo)throw new qL(PN.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)}}handlePrePc(e,t,i){if(this.joinInfo){var n,r;this.updateTurnConfigFromSignal();const u=this.getCurrentGatewayAddress(),h=ID(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(VP("NEW_TURN_MODE")&&h&&"disabled"===(null===(r=this.joinInfo)||void 0===r?void 0:r.cloudProxyServer)){var o;let e=h.servers.map((e=>"turnServerURL"in e&&VP("USE_TURN_IP")?kB(kB({},e),{},{turnServerURL:VF(e.turnServerURL)}):e)),t=null===(o=h.serversFromGateway)||void 0===o?void 0:o.map((e=>VP("USE_TURN_IP")?kB(kB({},e),{},{turnServerURL:VF(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],h.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],h.serversFromGateway=t),gL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i,",in pre pc"))}const p=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],_=VP("FINGERPRINT")||p.fingerprint;if(u&&_){var s,a,c,d,l;const n=sB(u);uD(this,xx.PRE_CONNECT_PC,{candidates:n,fingerprint:_,turnServer:h,iceUfrag:p.iceUfrag,icePwd:p.icePwd,originalPreSubSsrcs:null!==(s=null==e||null===(a=e.preJoinResponse.attributes)||void 0===a||null===(a=a.userAttributes)||void 0===a?void 0:a.preSubSsrcs)&&void 0!==s?s:null===(c=this.joinInfo.apResponse.signalResponse)||void 0===c||null===(c=c.attributes)||void 0===c||null===(c=c.userAttributes)||void 0===c?void 0:c.preSubSsrcs,rtpCapabilities:null!==(d=null==e?void 0:e.preJoinResponse.rtpCapabilities)&&void 0!==d?d:null===(l=this.joinInfo.apResponse.signalResponse)||void 0===l?void 0:l.rtpCapabilities,isSDPEndpoint:!!e}).then((e=>{null==t||t(e)})).catch(i||(()=>{}))}}}handleSignalEvents(){this.signal.on(Cx.SHOULD_ENTER_RECONNECTING,((e,t)=>{var i;t("ice"===(null===(i=this._sdpEndpointJoin)||void 0===i||null===(i=i.winner)||void 0===i?void 0:i.type)&&"CONNECTED"===this.state&&this.signal.connectionState===vx.CONNECTING)})),this.signal.on(Cx.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(Cx.WS_RECONNECTING,(e=>{this.joinInfo&&YL.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||cD.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",YL.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:5}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(Cx.WS_CLOSED,(e=>{let t;switch(e){case tD.LEAVE:t=cD.LEAVE;break;case tD.UID_BANNED:case tD.IP_BANNED:case tD.CHANNEL_BANNED:case tD.SERVER_ERROR:t=cD.SERVER_ERROR;break;case tD.FALLBACK:t=cD.FALLBACK;break;case tD.LICENSE_MISSING:case tD.LICENSE_EXPIRED:case tD.LICENSE_MINUTES_EXCEEDED:case tD.LICENSE_PERIOD_INVALID:case tD.LICENSE_MULTIPLE_SDK_SERVICE:case tD.LICENSE_ILLEGAL:case tD.TOKEN_EXPIRE:t=e;break;default:t=cD.NETWORK_ERROR}gL.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+cD.NETWORK_ERROR)),this.joinInfo&&YL.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===tD.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==tD.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(Cx.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",!this.joinInfo)return;const e=this._sdpEndpointJoin;if(e&&!e.roleReplaySent&&e.initialRole!==this.role){const t=this.role,i=VP("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e.roleReplaySent=!0,gL.debug("[".concat(this.store.clientId,"] JoinV4 role changed during early join, replay set client role: ").concat(t)),this.setClientRole(t,i).catch((e=>{gL.debug("[".concat(this.store.clientId,"] JoinV4 role replay failed"),e)}))}else if("audience"===this.role){const e=VP("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(gL.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(YL.joinGateway(this.joinInfo.sid,kB({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:e?"2":"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess},null!=e&&e.winner?{winner:e.winner.type,winnerAt:e.winner.at}:{})),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 gL.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));UP("EVENT_REPORT_DOMAIN",e[1]),UP("EVENT_REPORT_BACKUP_DOMAIN",e[1]),UP("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}})),this.signal.on(Ax.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(Ax.ON_P2P_OK,(()=>{var e;const t=this._sdpEndpointJoin;t&&(null!==(e=t.p2pOkAt)&&void 0!==e||(t.p2pOkAt=Date.now()),this.reportSDPEndpointJoinTiming())})),this.signal.on(Cx.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new qL(PN.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,this._sdpEndpointJoin=void 0,uD(this,xx.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(Cx.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n,r,o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage());const s=ID(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(VP("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&&VP("USE_TURN_IP")?kB(kB({},e),{},{turnServerURL:VF(e.turnServerURL)}):e)),t=null===(a=s.serversFromGateway)||void 0===a?void 0:a.map((e=>VP("USE_TURN_IP")?kB(kB({},e),{},{turnServerURL:VF(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),gL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const c=await uD(this,xx.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer}),d=c.iceParameters,l=c.dtlsParameters,u=c.rtpCapabilities;try{e(this.getJoinMessage({iceParameters:d,dtlsParameters:l,rtpCapabilities:u,version:"2"}))}catch(e){t(e)}})),this.signal.on(Cx.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(Cx.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var r;e instanceof qL?(i=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,n=e.message):i=e;YL.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})})),this.signal.on(Cx.IS_P2P_DISCONNECTED,(e=>{e(_D(this,xx.IS_P2P_DISCONNECTED))})),this.signal.on(Cx.DISCONNECT_P2P,(()=>{this._sdpEndpointJoin=void 0,this.emit(xx.DISCONNECT_P2P)})),this.signal.on(Cx.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(Cx.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(Cx.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(xx.JOIN_RESPONSE,e,t)})),this.signal.on(Cx.PRE_CONNECT_PC,(async(e,t)=>{this.handlePrePc(void 0,e,t)})),this.signal.on(Cx.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof VP("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(VP("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(Cx.VOS_FALLBACK,(e=>{this.emit(xx.VOS_FALLBACK,e)})),this.signal.on(Cx.DATACHANNEL_FAILBACK,(e=>{gL.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(xx.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(Ix.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(Ix.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw gL.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(Ix.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(Ix.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw gL.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(Ix.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Vx.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ix.CONTROL,i,!0,!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Vx.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ix.CONTROL,i,!0,!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===zx.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ix.CONTROL,i,!0,!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===zx.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ix.CONTROL,i,!0,!0)}catch(e){throw gL.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(Ix.RESTART_ICE,t,!0)}catch(e){throw gL.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||cD.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!VP("GATEWAY_WSS_ADDRESS"))return VP("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(gL.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}reportSDPEndpointJoinTiming(){const e=this._sdpEndpointJoin,t=this.joinInfo;e&&t&&!e.timingReported&&e.winner&&e.p2pOkAt&&void 0!==e.iceConnectedAt&&void 0!==e.joinResponseAt&&(e.timingReported=!0,YL.joinGateway(t.sid,{lts:e.startAt,succ:!0,ec:null,vid:t.vid,addr:this.signal.url,uid:t.uid,cid:t.cid,firstSuccess:this._isProactiveJoin,isProxy:!!t.proxyServer||this.usingProxy,signalChannel:"2",preload:t.preload,isABTestSuccess:this.store.isABTestSuccess,iceConnectedAt:e.iceConnectedAt,joinResponseAt:e.joinResponseAt,winnerAt:e.winner.at,winner:e.winner.type,reportAt:e.p2pOkAt}),this._isProactiveJoin=!1,this._sdpEndpointJoin===e&&(this._sdpEndpointJoin=void 0))}async setPublishAudioFilterEnabled(e){await this.signal.request(Ix.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(tD.FALLBACK)),this.store.useDcSignal=!1,this.signal=new yF(kB(kB({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(xx.RESET_SIGNAL)}}let VB=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),xB=0,FB=0;function BB(e,t,i,n){return new cp(((r,o)=>{t.timeout=t.timeout||VP("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),xB+=DD(t.data)):i&&(t.data.size?xB+=t.data.size:t.data instanceof FormData?xB+=PD(t.data):xB+=DD(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Vw.request(t).then((e=>{"string"==typeof e.data?FB+=DD(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?FB+=e.data.byteLength:FB+=DD(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Vw.isCancel(e)?o(new qL(PN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new qL(PN.NETWORK_TIMEOUT,e.message)):e.response?o(new qL(PN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new qL(PN.NETWORK_ERROR,e.message))}))}))}
/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function i(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e};var r,o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var i=0;i<e.length;++i){var n=e[i];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var i=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in i))break e;i=i[s]}(t=t(r=i[e=e[e.length-1]]))!=r&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t})}}function a(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:i(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,n(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var i="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<t.length;r++){var s=o[t[r]];"function"==typeof s&&"function"!=typeof s.prototype[e]&&n(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(i(this))}})}return e})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var d;e:{var l={};try{l.__proto__={a:!0},d=l.a;break e}catch(e){}d=!1}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var u=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function _(e,t){return e.h=3,{value:t}}function E(e){this.g=new h,this.G=e}function f(e,t,i,n){try{var r=t.call(e.g.j,i);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var o=r.value}catch(t){return e.g.j=null,e.g.s(t),m(e)}return e.g.j=null,n.call(e.g,o),m(e)}function m(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function S(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){p(e.g);var i=e.g.j;return i?f(e,"return"in i?i.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),m(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function g(e,t){return t=new S(new E(t)),u&&e.prototype&&u(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},E.prototype.o=function(e){return p(this.g),this.g.j?f(this,this.g.j.next,e,this.g.o):(this.g.o(e),m(this))},E.prototype.s=function(e){return p(this.g),this.g.j?f(this,this.g.j.throw,e,this.g.o):(this.g.s(e),m(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var i=0,n=!1,r={next:function(){if(!n&&i<e.length){var r=i++;return{value:t(r,e[r]),done:!1}}return n=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var T=function(e,t){for(var i=0;i<e.length;i++)t(e[i])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},v=function(e,t,i){return t instanceof Blob?(i=void 0!==i?String(i+""):"string"==typeof t.name?t.name:"blob",t.name===i&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],i)),[String(e),t]):[String(e),String(t)]},C=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},I="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,y=I.FormData,A=I.XMLHttpRequest&&I.XMLHttpRequest.prototype.send,b=I.Request&&I.fetch,O=I.navigator&&I.navigator.sendBeacon,w=I.Element&&I.Element.prototype,N=I.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in I&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){I.File=function(e,t,i){return e=new Blob(e,i||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),N&&Object.defineProperty(e,N,{value:"File"}),e}}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},P=function(e){this.i=[];var t=this;e&&T(e.elements,(function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var i=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];T(i,(function(i){t.append(e.name,i)}))}else"select-multiple"===e.type||"select-one"===e.type?T(e.options,(function(i){!i.disabled&&i.selected&&t.append(e.name,i.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(i="textarea"===e.type?R(e.value):e.value,t.append(e.name,i))}))};if((e=P.prototype).append=function(e,t,i){C(arguments,2),this.i.push(v(e,t,i))},e.delete=function(e){C(arguments,1);var t=[];e=String(e),T(this.i,(function(i){i[0]!==e&&t.push(i)})),this.i=t},e.entries=function e(){var t,i=this;return g(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=_(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){C(arguments,1);for(var i=c(this),n=i.next();!n.done;n=i.next()){var r=c(n.value);n=r.next().value,r=r.next().value,e.call(t,r,n,this)}},e.get=function(e){C(arguments,1);var t=this.i;e=String(e);for(var i=0;i<t.length;i++)if(t[i][0]===e)return t[i][1];return null},e.getAll=function(e){C(arguments,1);var t=[];return e=String(e),T(this.i,(function(i){i[0]===e&&t.push(i[1])})),t},e.has=function(e){C(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,i,n,r,o=this;return g(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,r=c(n),_(e,r.next().value));i=t.next(),e.h=2}))},e.set=function(e,t,i){C(arguments,2),e=String(e);var n=[],r=v(e,t,i),o=!0;T(this.i,(function(t){t[0]===e?o&&(o=!n.push(r)):n.push(t)})),o&&n.push(r),this.i=n},e.values=function e(){var t,i,n,r,o=this;return g(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,(r=c(n)).next(),_(e,r.next().value));i=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new y,t=c(this),i=t.next();!i.done;i=t.next()){var n=c(i.value);i=n.next().value,n=n.next().value,e.append(i,n)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,n){return"string"==typeof e?t.push(i+D(R(n))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(i+D(R(n))+'"; filename="'+D(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")})),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},P.prototype[Symbol.iterator]=function(){return this.entries()},P.prototype.toString=function(){return"[object FormData]"},w&&!w.matches&&(w.matches=w.matchesSelector||w.mozMatchesSelector||w.msMatchesSelector||w.oMatchesSelector||w.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),N&&(P.prototype[N]="FormData"),A){var L=I.XMLHttpRequest.prototype.setRequestHeader;I.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},I.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),A.call(this,e)):A.call(this,e)}}b&&(I.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),b.call(this,e,t)}),O&&(I.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),O.call(this,e,t)}),I.FormData=P}}();const jB=()=>{const e=VP("AREAS");0===e.length&&e.push(jx.GLOBAL);return sr(e).call(e,((e,t,i)=>{const n=GB(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},GB=e=>e===jx.OVERSEA?"".concat(Wx.ASIA,",").concat(Wx.EUROPE,",").concat(Wx.AFRICA,",").concat(Wx.NORTH_AMERICA,",").concat(Wx.SOUTH_AMERICA,",").concat(Wx.OCEANIA):Wx[e],WB=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=Hx[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},HB={GLOBAL:{ASIA:[jx.CHINA,jx.JAPAN,jx.INDIA,jx.KOREA,jx.HKMC],EUROPE:[],NORTH_AMERICA:[jx.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},KB=Object.keys(HB[jx.GLOBAL]),YB=[jx.CHINA,jx.NORTH_AMERICA,jx.EUROPE,jx.ASIA,jx.JAPAN,jx.INDIA,jx.OCEANIA,jx.SOUTH_AMERICA,jx.AFRICA,jx.KOREA,jx.HKMC,jx.US],qB=function(e,t){let i=[];if(Un(e).call(e,jx.GLOBAL)){const o=[jx.GLOBAL,jx.OVERSEA],s=Object.keys(Hx);if(t===jx.GLOBAL)throw new qL(PN.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===jx.CHINA)i=[jx.OVERSEA];else if(r=t,Un(KB).call(KB,r)){const e=(n=t,HB[jx.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter((e=>!Un(r).call(r,e)))}else if(function(e){let t=!1;return KB.forEach((i=>{var n;Un(n=HB[jx.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return KB.forEach((i=>{var n;Un(n=HB[jx.GLOBAL][i]).call(n,e)&&(t=i)})),t}(t),n=[...o,e,t];i=s.filter((e=>!Un(n).call(n,e)))}else i=e;i=function(e){const t=[];return YB.forEach((i=>{Un(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!Un(YB).call(YB,e))))}(i)}else i=e;var n,r;return i};function JB(e){var t,i;if(!e&&Un(t=VP("AREAS")).call(t,jx.EXTENSIONS))return gL.debug("update area from ap : reset"),void zB(JV,!0);if(!Un(i=VP("AREAS")).call(i,jx.GLOBAL)||!e)return;let n=Hx.EXTENSIONS;n&&(n={CODE:GB(jx.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")]},gL.debug("update area from ap success: ".concat(e,",config is "),n),UP("AREAS",[jx.EXTENSIONS],!0),Object.keys(n).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){UP(e,n[e][0])}else UP(e,n[e])})))}function zB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=YL.reportApiInvoke(null,{name:QN.SET_AREA,options:e,tag:$N.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Un(Gx).call(Gx,e))throw new qL(PN.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const t=e,i=t.areaCode,r=t.excludedArea;if(!i)throw new qL(PN.INVALID_PARAMS,"area code is needed");let o=i;"string"==typeof i&&(o=[i]),n=r?qB(o,r):o}if(!t){if(FP.AREAS){const e=new qL(PN.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void gL.warning("setArea is prohibited because of config-distribute")}if(Un(n).call(n,jx.GLOBAL)&&VP("AREAS")===jx.EXTENSIONS){const e=new qL(PN.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void gL.warning("setArea is prohibited because of ap extensions")}}UP("AREAS",n,t);const r=WB(n);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){UP(e,r[e][0])}else UP(e,r[e])})),gL.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function XB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function QB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?XB(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):XB(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let $B=1;function ZB(e,t,i,n,r){$B+=1;const o={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:$B,requestId:$B,version:bP,cname:i.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return $D((async()=>{a=Date.now();const e=await BB(d,{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new qL(PN.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw gL.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new qL(PN.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw gL.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new qL(PN.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw gL.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(VP("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return VP("LIVE_STREAMING_ADDRESS")&&(r.addressList=VP("LIVE_STREAMING_ADDRESS")instanceof Array?VP("LIVE_STREAMING_ADDRESS"):[VP("LIVE_STREAMING_ADDRESS")]),QB(QB({},r),{},{responseTime:c})}),((n,r)=>(YL.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((n,r)=>(YL.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==PN.OPERATION_ABORTED&&n.code!==PN.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}function ej(e,t,i,n){let r=e.url,o=e.areaCode;const s=t.clientId,a=t.sid,c=Date.now();let d;const l=t.role,u=HI(oj(t,o,[AF.CHOOSE_SERVER]),2),h=u[0],p=u[1];let _=ED.networkState;return $D((async()=>{_&&ED.networkState===dD.OFFLINE&&ED.onlineWaiter&&await cp.race([ED.onlineWaiter,kD(n&&n.maxRetryTimeout||XD.maxRetryTimeout)]),_=ED.networkState;const e=await BB(r,{data:h,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),o=e.data,l=e.headers;d="1"===l.http3?1:-1,YL.reportResourceTiming(r,a,s),ij(o,r,t,c,[AF.CHOOSE_SERVER],d);const u=GF(o,AF.CHOOSE_SERVER);return nj(u),xF(u,r)}),(e=>(e&&YL.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:p,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[AF.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==PN.OPERATION_ABORTED&&(e.code===PN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(YL.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:p,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[AF.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:_}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),gL.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function tj(e,t,i,n){let r,o=e.url,s=e.areaCode,a=e.serviceIds;const c=Date.now(),d=t.role,l=HI(oj(t,s,a),2),u=l[0],h=l[1];let p;return $D((async()=>{p&&ED.networkState===dD.OFFLINE&&ED.onlineWaiter&&await cp.race([ED.onlineWaiter,kD(n&&n.maxRetryTimeout||XD.maxRetryTimeout)]),p=ED.networkState;const e=await BB(o,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),s=e.data,d=e.headers;r="1"===d.http3?1:-1,YL.reportResourceTiming(o,t.sid,t.clientId),ij(s,o,t,c,a,r);const l=GF(s,AF.CHOOSE_SERVER),h=GF(s,"proxy5"===t.cloudProxyServer?AF.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?AF.CLOUD_PROXY:AF.CLOUD_PROXY_FALLBACK),_=performance.getEntriesByName(o),E=_[_.length-1];let f;return E&&(f={name:E.name,protocol:"nextHopProtocol"in E?E.nextHopProtocol:"",dnscost:"domainLookupEnd"in E&&"domainLookupStart"in E&&"number"==typeof E.domainLookupEnd&&"number"==typeof E.domainLookupStart?E.domainLookupEnd-E.domainLookupStart:-1,tcpTlsCost:"connectEnd"in E&&"connectStart"in E&&"number"==typeof E.connectEnd&&"number"==typeof E.connectStart?E.connectEnd-E.connectStart:-1,reqCost:"requestStart"in E&&"number"==typeof E.requestStart&&"responseEnd"in E&&"number"==typeof E.responseEnd?E.responseEnd-E.requestStart:-1,handleCost:"leave_ts"in s&&"enter_ts"in s&&"number"==typeof s.leave_ts&&"number"==typeof s.enter_ts?s.leave_ts-s.enter_ts:-1}),nj(l),{gatewayInfo:xF(l,o),proxyInfo:h,url:o,resourceTimingInfo:f}}),(e=>{var i;return e.gatewayInfo&&YL.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:h,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null===(i=e.gatewayInfo)||void 0===i?void 0:i.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&YL.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!==PN.OPERATION_ABORTED&&(e.code===PN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(YL.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:p})}),gL.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const ij=(e,t,i,n,r,o)=>{const s=i.sid,a=i.clientId,c=i.cloudProxyServer,d=[],l=a=>{4096===a.flag?YL.joinChooseServer(s,{role:i.role,lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:a.error.message,csIp:a.error.data&&a.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:i.apRequestDetail}):1048576!==a.flag&&4194304!==a.flag&&4194310!==a.flag||YL.joinWebProxyAP(s,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:a.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)gL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new qL(PN.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:VP("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=lF(i),r={error:new qL(PN.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?gL.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw gL.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 qL(PN.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)))]})},nj=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new qL(PN.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});VP("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?JB(e.detail[23].toLowerCase()):JB());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){var o;const n=zg(o=i[t]).call(o),r=e.addresses[t];r&&i&&!r.fingerprint&&(e.addresses[t].fingerprint=n)}}if(VP("GATEWAY_ADDRESS")&&VP("GATEWAY_ADDRESS").length>0){gL.debug("assign gateway address to",VP("GATEWAY_ADDRESS"));const t=VP("GATEWAY_ADDRESS").map((t=>{var i,n,r,o;const s=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint: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}},rj=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=lF(t.buffer.code);throw new qL(PN.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw gL.debug("update ticket request received ap response without response body:",t),new qL(PN.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},oj=(e,t,i)=>{var n;const r=Math.floor(Math.random()*10**12),o="host"===e.role?"1":"audience"===e.role?"2":void 0,s={appid:e.appId,client_ts:Date.now(),opid:r,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:QB(QB(QB(QB(QB({6:e.stringUid},null!==(n=e.multiIP)&&void 0!==n&&n.gateway_ip?{5:JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]})}:{}),{},{11:t,12:VP("USE_NEW_TOKEN")?"1":void 0},o?{17:o}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),e.apRequestDetailExtend),key:e.token,service_ids:i,uid:e.uid||0}}]},a=new FormData;return a.append("request",JSON.stringify(s)),[a,r]},sj=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};function aj(e){return cp.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const cj=async e=>{let t=e.fragementLength,i=e.referenceList,n=e.asyncMapHandler,r=e.allFailedhandler,o=e.promisesCollector,s=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*a,t=e+a;return i.slice(e,t).map(n)})();o&&o.push(...e);try{c=await aj(e)}catch(e){if(d+=a,s++,!(d>=i.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c};async function dj(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],r=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128],a=await new cp(((a,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),a(!0)},error:e=>{clearTimeout(d),a(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,i,n,r,o,s];for(let t=0;t<c.length;t++){const i=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(i)}catch(e){return void a(!1)}}}(),d=setTimeout((()=>{a(!1)}),5e3)}));return a}async function lj(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=VP("WEBCS_DOMAIN").slice(0,VP("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:jB()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await cj({fragementLength:VP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(gL.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),ej(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await kD(1e3),null!==r)return r;const s=VP("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:jB()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await cj({fragementLength:VP("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(gL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),ej(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await aj([s(),a()]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await r}}async function uj(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await lj(e,t,i,r);if(VP("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const n=await _j(e,t,i,r),o=n.gatewayInfo,a=n.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:o};const c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||NP.tcpport,udpport:e.udpport||NP.udpport,username:e.username||NP.username,password:e.password||NP.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:o.uid,i="glb:".concat(t.toString()),n=await qN(i),r=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||NP.tcpport,udpport:e.udpport||NP.udpport,username:i,password:n,forceturn:!1,security:!0})));c.push(...r)}return e.turnServer={mode:"manual",servers:c},{gatewayInfo:o}}return await lj(e,t,i,r)}const a=await _j(e,t,i,r),c=a.proxyInfo,d=a.gatewayInfo,l={gatewayInfo:d},u=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:NP.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:NP.udpport,username:e.username||NP.username,password:e.password||NP.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var h;const t=null!==(h=e.uid)&&void 0!==h?h:d.uid,i="glb:".concat(t.toString()),n=await qN(i),r=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||NP.tcpport,udpport:"proxy4"===o?void 0:e.udpport||NP.udpport,username:i,password:n,forceturn:"proxy4"!==o,security:"proxy5"===o})));u.push(...r)}return e.turnServer={mode:"manual",servers:u},gL.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),l}async function hj(e,t,i,n,r){const o=VP("ACCOUNT_REGISTER").slice(0,VP("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):o.map((e=>"https://".concat(e,"/api/v1")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const o=await async function(e,t,i,n,r){const o=Date.now(),s={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await $D((()=>BB(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw gL.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),YL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:PN.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new qL(PN.INVALID_UINT_UID_FROM_STRING_UID);return YL.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=lF(i.code);return r.retry&&(a=e[(n+1)%e.length]),YL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:r.desc,extend:s}),r.retry}),((t,i)=>t.code!==PN.OPERATION_ABORTED&&(YL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(i+1)%e.length],!0)),r);if(0!==c.code){const e=lF(c.code);throw new qL(PN.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),o.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function pj(e,t,i){const n=VP("CDS_AP").slice(0,VP("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))),r=n.map((n=>function(e,t,i,n){const r=Jw(),o={flag:64,cipher_method:0,features:QB(QB(QB(QB(QB({install_id:AP(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:bP,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:VB.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 $D((()=>BB(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==PN.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,s=null,a={};try{o=await aj(r)}catch(e){if(e.code===PN.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(YL.reportApiInvoke(e.sid,{name:QN.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{var i;const r=zg(i=e.slice(4)).call(i),o=JSON.parse(t[e]),s=o[1];n[r]={tag:o[0]||"",value:s}})),n}(o)}catch(e){}return a}async function _j(e,t,i,n){const r=VP("PROXY_SERVER_TYPE3"),o=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0&&r[1]||r[0]),"https://".concat(n,"/ap/?url=").concat(e)};let s=null;const a=[],c=async()=>{const r=VP("WEBCS_DOMAIN").slice(0,VP("AJAX_REQUEST_CONCURRENT")).map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jB(),serviceIds:[AF.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?AF.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?AF.CLOUD_PROXY:AF.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await cj({fragementLength:VP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(gL.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),tj(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c},d=async()=>{if(await kD(1e3),null!==s)return s;const r=VP("WEBCS_DOMAIN_BACKUP_LIST").map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jB(),serviceIds:[AF.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?AF.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?AF.CLOUD_PROXY:AF.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await cj({fragementLength:VP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(gL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),tj(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,u,h;try{var p=await aj([c(),d()]);l=p.gatewayInfo,u=p.proxyInfo,h=p.url}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!u)throw new qL(PN.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];Un(r).call(r,t)&&(e.proxyServer=t,gL.setProxyServer(t),YL.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await WF(u,l.uid)},s}async function Ej(e,t,i){let n=null;const r=[],o=async o=>{const s=VP(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 kD(1e3),null!==n)?n:await cj({fragementLength:VP("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(gL.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const r=HI(sj(t,[AF.CHOOSE_SERVER]),1)[0];let o=ED.networkState;return $D((async()=>{o&&ED.networkState===dD.OFFLINE&&ED.onlineWaiter&&await cp.race([ED.onlineWaiter,kD(n&&n.maxRetryTimeout||XD.maxRetryTimeout)]),o=ED.networkState;const t=await BB(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return rj(t,e)}),(()=>!1),(e=>e.code!==PN.OPERATION_ABORTED&&(e.code===PN.UPDATE_TICKET_FAILED?e.data.retry:(gL.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return n=await aj([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}const fj=()=>{},mj={markJoined:fj,releaseIfNotJoined:fj},Sj=fj,gj=fj,Tj=fj;function Rj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Rj(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Rj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Cj extends JN{get isSuccess(){return!!this.configs}constructor(e,t){super(),Zb(this,"configs",void 0),Zb(this,"store",void 0),Zb(this,"joinInfo",void 0),Zb(this,"cancelToken",void 0),Zb(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),Zb(this,"interval",void 0),Zb(this,"mutex",void 0),Zb(this,"mutableParamsRead",!1),Zb(this,"configCache",{}),Zb(this,"limit_bitrate",void 0),this.mutex=new JD("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),VP("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),VP("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;YL.reportApiInvoke(null,{options:void 0,name:QN.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:$N.TRACER}).onSuccess(JSON.stringify(FP))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void gL.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await pj(this.joinInfo,this.cancelToken,this.retryConfig),gL.debug("[config-distribute] get config distribute",JSON.stringify(e));const i=function(e){var t;const i=t_(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<i.length;t++)for(let n=i.length-1;n>t;n--){const t=i[n],r=e[t].value;if("number"==typeof r.__priority){const o=r.__priority,s=i[n-1],a=e[s].value;if("number"==typeof a.__priority){if(!(o>a.__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e}}else{const e=t;i[n]=i[n-1],i[n-1]=e}}}const n=Date.now(),r={};return i.forEach((t=>{const i=e[t].value.__expires;i&&i<=n||(r[t]=e[t])})),r}(e);this.cacheGlobalParameterConfig(i),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=i}catch(e){const t=new qL(PN.NETWORK_RESPONSE_ERROR,e);gL.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){Yx(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(Kx.UPDATE_BITRATE_LIMIT,e):this.emit(Kx.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&vj({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},i=Object.keys(e),n=[];i.forEach((i=>{const r=e[i].value;t[i]=r;const o=r.__id;if(o&&this.configCache[i]&&this.configCache[i].__id===o)return;const s=r.__type,a=e[i].value,c=e[i].tag;let d=0;s?s===xP.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(kP,e)||!ZV()&&Object.prototype.hasOwnProperty.call(DP,e)?(d=1,!0):void 0)),n.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(r)})})),n.forEach((e=>{let t=e.tag,i=e.feature,n=e.params,r=e.isApplied;this.store.sessionId&&YL.abTest(this.store.sessionId,{intSucc:1,isApplied:r,tag:t,feature:i,params:n,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){gL.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i].value,r=n.__expires,o=n.__type;Object.keys(n).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=vj(vj({value:n[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var i;const n=null===(i=t.LIMIT_BITRATE)||void 0===i?void 0:i.value;if(delete t.LIMIT_BITRATE,n&&Yx(n)&&this.handleBitrateLimit(n),this.limit_bitrate=n,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{const n=e[i],r=n.value,o=n.type,s=n.expires;s&&s<=t||((o===xP.REALTIME||Object.prototype.hasOwnProperty.call(kP,i))&&(FP[i]=r,MP[i]=r,gL.debug("Update realtime parameters from config distribute",i,r)),o||ZV()||!Object.prototype.hasOwnProperty.call(DP,i)||(FP[i]=r,MP[i]=r,gL.debug("Update gateway parameters from config distribute",i,r)))}))}catch(t){gL.error("Error update config immediately: ".concat(e),t.message)}}(t),function(e){try{var t;if(!VP("ENABLE_CONFIG_RESTORE"))return!1;const i=ML(e),n=window.localStorage.getItem(NL);if(!n)return!1;const r=JSON.parse(n),o=VP("BLOCKED_CONFIG_MAX_TIME");return Date.now()-r.timestamp>o?(WL(),!1):Un(t=r.configHashes).call(t,i)}catch(e){return gL.debug("[error] ".concat(OL," error checking blocked config:"),e),!1}}(t))return gL.debug("[warning] [config-distribute] blocked config detected and skipped"),void YL.reportAlarm(this.store.sessionId||null,{type:CL.CONFIG_DISTRIBUTE,status:vL.RECOVER,message:"Blocked config detected and skipped"});!function(e){try{const t=ML(e),i=UL();if(i.currentConfigHash&&i.currentConfigHash===t)return VL({currentConfigHash:t,configVerified:!0}),BL(),WL(),void gL.debug("".concat(OL," config verified as safe, skip further checks"));VL({currentConfigHash:t,configVerified:!1}),BL(),WL()}catch(e){gL.debug("[error] ".concat(OL," error on config applied:"),e)}}(t),Tj();const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),gL.debug("Caching global parameters ".concat(r))}catch(e){gL.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(MP,i)){const n=e[i],r=n.value,o=n.expires;if(o&&o<=t)return;HD(MP[i],r)||(FP[i]=r,MP[i]=r,this.emit(Kx.UPDATE_CLIENT_ROLE_OPTIONS,r),gL.debug("Updating client role options: ".concat(JSON.stringify(r))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(MP,i)){var n;const r=e[i],o=r.value,s=r.expires;if(s&&s<=t)return;"number"==typeof o&&Un(n=[0,1,4,5,6,7,8,9]).call(n,o)&&(FP[i]={value:o},MP[i]=o,this.emit(Kx.UPDATE_REMOTE_VIDEO_STREAM_TYPE,o),gL.debug("Updating client remote stream type: ".concat(JSON.stringify(o))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(MP,i)){const n=e[i],r=n.value,o=n.expires;if(o&&o<=t)return;HD(MP[i],r)||(FP[i]=r,MP[i]=r,this.emit(Kx.FALLBACK_TO_HLS,r),gL.debug("Updating enable force hls: ".concat(JSON.stringify(r))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(MP,i)){const n=e[i],r=n.value,o=n.expires;if(o&&o<=t)return;HD(MP[i],r)||(FP[i]=r,MP[i]=r,this.emit(Kx.UPDATE_VOS_CONFIGURE,r),gL.debug("Updating vos configure: ".concat(JSON.stringify(r))))}}}))}catch(e){gL.error("Error handling global parameter config:",e.message)}}}class Ij extends JN{constructor(){super(...arguments),Zb(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){var i;const n=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",n,this.checkVideoDecode(t),(null!==(i=t.decodeFrameRate)&&void 0!==i?i:0)>0)}record(e,t,i,n){if(VP("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0,recoverResult:[]});const r=this.resultStorage.get(e);if(!r)return;r.result.push(i),void 0!==n&&(r.recoverResult||(r.recoverResult=[]),r.recoverResult.push(n));const o="VIDEO_ENCODE_FAILED"===e?VP("ENCODE_EXCEPTION_TIMES"):5;if(r.result.length>=o){var s,a,c;const i=Un(s=r.result).call(s,!0),n=null!==(a=r.recoverResult)&&void 0!==a&&a.length?Un(c=r.recoverResult).call(c,!0):i;r.isPrevNormal&&!i&&this.emit("exception",yj[e],e,t),!r.isPrevNormal&&n&&this.emit("exception",yj[e]+2e3,e+"_RECOVER",t),r.isPrevNormal=i,r.result=[],r.recoverResult&&(r.recoverResult=[])}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof kU&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=FF(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){var t;return!(!e.codecType||Un(t=VP("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 kU&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const yj={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 Aj=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function bj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Oj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?bj(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):bj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class wj{constructor(e){Zb(this,"store",void 0),Zb(this,"onStatsException",void 0),Zb(this,"onUploadPublishDuration",void 0),Zb(this,"onStatsChanged",void 0),Zb(this,"onVideoCodecChanged",void 0),Zb(this,"localStats",new Map),Zb(this,"remoteStats",new Map),Zb(this,"updateStatsInterval",void 0),Zb(this,"trafficStats",void 0),Zb(this,"trafficStatsPeerList",[]),Zb(this,"uplinkStats",void 0),Zb(this,"exceptionMonitor",void 0),Zb(this,"p2pChannel",void 0),Zb(this,"scalabilityMode",mP.L1T1),Zb(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new Ij,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(Zx.LocalAudioTrack)||Oj({},Ok)}getLocalVideoTrackStats(){return this.localStats.get(Zx.LocalVideoTrack)||Oj({},wk)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=HI(e,2),r=n[0],o=n[1].audioStats;o&&(i[r]=t(r,o))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=HI(e,2),n=i[0],r=i[1].networkStats;r&&(t[n]=r)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=jF(this.trafficStats.B_unq),t=jF(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=HI(e,2),r=n[0],o=n[1].videoStats;o&&(i[r]=t(r,o))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(Zx.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(Zx.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(Zx.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let t=e.audioStats,r=e.videoStats;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?Aj.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?Aj.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&gL.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let i=HI(t,2),n=i[0],r=i[1];switch(n){case Zx.LocalVideoTrack:case Zx.LocalVideoLowTrack:{const t=r,i=Oj({},wk),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 r=e.getLocalVideoSize(),s=e.getEncoderConfig(Zx.LocalVideoTrack);var o;if("H264"===n.codec||"H265"===n.codec||"VP8"===n.codec||"VP9"===n.codec||"AV1X"===n.codec||"AV1"===n.codec)if(i.codecType=n.codec,(null==t?void 0:t.codecType)!==n.codec)null===(o=this.onVideoCodecChanged)||void 0===o||o.call(this,n.codec.toLocaleLowerCase());i.sendBytes=n.bytes,i.sendBitrate=t?8*Math.max(0,i.sendBytes-t.sendBytes):0,n.inputFrame?(i.captureFrameRate=n.inputFrame.frameRate,i.captureResolutionHeight=n.inputFrame.height,i.captureResolutionWidth=n.inputFrame.width):r&&(i.captureResolutionWidth=r.width,i.captureResolutionHeight=r.height),n.sentFrame?(i.sendFrameRate=n.sentFrame.frameRate,i.sendResolutionHeight=n.sentFrame.height,i.sendResolutionWidth=n.sentFrame.width):r&&(i.sendResolutionWidth=r.width,i.sendResolutionHeight=r.height),n.avgEncodeMs&&(i.encodeDelay=n.avgEncodeMs),s&&s.bitrateMax?i.targetSendBitrate=1e3*s.bitrateMax:n.targetBitrate&&(i.targetSendBitrate=n.targetBitrate),i.sendPackets=n.packets,i.sendPacketsLost=n.packetsLost,i.sendJitterMs=n.jitterMs,i.sendRttMs=n.rttMs,i.totalDuration=t?t.totalDuration+1:1,i.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(n)&&(i.totalFreezeTime+=1),n.scalabilityMode&&this.scalabilityMode!==n.scalabilityMode&&(gL.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(n.scalabilityMode)),this.scalabilityMode=n.scalabilityMode)}this.trafficStats&&(i.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var s;if(this.localStats.set(n,i),(null==t?void 0:t.sendResolutionWidth)!==i.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==i.sendResolutionHeight)null===(s=this.onStatsChanged)||void 0===s||s.call(this,"resolution",{width:i.sendResolutionWidth,height:i.sendResolutionHeight});i&&c&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,c.track,i);break}case Zx.LocalAudioTrack:{const t=r,i=Oj({},Ok),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||(i.codecType=n.codec),n.inputLevel)i.sendVolumeLevel=Math.round(32767*n.inputLevel);else{const t=e.getLocalAudioVolume();t&&(i.sendVolumeLevel=Math.round(32767*t))}i.sendBytes=n.bytes,i.sendPackets=n.packets,i.sendPacketsLost=n.packetsLost,i.sendJitterMs=n.jitterMs,i.sendRttMs=n.rttMs,i.sendBitrate=t?8*Math.max(0,i.sendBytes-t.sendBytes):0}}this.trafficStats&&(i.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(Zx.LocalAudioTrack,i),i&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,i);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let r=HI(t,2),o=r[0],s=r[1],a=s.videoStats;const c=s.audioStats,d=a,l=s.videoPcStats,u=Oj({},Nk),h=Oj({},Pk),p=Oj({},Dk),_=e.getRemoteMedia(o),E=_.audioTrack,f=_.videoTrack,m=_.audioSSRC,S=_.videoSSRC;let g;g=this.store.useP2P?e.getStats(!0):e.getStats();const T=null===(i=g)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===m)),R=null===(n=g)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===S)),v=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===o));if(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):E&&(u.receiveLevel=Math.round(32767*E.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.receivePacketsDiscarded=T.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=T.jitterBufferMs,u.totalDuration>10&&wj.isRemoteAudioFreeze(E)&&(u.totalFreezeTime+=1)),R){"H264"!==R.codec&&"H265"!==R.codec&&"VP8"!==R.codec&&"VP9"!==R.codec&&"AV1X"!==R.codec&&"AV1"!==R.codec||(h.codecType=R.codec),h.receiveBytes=R.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,h.renderFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,R.outputFrame&&(h.renderFrameRate=R.outputFrame.frameRate),R.receivedFrame?(h.receiveFrameRate=R.receivedFrame.frameRate,h.receiveResolutionHeight=R.receivedFrame.height,h.receiveResolutionWidth=R.receivedFrame.width):f&&(h.receiveResolutionHeight=f._videoHeight||0,h.receiveResolutionWidth=f._videoWidth||0),void 0!==R.framesRateFirefox&&(h.receiveFrameRate=Math.round(R.framesRateFirefox)),h.receivePackets=R.packets,h.receivePacketsLost=R.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.receiveDelay=R.jitterBufferMs||0;const t=!!S&&e.getRemoteVideoIsReady(S),i=d?d.totalFreezeTime:0,n=d?d.totalDuration:0;var C;if(h.totalDuration=d?d.totalDuration+1:1,1===VP("REMOTE_VIDEO_FREEZE_TIME_VERSION"))f&&t&&f._player&&(h.totalFreezeTime=f._player.totalFreezeTime/1e3);else h.totalFreezeTime=null!==(C=R.totalFreezesDuration)&&void 0!==C?C:i||0,void 0===R.totalFreezesDuration&&f&&t&&wj.isRemoteVideoFreeze(f,R,l)&&(h.totalFreezeTime+=1);h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-i)/(h.totalDuration-n),1))}v&&(u.end2EndDelay=v.B_ad,h.end2EndDelay=v.B_vd,u.transportDelay=v.B_ed,h.transportDelay=v.B_ed,u.currentPacketLossRate=v.B_ealr4/100,h.currentPacketLossRate=v.B_evlr4/100,p.uplinkNetworkQuality=v.B_punq?v.B_punq:0,p.downlinkNetworkQuality=v.B_pdnq?v.B_pdnq:0),this.remoteStats.set(o,{audioStats:u,videoStats:h,videoPcStats:R,networkStats:p}),E&&this.exceptionMonitor.setRemoteAudioStats(E,u),f&&this.exceptionMonitor.setRemoteVideoStats(f,h)}))}}class Nj{constructor(){Zb(this,"destChannelMediaInfos",new Map),Zb(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){Lx(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){Lx(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){wx(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function Dj(e){if(!(e instanceof Nj)){return new qL(PN.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new qL(PN.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new qL(PN.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class Pj{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){Zb(this,"uid",void 0),Zb(this,"_uintid",void 0),Zb(this,"_trust_in_room_",!0),Zb(this,"_trust_audio_enabled_state_",!0),Zb(this,"_trust_video_enabled_state_",!0),Zb(this,"_trust_audio_mute_state_",!0),Zb(this,"_trust_video_mute_state_",!0),Zb(this,"_audio_muted_",!1),Zb(this,"_video_muted_",!1),Zb(this,"_audio_enabled_",!0),Zb(this,"_video_enabled_",!0),Zb(this,"_audio_added_",!1),Zb(this,"_video_added_",!1),Zb(this,"_is_pre_created",!1),Zb(this,"_video_pre_subscribed",!1),Zb(this,"_audio_pre_subscribed",!1),Zb(this,"_trust_video_stream_added_state_",!0),Zb(this,"_trust_audio_stream_added_state_",!0),Zb(this,"_audioTrack",void 0),Zb(this,"_videoTrack",void 0),Zb(this,"_dataChannels",[]),Zb(this,"_audioSSRC",void 0),Zb(this,"_videoSSRC",void 0),Zb(this,"_audioOrtc",void 0),Zb(this,"_videoOrtc",void 0),Zb(this,"_cname",void 0),Zb(this,"_rtxSsrcId",void 0),Zb(this,"_videoMid",void 0),Zb(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function Lj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function kj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Lj(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Lj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const Mj=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"),Uj="9",Vj=2e4,xj=4e4;function Fj(e){return!!e&&Boolean("number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1||"number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1)}function Bj(e,t,i,n){if("number"!=typeof n)return Array.from({length:i+1},((i,n)=>e/Math.pow(t,n)));const r=Math.max(e,n),o=r/e;if(o<=1)return Array.from({length:i+1},(()=>e));const s=1/t,a=Math.min(i,Math.max(1,Math.ceil(Math.log(o)/Math.log(s)))),c=Math.pow(o,1/a);return Array.from({length:i+1},((t,i)=>{if(0===i)return e;const n=Math.min(i,a);return Math.min(e*Math.pow(c,n),r)}))}function jj(e,t,i,n){if("number"!=typeof n)return i;const r=Math.max(e,n)/e;if(r<=1)return 0;const o=1/t;return Math.min(i,Math.max(1,Math.ceil(Math.log(r)/Math.log(o))))}function Gj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Wj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Gj(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Gj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var Hj=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(Hj||{});const Kj=new Map;function Yj(e,t,i,n){let r=e.scale;if(0===r&&n===Hj.UP||r>=t.length-1&&n===Hj.DOWN)return e;let o=Wj(Wj({},e),{},{scale:n===Hj.DOWN?++r:--r});switch(i){case"maintain-framerate":o=Wj(Wj({},o),t[r].motion);break;case"maintain-resolution":o=Wj(Wj({},o),t[r].detail);break;case"balanced":o=Wj(Wj({},o),t[r].balanced)}return o}function qj(e,t,i){if(t){const n={overUse:0,underUse:0,adaptationList:Jj(t,i)};Kj.set(e,n)}else Kj.delete(e)}function Jj(e,t){const i=Wj({},e),n=i.bitrateMax,r=i.frameRate,o=i.scaleResolutionDownBy,s=i.bitrateMin,a=function(e){const t=[];if("number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1&&e.height>0&&t.push(e.height/e.minDownscaleHeight),"number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1&&e.width>0&&t.push(e.width/e.minDownscaleWidth),t.length)return Math.max(e.scaleResolutionDownBy,Math.min(...t))}(i),c=PP.MIN_FRAME_RATE,d=PP.MAX_THRESHOLD_FRAMERATE,l=PP.MAX_SCALE,u=PP.BITRATE_MIN_THRESHOLD,h=PP.BITRATE_MAX_THRESHOLD,p=PP.BWE_SCALE_UP_THRESHOLD,_=PP.BWE_SCALE_DOWN_THRESHOLD,E=PP.PERF_SCALE_DOWN_THRESHOLD,f=PP.PERF_SCALE_UP_THRESHOLD,m=PP.BALANCE_BITRATE_FACTOR,S=PP.BALANCE_FRAMERATE_FACTOR,g=PP.BALANCE_RESOLUTION_FACTOR,T=PP.MOTION_RESOLUTION_FACTOR,R=PP.MOTION_BITRATE_FACTOR,v=PP.DETAIL_FRAMERATE_FACTOR,C=PP.DETAIL_BITRATE_FACTOR,I=Math.min(i.frameRate,d);let y=l;"maintain-framerate"===t?y=jj(o,T,l,a):"balanced"===t&&(y=jj(o,g,l,a));const A=Bj(o,g,y,a),b=Bj(o,T,y,a),O=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(_,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(E,1)*I),fps_up:r},balanced:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:n,bitrateMin:s},motion:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:n,bitrateMin:s},detail:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:n,bitrateMin:s}}];for(let e=1;e<=y;e++){const t={bwe_up:Math.round(Math.pow(p,e)*n),bwe_down:Math.round(Math.pow(_,e+1)*n),fps_up:Math.round(Math.pow(f,e)*I),fps_down:Math.round(Math.pow(E,e+1)*I)},i={scaleResolutionDownBy:A[e],frameRate:Math.max(Math.round(Math.pow(S,e)*r),c),bitrateMax:Math.max(Math.round(Math.pow(m,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(m,e)*s),u)},o={scaleResolutionDownBy:b[e],frameRate:r,bitrateMax:Math.max(Math.round(Math.pow(R,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(R,e)*s),u)},a={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(v,e)*r),c),bitrateMax:Math.max(Math.round(Math.pow(C,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(C,e)*s),u)};O.push({scale:e,threshold:t,balanced:i,motion:o,detail:a})}return O}function zj(e,t,i,n,r,o){const s=Kj.get(e)||{overUse:0,underUse:0,adaptationList:Jj(r,o)},a=s.adaptationList;Kj.set(e,s);const c=PP.OVERUSE_TIMES_THRESHOLD,d=PP.UNDERUSE_TIMES_THRESHOLD,l=n.scale;let u,h;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let r=i[t].threshold.fps_down;return VP("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[0].threshold.fps_down),e<r}(t,l,a,o)&&(s.overUse++,h=fP.CPU,s.overUse>c)||"number"==typeof i&&i>0&&function(e,t,i){return!(t>=i.length)&&e<i[t].threshold.bwe_down}(i,l,a)&&(s.overUse++,h=fP.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=Yj(n,a,o,Hj.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let r=i[t].threshold.fps_up;return VP("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,i){if(0===t)return;return e>i[t].threshold.bwe_up}(i,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=Yj(n,a,o,Hj.UP),0===u.scale&&(h=fP.NONE))),[u,h])}function Xj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Qj(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Xj(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Xj(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const $j=new Map;function Zj(e,t){const i=$j.get(e);if(i){const t=i.timer;window.clearTimeout(t),$j.delete(e)}t.qualityLimitationReason=fP.NONE,qj(e)}const eG=["balanced","maintain-framerate","maintain-resolution"];function tG(e){switch(e){case"motion":return"maintain-framerate";case"detail":return"maintain-resolution";case"balanced":return"balanced";default:return}}function iG(e){var t;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=tG(e._optimizationMode);if(n)return n;const r=VP("CUSTOM_ADAPTATION_DEFAULT_MODE");return Un(t=e._hints).call(t,gk.CUSTOM_TRACK)?function(e){return"string"==typeof e&&Un(eG).call(eG,e)}(r)?r:i?"maintain-framerate":"":"maintain-framerate"}function nG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function rG(e,t,i){var n;const r=e.getParameters(),o=null===(n=r.encodings)||void 0===n?void 0:n[0];return o&&Object.assign(o,i),Object.assign(r,t),r}async function oG(e,t,i){try{return await e.setParameters(rG(e,t,i)),{classification:"transient"}}catch(n){const r=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?nG(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):nG(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},i);delete r.scaleResolutionDownBy;try{return await e.setParameters(rG(e,t,r)),{classification:"unsupported",retryWithScaleError:n}}catch(e){return{classification:"unknown",retryWithScaleError:n,retryWithoutScaleError:e}}}}function sG(e){const t=zL();if(e.some((e=>e._bypassWebAudio)))throw new LN(PN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new LN(PN.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function aG(e,t){sG(e);const i=t||new kU;return e.forEach((e=>i.addAudioTrack(e))),i}const cG=!zL().supportUnifiedPlan||VP("CHROME_FORCE_PLAN_B")&&IN();function dG(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return i={spec:t,store:e},bB("DataChannelConnection").create(i);var i;const n=cG?function(e){return bB("PlanBConnection").create(e)}({spec:t,store:e}):new EG(t,e);return n}function lG(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function uG(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(iD(e.turnServer.servers))return!1;if(VP("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var hG;function pG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _G(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pG(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pG(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let EG=(hG=class e extends Jx{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get remoteIceUfrag(){var e;return null===(e=this.remoteSDP)||void 0===e?void 0:e.remoteIceUfrag}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 Un(t=Object.keys(jP)).call(t,e)})))]}constructor(t,i){if(super(t,i),Zb(this,"id",MD(5,"connection-")),Zb(this,"store",void 0),Zb(this,"peerConnection",void 0),Zb(this,"forceTurn",!1),Zb(this,"remoteSDP",void 0),Zb(this,"initialOffer",void 0),Zb(this,"transportEventReceiver",void 0),Zb(this,"statsFilter",void 0),Zb(this,"extension",{useXR:VP("USE_XR")}),Zb(this,"localCapabilities",void 0),Zb(this,"remoteCodecs",void 0),Zb(this,"localCandidateCount",0),Zb(this,"allCandidatesReceived",!1),Zb(this,"isPreallocation",!1),Zb(this,"isPreRender",!1),Zb(this,"preMediaMap",new Map),Zb(this,"dataStreamChannelMap",new Map),Zb(this,"establishPromise",void 0),Zb(this,"recoveredDataChannelIds",[]),Zb(this,"currentDataChannelId",1),Zb(this,"supportAV1RtpSpec",!1),Zb(this,"_nvMedia",void 0),Zb(this,"mutex",void 0),Zb(this,"qualityLimitationReason",fP.NONE),Zb(this,"unsupportedResolutionFloorTrackIds",new Set),Zb(this,"isFirstConnected",!1),this.store=i,this.forceTurn=uG(t),this.mutex=new JD("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=IP(this.peerConnection,VP("STATS_UPDATE_INTERVAL"),void 0,rN()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.store.aiClientMode){const e=this.peerConnection.createDataChannel("agora-media",{id:this.store.mediaDcId,ordered:!1,negotiated:!0});e.binaryType="arraybuffer";try{this._nvMedia=(n=e,bB("AiAudioModeExtension").create(n)),this._nvMedia.setAudioMetadataHandler((e=>{var t;null===(t=this.onAudioMetadata)||void 0===t||t.call(this,e)})),this._nvMedia.setAudioPtsHandler((e=>{var t;null===(t=this.onAudioPts)||void 0===t||t.call(this,e)})),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode initialized"))}catch(e){this._nvMedia=void 0,gL.warning("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode not available"),e)}}var n;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 gL.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else gL.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const i=await this.peerConnection.createOffer();if(!i.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=nB(i.sdp),r=await hB({filterRTX:!VP("USE_PUB_RTX")&&!VP("USE_SUB_RTX"),filterVideoFec:VP("FILTER_VIDEO_FEC"),filterAudioFec:VP("FILTER_AUDIO_FEC"),filterVideoCodec:VP("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:VP("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:VP("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=_B(r),this.initialOffer=i,VP("ENABLE_SVC")&&"av1"==this.store.codec){const t=await async function(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:mP.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=JP(t.sdp).mediaDescriptions[0];if(!i)return;const n=i.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),n}catch(e){return}}();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=r.send)||void 0===e||e.videoExtensions.push(t)}let o;return i.sdp&&RB(i.sdp)&&(o=ID(r),(t=o).send&&(QF(zx.VIDEO,t.send.videoExtensions),QF(zx.AUDIO,t.send.audioExtensions)),t.recv&&(QF(zx.VIDEO,t.recv.videoExtensions),QF(zx.AUDIO,t.recv.audioExtensions)),t.sendrecv&&(QF(zx.VIDEO,t.sendrecv.videoExtensions),QF(zx.AUDIO,t.sendrecv.audioExtensions))),_G(_G({},n),{},{rtpCapabilities:o||r,offerSDP:i.sdp})}catch(e){throw new LN(PN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}var t}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.initialOffer.sdp&&RB(this.initialOffer.sdp)&&(i=e.rtpCapabilities,n=this.localCapabilities,i.send&&(XF(zx.VIDEO,i.send.videoExtensions,n.send.videoExtensions),XF(zx.AUDIO,i.send.audioExtensions,n.send.audioExtensions)),i.recv&&(XF(zx.VIDEO,i.recv.videoExtensions,n.recv.videoExtensions),XF(zx.AUDIO,i.recv.audioExtensions,n.recv.audioExtensions))),this.remoteSDP=new class{get localCapabilities(){return ID(this._localCapabilities)}get rtpCapabilities(){return ID(this._rtpCapabilities)}get candidates(){return ID(this._candidates)}get iceParameters(){return ID(this._iceParameters)}get remoteIceUfrag(){var e;return null===(e=this._iceParameters)||void 0===e?void 0:e.iceUfrag}get dtlsParameters(){return ID(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];Zb(this,"sessionDesc",void 0),Zb(this,"_localCapabilities",void 0),Zb(this,"_rtpCapabilities",void 0),Zb(this,"_candidates",void 0),Zb(this,"_originCandidates",void 0),Zb(this,"_iceParameters",void 0),Zb(this,"_isUseExtmapAllowMixed",void 0),Zb(this,"_isUseLocalCodecs",void 0),Zb(this,"_isUseDataChannel",void 0),Zb(this,"_dtlsParameters",void 0),Zb(this,"setup",void 0),Zb(this,"currentMidIndex",void 0),Zb(this,"cname",void 0),Zb(this,"useLocalCodecsMids",[]),Zb(this,"preloadSsrcs",[]),Zb(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=i,this._isUseDataChannel=n;const r=e=ID(e),o=r.iceParameters,s=r.dtlsParameters,a=r.candidates,c=r.rtpCapabilities,d=r.setup,l=r.localCapabilities,u=r.cname;this._rtpCapabilities=c,this._candidates=a,this._originCandidates=ID(a),this._iceParameters=o,this._dtlsParameters=s,this._localCapabilities=l,this.setup=d,this.cname=u;var h=HI(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=h[0],this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>{var t;return Un(t=this.preloadSsrcs).call(t,e)}))}preloadRemoteMedia(e){let t=0;const i=[],n=[];for(;e>0;){const r=[kj({ssrcId:xj+t},VP("USE_SUB_RTX")?{rtx:xj+t+1}:{})],o="".concat(xj+t,"_").concat(Vj+t),s=aB(r,this.cname,VP("SYNC_GROUP")?o:void 0),a=s.ssrcs,c=s.ssrcGroups,d=this.preCreateOrRecycleSendMedia("video",a,c,void 0),l=[{ssrcId:Vj+t}],u="".concat(xj+t,"_").concat(Vj+t),h=aB(l,this.cname,VP("SYNC_GROUP")?u:void 0),p=h.ssrcs,_=h.ssrcGroups,E=this.preCreateOrRecycleSendMedia("audio",p,_,void 0);e--,t+=2,i.push(d,E),n.push(a[0].ssrcId,p[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=n,{mids:i,preSSRCs:n,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,n){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;gL.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===zx.VIDEO?o.videoCodecs:o.audioCodecs,a=e===zx.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Uj,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,n),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return zP(this.sessionDesc)}send(e,t,i,n){const r=aB(t,this.cname,VP("SYNC_GROUP")?i:void 0),o=r.ssrcs,s=r.ssrcGroups,a=this.findPreloadMediaDesc(o);if(a){if(rN()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,n),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o);let i;return-1===t||1===t&&(tN()||function(){const e=Jw();return!(e.name!==Hw.CHROME||!e.osVersion)&&Number(e.version)<=90}()||sN(143)||dN(143)||Zw()||VP("RESERVE_MID_1_MLINE")||VP("ENABLE_ENCODED_TRANSFORM")&&eN())||0===t&&!function(e){const t=Jw();return!(t.name!==Hw.FIREFOX||!t.osVersion)&&Number(t.version)===e}(138)&&VP("USE_SUB_RTX")||fN()?(i=this.createOrRecycleSendMedia(e,o,s,"sendonly",n),this.updateBundleMids()):(i=ID(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),rN()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const e=this.createOrRecycleDataChannel(),t=e.mediaDesc,i=e.needExchangeSDP;return this.updateBundleMids(),{mid:t.attributes.mid,needExchangeSDP:i}}batchSend(e){const t=e.map((e=>{let t=e.kind,i=e.ssrcMsg,n=e.mslabel;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let t=e.mid;e.needExchangeSDP&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||rN()||fN()?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=>Un(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=>Un(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||JP((i=this._isUseExtmapAllowMixed,this._isUseDataChannel?Mj(i):"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(i?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));var i;this._rtpCapabilities=e;let n=!1;const r=this.rtpCapabilities.send,o=this.localCapabilities.send,s=this.localCapabilities.recv,a=s.videoCodecs,c=s.audioCodecs,d=s.videoExtensions,l=s.audioExtensions;for(const e of t.mediaDescriptions){var u;if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!Un(u=this.useLocalCodecsMids).call(u,e.attributes.mid)){if(n=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var h;e.media.fmts=a.map((e=>e.payloadType.toString(10))),e.attributes.payloads=a,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||Un(h=this.useLocalCodecsMids).call(h,t)||this.useLocalCodecsMids.push(t)}else if(0===r.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Un(i=t.encodingName.toLowerCase()).call(i,"vp8")}));0===t.length&&t.push(o.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.videoCodecs,e.attributes.extmaps=r.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var p;e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||Un(p=this.useLocalCodecsMids).call(p,t)||this.useLocalCodecsMids.push(t)}else if(0===r.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Un(i=t.encodingName.toLowerCase()).call(i,"opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.audioCodecs,e.attributes.extmaps=r.audioExtensions,EB(e)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,n]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(kj(kj({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case Xx.TCP_RELAY:this._candidates=i;break;case Xx.UDP_TCP_RELAY:case Xx.RELAY:this._candidates=[...t,...i];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=ID(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((i=>{i.attributes.iceUfrag===e.iceUfrag&&i.attributes.icePwd===e.icePwd||(t=!0),i.attributes.iceUfrag=e.iceUfrag,i.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(rN()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:Uj,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=fB(s,a,this.localCapabilities.send,s===zx.VIDEO?n:r),d=s===zx.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:Uj,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),i=new Set(e.map((e=>e.fingerprint)));let n=!1;t.size!==i.size&&(n=!0);for(const e of t)i.has(e)||(n=!0);return n}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Un(t=Object.keys(jP)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return gL.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return Un(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t)}))));if(0===o.length)return gL.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let a;if(gL.debug("updateRemoteCodec, from ".concat(n," to ").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&"video"===t.media.mediaType&&Un(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return gL.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(VP("USE_PUB_RTX")||VP("USE_SUB_RTX")){const e=mB(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=fB(zx.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));gL.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),gL.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===zx.VIDEO?s.videoCodecs:s.audioCodecs,c=e===zx.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:Uj,protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=ID(e);return dB(n),cB(n,t),lB(n,t),function(e){if("video"!==e.media.mediaType)return;const t=Jw();if(t.name!==Hw.SAFARI&&t.os!==Ww.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}(n),uB(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=ID(e);return i.attributes&&i.attributes.payloads&&Array.isArray(i.attributes.payloads)&&i.attributes.payloads.length>0&&i.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&VP("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),uB(i,t,this.localCapabilities.recv),EB(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>rN()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}(_G(_G({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!VP("ENABLE_PRE_SUB_WITH_PRE_PC")||!VP("PRE_USE_LOCAL_CODECS"))&&$L(this.store),this.store.aiClientMode),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);{const i=this.remoteSDP.toString(),n=gB(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(n||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==r||r(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),$L(this.store))if(e.preallocation&&VP("ENABLE_PRE_SUB_WITH_PRE_PC")){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,i=VP("PRE_SUB_NUM")||1,n=e>i?e:i,r=this.remoteSDP.preloadRemoteMedia(n),o=r.mids,s=r.preSSRCs;await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(s)),await this.presetMedia(o,s)}else{const t=e.preSSRCs,i=void 0===t?[]:t,n=i.map((e=>e.ssrcMsg[0].ssrcId));if(0===i.length)return;const r=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),await this.presetMedia(r,n)}}}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}var i,n}shouldUseAiAudioPreload(){return this.store.aiClientMode&&this.store.autoSubscribe&&!!this._nvMedia}async presetAiAudioMedia(e,t){if(!this._nvMedia)return;const i=await this._nvMedia.receiveByRTCMedia(zx.AUDIO,[{ssrcId:t}],void 0);this.store.autoReceiveAndPlayAudio&&this._nvMedia.play(),this.preMediaMap.set(t,{mid:e,track:i.track,player:void 0,transceiver:void 0,aiAudioMode:!0})}async presetMedia(e,t){for(const o of e.entries()){var i=HI(o,2);const e=i[0],s=i[1];for(const i of this.peerConnection.getTransceivers())if(null!=i.mid&&s===i.mid&&i.receiver.track){const o=i.receiver.track;if("audio"===o.kind&&this.shouldUseAiAudioPreload()){await this.presetAiAudioMedia(s,t[e]);break}if(VP("PRE_PLAYOUT_DELAY_HINT")){const e=i.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=VP("PRE_PLAYOUT_DELAY_HINT"),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(VP("PRE_PLAYOUT_DELAY_HINT"))))}let a,c;if("video"===o.kind&&VP("ENABLE_PRE_RENDER")){var n,r;let i=null===(n=this.store.preSubOptions)||void 0===n||null===(n=n[e])||void 0===n?void 0:n.element;const s=(null===(r=this.store.preSubOptions)||void 0===r||null===(r=r[e])||void 0===r?void 0:r.config)||{};gL.debug("try to play pre sub video","string"==typeof i?i:"element","config: ".concat(JSON.stringify(s))),"string"==typeof i&&(i=document.getElementById(i)||void 0),a=i instanceof HTMLVideoElement?new xU(_G({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(MD(5,"")),element:i},s)):new BU(_G({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(MD(5,"")),element:i},s),!i),a.updateVideoTrack(o),a.onFirstVideoFrameRender=()=>{var i;a&&(a.onFirstVideoFrameRender=void 0);const n=this.preMediaMap.get(t[e]);n&&(n.firstVideoRender=Date.now()),null===(i=this.onFirstVideoRender)||void 0===i||i.call(this,t[e])},a.onVideoBufferReady=()=>{var i;null===(i=this.onFirstVideoBufferReady)||void 0===i||i.call(this,t[e])},a.play(this.store.sessionId||void 0),this.isPreRender=!0}if("audio"===o.kind&&this.store.autoReceiveAndPlayAudio){c="track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(MD(5,""));const e=100;NM.play(o,c,e,this.store.sessionId||void 0),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia start audio playback, trackId: ").concat(c))}this.preMediaMap.set(t[e],{mid:s,track:o,player:a,transceiver:i,audioTrackId:c});break}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 i=!1;const n=e.rtpCapabilities;if(i=HI(this.remoteSDP.updateRemoteRTPCapabilities(n),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);i=i||e}const r=e.preSSRCs,o=void 0===r?[]:r,s=o.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(s)){const e=[],i=[];let n=!1;var t;if(Array.from(this.preMediaMap.entries()).every((t=>{let r=HI(t,2),o=r[0],s=r[1],a=s.mid,c=s.player,d=(s.track,s.audioTrackId),l=s.aiAudioMode;return e.push(a),i.push(o),this.preMediaMap.delete(o),c&&c.destroy(),d&&NM.stop(d),n=n||!!l,!0})),n)null===(t=this._nvMedia)||void 0===t||t.stopReceiving();if(e.length>0&&(this.remoteSDP.stopSending(e),await SB(this.peerConnection,this.remoteSDP,this.extension),gL.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(i)),YL.reportApiInvoke(this.store.sessionId,{name:QN.PRELOAD_MEDIA_FAILED,options:[o,i],tag:$N.TRACER}).onSuccess()),o.length>0){const e=this.remoteSDP.batchSend(o.map((e=>Object.assign({},e)))).mids;await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(s)),await this.presetMedia(e,s)}}i?(await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):gL.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return XO((function*(){const r=yield QO(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=JF();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,_G({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),rN()&&!0===VP("SIMULCAST")&&(yield QO(n.applySimulcastForFirefox(o,e)));const a=yield QO(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(a.sdp,e,c),l=JP(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 function(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}(t,VP("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield QO(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield QO(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield QO(n.stopSending(c,!0)),r}n.remoteSDP.receive(e,t,i,h);const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return yield QO(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield QO(n.applySimulcastEncodings(o,e)),yield QO(n.applySendEncodings(o,e)),null==_||_(p),yield QO(n.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=c[t];return{localSSRC:u[t],id:i,transceiver:e}}))}catch(e){throw e instanceof LN?e:new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)gL.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:VP("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const n=this.remoteSDP.sendDataChannel();if(n.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),gL.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else gL.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof LN?e:new LN(PN.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 LN?e:new LN(PN.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;Zj(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){if(this._nvMedia&&e===zx.AUDIO)return gL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by DataChannel.")),await this._nvMedia.receiveByRTCMedia(e,t,void 0);try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,i,n),o=r.mid;r.needExchangeSDP&&(await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");if(VP("PRE_PLAYOUT_DELAY_HINT")){const t=s.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=VP("PRE_PLAYOUT_DELAY_HINT"),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(VP("PRE_PLAYOUT_DELAY_HINT"))))}return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new LN(PN.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 t=this.remoteSDP.batchSend(e),i=t.mids;return t.needExchangeSDP&&(await SB(this.peerConnection,this.remoteSDP,this.extension),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),i.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");if(VP("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=VP("PRE_PLAYOUT_DELAY_HINT"),gL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(VP("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new LN(PN.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.");let t=!1;e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((i=>{let n=HI(i,2),r=n[0],o=n[1],s=o.mid,a=o.player,c=o.audioTrackId,d=o.aiAudioMode;if(s===e)return this.preMediaMap.delete(r),a&&a.destroy(),c&&NM.stop(c),t=t||!!d,!0}))})),t&&this._nvMedia&&(this._nvMedia.setAudioMetadataHandler(null),this._nvMedia.setAudioPtsHandler(null),this._nvMedia.stopReceiving()),this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const r=await this.peerConnection.createAnswer();null==n||n(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return XO((function*(){const i=yield QO(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=zL().supportPCSetConfiguration,r=VP("FORCE_TURN_TCP")||t.forceTurn;if(e===Xx.RELAY&&!n)return;if(n&&!r){const i=e===Xx.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(gL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const o=yield QO(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=nB(o.sdp),a=(yield s.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield QO(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield QO(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){gL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(Xx.TCP_RELAY),await SB(this.peerConnection,this.remoteSDP,this.extension)}catch(e){gL.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e,t,i,n;null===(e=this._nvMedia)||void 0===e||e.setAudioMetadataHandler(null),null===(t=this._nvMedia)||void 0===t||t.setAudioPtsHandler(null),null===(i=this._nvMedia)||void 0===i||i.close(),this._nvMedia=void 0,this.peerConnection.getTransceivers().forEach((e=>{Zj(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player,i=e.audioTrackId;t&&t.destroy(),i&&NM.stop(i)})),this.preMediaMap.clear(),this.peerConnection.close(),null===(n=this.onConnectionStateChange)||void 0===n||n.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(){const e=_G(_G({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason});if(this._nvMedia){const t=this._nvMedia.getStats();e.audioRecv.push(t)}return e}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?rN()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),i=t.local,n=t.remote;return{local:_G(_G({},cP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:_G(_G({},cP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",r=YF(e.url||"");gL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(r||"",", host_candidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&gL.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,gL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,gL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),VP("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(iD(t.turnServer.servers)?i.iceServers=t.turnServer.servers:VP("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(VP("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),VP("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),VP("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),VP("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(UF(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!VP("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=VP("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(UF(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(UF(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const e=i.getSelectedCandidatePair()||{},t=e.local,n=e.remote;if(t&&n){const e=t.address+":"+t.port,i=n.address+":"+n.port;gL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(YF(e)),", remote ").concat(JSON.stringify(YF(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 i,n;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return gL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return gL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!zL().supportSetRtpSenderParameters)return gL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r=GM(e),o=!!r&&("vp8"===(s=this.store.codec)||"vp9"===s)&&Fj(r);var s;const a=o&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),c=!!r&&!(o&&!a)&&function(e,t){var i;return!(!VP("ENABLE_AG_ADAPTATION")||!Fj(t)&&(!(e instanceof AV||Un(i=e._hints).call(i,gk.CUSTOM_TRACK))||!VP("FORCE_SUPPORT_AG_ADAPTATION")&&!(hN(14,0,!1)&&pN(17,4,!0)||uN(14)&&_N(17,4,!0))))}(e,a?r:void 0),d=a&&c,l=a||Un(i=["vp8","vp9"]).call(i,this.store.codec),u={},h={},p=function(e,t){if(t)return"maintain-resolution";const i=tG(e._optimizationMode);return i||void 0}(e,d);p&&(u.degradationPreference=p);const _=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack);if(c&&_&&t&&r&&this.getLocalVideoStats&&l){const i=this.id+_.mid,n=iG(e,a);!function(e,t,i,n,r,o){if(Zj(e,i),r(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;qj(e,t,n);const a=window.setInterval((()=>{const a=$j.get(e);if(!VP("ENABLE_AG_ADAPTATION")||!a)return Zj(e,i),void r(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,l=HI(zj(e,o,d,a.adaptationConfig,t,n),2),u=l[0],h=l[1];h&&(i.qualityLimitationReason=h),u&&a.adaptationConfig.scale!==u.scale&&(gL.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n           sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(u.scale," ")),a.adaptationConfig=Qj(Qj({},a.adaptationConfig),u),r(u))}}),VP("CHECK_LOCAL_STATS_INTERVAL")),c=Qj({},t);$j.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),gL.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}(i,r,this,n,(n=>{t&&this.updateAdaptation(e,t,n,i,a)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var E;const t=e._encoderConfig,i=t.bitrateMax,n=t.frameRate,r=t.scaleResolutionDownBy;i&&(h.maxBitrate=1e3*i),(Un(E=e._hints).call(E,gk.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(h.maxFramerate=FF(n)),r&&r>=1&&(h.scaleResolutionDownBy=r))}const f=VP("ENCODER_CONFIG_LIMIT").maxFramerate;if(f&&"number"==typeof f&&(h.maxFramerate=h.maxFramerate?Math.min(h.maxFramerate,f):f),VP("DSCP_TYPE")&&IN()){var m;const e=VP("DSCP_TYPE");Un(m=["very-low","low","medium","high"]).call(m,e)&&(h.networkPriority=e)}const S=t.getParameters(),g=null===(n=S.encodings)||void 0===n?void 0:n[0];rN()&&!g&&(u.encodings=[h]),g&&Object.assign(g,h),Object.assign(S,u),gL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(S.encodings))),await t.setParameters(S),await async function(e,t,i){try{var n;if(!zL().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!VP("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];o.scalabilityMode=JF(i),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),gL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){gL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,VP("SVC_MODE"))}async updateAdaptation(e,t,i,n,r){var o,s;if(!t)return gL.debug("[updateAdaptation] no rtpSender found");if(!zL().supportSetRtpSenderParameters)return gL.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const a={},c={},d=i.bitrateMax,l=i.frameRate,u=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=FF(l));let h=!1;"number"==typeof u&&u>=1&&(r||Un(o=["vp8","vp9"]).call(o,this.store.codec))&&(c.scaleResolutionDownBy=u,h=u>1);const p=t.getParameters(),_=null===(s=p.encodings)||void 0===s?void 0:s[0];_&&Object.assign(_,c),Object.assign(p,a);try{await t.setParameters(p),gL.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(p.encodings)))}catch(i){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)gL.debug("[updateAdaptation] peerConnection not connected}");else if(r&&h){const r=await oG(t,a,c);"unsupported"===r.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),Zj(n,this),gL.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,r.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{gL.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===r.classification?gL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):gL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,r.retryWithScaleError,r.retryWithoutScaleError)}else gL.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else gL.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!zL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof yV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){gL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){if(VP("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=JP(e);return t.forEach(((e,t)=>{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(cB(o,e),function(e,t,i){if(rN())return;if("video"!==e.media.mediaType)return;if(!(t instanceof yV))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!VP("SIMULCAST"))return;if("vp9"===i&&VP("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<n;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:ID(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:ID(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}(o,e,this.store.codec))})),zP(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,o,s;const c=e[a],d=t[a];if(d instanceof yV&&!Un(i=d._hints).call(i,gk.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!rN()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof yV&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r,o;return!!(e instanceof yV&&VP("SIMULCAST")&&"vp8"===this.store.codec&&!Un(t=e._hints).call(t,gk.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(VP("SDP_LOGGING"))return gL.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(zL().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},fx(hG.prototype,"updateRemoteRTPCapabilities",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"updateRemoteRTPCapabilities"),hG.prototype),fx(hG.prototype,"connect",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"connect"),hG.prototype),fx(hG.prototype,"updateRemoteConnect",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"updateRemoteConnect"),hG.prototype),fx(hG.prototype,"createDataChannels",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"createDataChannels"),hG.prototype),fx(hG.prototype,"receive",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"receive"),hG.prototype),fx(hG.prototype,"batchReceive",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"batchReceive"),hG.prototype),fx(hG.prototype,"stopReceiving",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"stopReceiving"),hG.prototype),fx(hG.prototype,"muteRemote",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"muteRemote"),hG.prototype),fx(hG.prototype,"unmuteRemote",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"unmuteRemote"),hG.prototype),fx(hG.prototype,"muteLocal",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"muteLocal"),hG.prototype),fx(hG.prototype,"unmuteLocal",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"unmuteLocal"),hG.prototype),fx(hG.prototype,"close",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"close"),hG.prototype),fx(hG.prototype,"updateEncoderConfig",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"updateEncoderConfig"),hG.prototype),fx(hG.prototype,"updateSendParameters",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"updateSendParameters"),hG.prototype),fx(hG.prototype,"replaceTrack",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"replaceTrack"),hG.prototype),fx(hG.prototype,"updateAdaptation",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"updateAdaptation"),hG.prototype),fx(hG.prototype,"getRemoteSSRC",[fG],Object.getOwnPropertyDescriptor(hG.prototype,"getRemoteSSRC"),hG.prototype),hG);function fG(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function mG(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=FF(t.width),n.height=FF(t.height);const r=FF(t.framerate||15);document.body.append(i),document.body.append(n);let o=e._mediaStreamTrack;i.srcObject=new MediaStream([o]),i.play().catch(VD);const s=n.getContext("2d");if(!s)throw new qL(PN.UNEXPECTED_ERROR,"can not get canvas context");const a=zL(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(gL.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r)}s.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,i.srcObject=new MediaStream([o]))},n.stopCapture=tM((()=>n.startCapture&&n.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),gL.debug("clean low stream renderer")},c}var SG=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(SG||{}),gG=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}(gG||{}),TG=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}(TG||{}),RG=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}(RG||{}),vG=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}(vG||{}),CG=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(CG||{}),IG=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(IG||{});const yG=1e3,AG=6,bG=3,OG=Math.max(AG,bG,60);function wG(e){return e=e.toLowerCase(),Un(e).call(e,"vp8")?1:Un(e).call(e,"h264")?2:Un(e).call(e,"vp9")?3:Un(e).call(e,"av1")?4:Un(e).call(e,"h265")?5:0}function NG(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function DG(e){const t={[vG.CONN_TYPE]:0,[vG.RTT]:e.rtt,[vG.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[vG.CONN_TYPE]=1),"tcp"===i&&(t[vG.CONN_TYPE]=3),"tls"===i&&(t[vG.CONN_TYPE]=4);break}case"srflx":t[vG.CONN_TYPE]=2;break;case"unknown":t[vG.CONN_TYPE]=5;break;default:t[vG.CONN_TYPE]=0}return t}function PG(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 LG extends JN{constructor(e){super(),Zb(this,"store",void 0),Zb(this,"uploadWRTCStatsTimer",void 0),Zb(this,"uploadOutboundDenoiserStatsTimer",void 0),Zb(this,"uploadExtStatsTimer",void 0),Zb(this,"uploadExtUsageStatsTimer",void 0),Zb(this,"uploadInboundExtStatsTimer",void 0),Zb(this,"requestStats",void 0),Zb(this,"requestTransportStats",void 0),Zb(this,"requestLocalMedia",void 0),Zb(this,"requestRemoteMedia",void 0),Zb(this,"requestAllTracks",void 0),Zb(this,"requestVideoIsReady",void 0),Zb(this,"requestUploadStats",void 0),Zb(this,"requestUpload",void 0),Zb(this,"uploadOutboundStarted",!1),Zb(this,"uploadInboundStarted",!1),Zb(this,"uploadTransportStarted",!1),Zb(this,"uploadBaseStatsStarted",!1),Zb(this,"uploadExtensionUsageStarted",!1),Zb(this,"lastRecvStats",void 0),Zb(this,"lastSendStats",void 0),Zb(this,"lastRefRecvStats",void 0),Zb(this,"lastRefSendStats",void 0),Zb(this,"lastNormalRecvStats",void 0),Zb(this,"lastNormalSendStats",void 0),Zb(this,"lastExtendStats",{}),Zb(this,"needUploadStats",{}),Zb(this,"needUploadRenderFreezeTime",!0),Zb(this,"lastUploadCompensateTime",-1),Zb(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%bG==0,i=e%AG==0,n=e%60==0;let r,o;if(this.uploadTransportStarted&&(r=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!r&&this.uploadOutboundStarted&&(r=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),r||o){var s;const a={};if(this.uploadTransportStarted&&r){const e=this.getTransportStats(r,t?this.lastRefSendStats:void 0,o,t);e&&(a.misc=[e])}if(this.uploadOutboundStarted&&r){const e=this.getOutboundStats(r,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,n);e&&(a.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const n=this.getInboundStats(o,i?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);n&&(a.inbound=n)}const c=null===(s=this.requestTransportStats)||void 0===s?void 0:s.call(this).connectState;if(c&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[CG.RTC_PEER_CONNECTION_STATE]=SP[c]):a.misc=[{addition:{[CG.RTC_PEER_CONNECTION_STATE]:SP[c]}}]),KV.needUploadStats.length>0||i){const e=KV.needUploadStats.shift()||("visible"===KV.visibility?1:0);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[CG.PAGE_VISIBILITY]=e):a.misc=[{addition:{[CG.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[SG.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,i&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,KV.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,i;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(i=this.requestUploadStats)||void 0===i||i.call(this,{misc:[{addition:{[CG.RTC_PEER_CONNECTION_STATE]:SP[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===OG+1&&(e=1)}),yG)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%bG==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const n=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*n;const r=this.requestStats(!0);new Array(n).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&r){const t=this.requestRemoteMedia()||[],i=[];t.forEach((e=>{let t=HI(e,2),n=t[0],o=t[1];const s={peer:n.uid};if((n._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(n._videoSSRC)||!1)&&o.has(zx.VIDEO)&&n.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const n={};if(i&&i._player){const e=i._player,t=e.renderFreezeAccTime2,r=e.videoElementStatus;if("visible"===KV.visibility&&r===Vk.PLAYING&&zL().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),NG(n,gG.Video_Render_Freeze_Time_Render2,i),VP("USE_NEW_RENDER_FREEZE_TIME")&&NG(n,gG.Video_Render_Freeze_Time_Render,i)}}return n}(n._videoSSRC,r,n.videoTrack);e&&(s.video=e)}s.video&&i.push(s)})),i.length>0&&(e.inbound=i,this.requestUploadStats(e))}}))}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,i,n){if(!this.requestStats)return;if(!n)return null==e.rtt?void 0:{addition:{[vG.RTT]:e.rtt,[vG.CONN_TYPE]:void 0,[vG.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=DG(e);if(this.store.useP2P){if(i){const e=DG(i);r[vG.CONN_TYPE]&&e[vG.CONN_TYPE]&&(r[vG.CONN_TYPE]+=e[vG.CONN_TYPE]<<3)}r[vG.CONN_TYPE]?r[vG.CONN_TYPE]+=110:r[vG.CONN_TYPE]=110}else{r[vG.CONN_TYPE]?r[vG.CONN_TYPE]+=100:r[vG.CONN_TYPE]=100;const i=function(e,t){if(t)return[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))];return[0,0]}(e,t);r[IG.Transport_Send_Bitrate]=i[0],r[IG.Transport_Recv_Bitrate]=i[1]}return{addition:r}}getOutboundStats(e,t,i,n,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||0===o.length)return;let s,a,c;return o.forEach((n=>{let o=HI(n,2),d=o[0],l=o[1],u=l.track,h=l.ssrcs;switch(d){case Zx.LocalVideoLowTrack:case Zx.LocalVideoTrack:if(d===Zx.LocalVideoTrack){var p;const n=function(e,t,i,n,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},c=s.sentFrame,d=s.inputFrame;if(n&&(NG(a,gG.Video_Send_Qp_Sum,s.qpSumPerFrame),s.codec&&NG(a,gG.Video_Send_Codec,wG(s.codec)),"number"==typeof s.powerEfficientEncoder&&NG(a,gG.Video_Send_Power_Efficient_Encoder,s.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;a[gG.Video_Send_Freeze]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(r){switch(c&&(NG(a,TG.Video_Send_Height,c.height),NG(a,TG.Video_Send_Width,c.width),NG(a,TG.Video_Send_Frame_Rate,c.frameRate)),a[TG.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[TG.Video_Send_Adaptation]=0;break;case"cpu":a[TG.Video_Send_Adaptation]=1;break;case"bandwidth":a[TG.Video_Send_Adaptation]=2;break;case"other":a[TG.Video_Send_Adaptation]=3}let n=0;s.adaptionChangeReason&&(n+=PG(s.adaptionChangeReason)),t.qualityLimitationReason&&(n+=PG(t.qualityLimitationReason)<<3),a[TG.Video_Send_Adaptation]=n,a[TG.Video_Send_Player_Status]=Fk[i._player?i._player.videoElementStatus:"uninit"],NG(a,TG.Video_Send_Nacks,s.nacksCount),NG(a,TG.Video_Send_Plis,s.plisCount),NG(a,TG.Video_Send_Firs,s.firsCount),NG(a,TG.Video_Send_Avg_Encode,s.avgEncodeMs),NG(a,TG.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),NG(a,TG.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),NG(a,TG.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),NG(a,TG.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const o=r.videoSend.find((t=>t.ssrc===e));if(o){let e=yG*bG;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.packets&&null!=s.packets&&NG(a,TG.Video_Send_Package_Rate,1e3*(s.packets-o.packets)/e),null!=s.packetsLost&&null!=o.packetsLost&&NG(a,TG.Video_Send_Package_Lost,s.packetsLost-o.packetsLost),null!=o.bytes&&null!=s.bytes&&NG(a,TG.Video_Send_Bitrate,8*(s.bytes-o.bytes)/e)}}return a}(h[0].ssrcId,e,u,t,i),o="CameraVideoTrack"===u.__className__?3:Un(p=u._hints).call(p,gk.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||r)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o);const s=u&&function(e,t,i,n){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(n){const e=r.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,s=e&&e.frameRate||0;NG(o,TG.Video_Capture_Height,t),NG(o,TG.Video_Capture_Width,n),NG(o,TG.Video_Capture_Frame_Rate,s)}return o}(h[0].ssrcId,e,u,!!i),c=function(e,t){const i={};return t&&(NG(i,TG.Video_Send_Retransmit,e.bitrate.retransmit),NG(i,TG.Video_Send_Target_Encoded,e.bitrate.targetEncoded),NG(i,TG.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),NG(i,TG.Video_Send_Transmit,e.bitrate.transmit),NG(i,TG.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);a=Object.assign({},n,s,c)}else c=function(e,t,i,n,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(n){const t=o.sentFrame;t&&(NG(s,TG.Video_Send_Low_Height,t.height),NG(s,TG.Video_Send_Low_Width,t.width),NG(s,TG.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=yG*AG;i.timestamp&&o.timestamp&&(e=o.timestamp-i.timestamp),null!=i.packets&&null!=o.packets&&NG(s,TG.Video_Send_Low_Package_Rate,1e3*(o.packets-i.packets)/e),null!=o.packetsLost&&null!=i.packetsLost&&NG(s,TG.Video_Send_Low_Package_Lost,o.packetsLost-i.packetsLost),null!=i.bytes&&null!=o.bytes&&NG(s,TG.Video_Send_Low_Bitrate,8*(o.bytes-i.bytes)/e)}}return s}(h[0].ssrcId,e,0,i);break;case Zx.LocalAudioTrack:s=u&&function(e,t,i,n,r,o){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(r){a[TG.Audio_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0;const t=100*i._source.getAccurateVolumeLevel(),n=s.inputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));NG(a,TG.Audio_Send_Level,e)}NG(a,TG.Audio_Capture_PCM_Level,t),NG(a,TG.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),NG(a,TG.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),NG(a,TG.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),NG(a,TG.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),a[TG.Audio_Send_Freeze]=0;const o=r.audioSend.find((t=>t.ssrc===e));if(o){let e=yG*AG;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.bytes&&null!=s.bytes&&NG(a,TG.Audio_Send_Bitrate,8*(s.bytes-o.bytes)/e),null!=o.packets&&null!=s.packets&&NG(a,TG.Audio_Send_Package_Rate,1e3*(s.packets-o.packets)/e)}}return a}(h[0].ssrcId,e,u,0,i)}})),{high:a,low:c,audio:s}}getInboundStats(e,t,i,n){if(!this.requestRemoteMedia)return;const r=this.requestRemoteMedia()||[],o=[];return r.forEach((r=>{let s=HI(r,2),a=s[0],c=s[1];const d={peer:a.uid};let l;if(c.has(zx.VIDEO)&&a.videoTrack){const r=a._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(a._videoSSRC)||!1,o=a.videoTrack?function(e,t,i,n,r,o,s,a){const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},l=c.receivedFrame,u=c.outputFrame,h=c.decodeFrameRate;NG(d,RG.Video_Render_Frame_Rate_Decode,h),c.framesRateFirefox&&NG(d,RG.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&NG(d,RG.Video_Recv_Frame_Rate,l.frameRate),NG(d,RG.Video_Recv_Frame_Dropped,c.framesDroppedCount),NG(d,RG.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),NG(d,RG.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),NG(d,RG.Video_Recv_Packages_Discarded,c.packetsDiscarded),NG(d,RG.Video_Recv_Avg_Decode,c.avgDecodeMs),NG(d,RG.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),NG(d,RG.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),NG(d,RG.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),NG(d,RG.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||yG;null!=c.packetsLost&&null!=p.packetsLost&&NG(d,RG.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&NG(d,RG.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&NG(d,RG.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}const _=o&&o.videoRecv.find((t=>t.ssrc===e));if(_&&(NG(d,gG.Video_Recv_Qp_Sum,c.qpSumPerFrame),c.codec&&NG(d,gG.Video_Recv_Codec,wG(c.codec)),"number"==typeof c.powerEfficientDecoder&&NG(d,gG.Video_Recv_Power_Efficient_Decoder,c.powerEfficientDecoder),d[gG.Video_Recv_Freeze]=n&&wj.isRemoteVideoFreeze(i,c,_)?1:0),s){var E;const t=s.videoRecv.find((t=>t.ssrc===e));l?(NG(d,TG.Video_Recv_Height,l.height),NG(d,TG.Video_Recv_Width,l.width)):i&&(NG(d,TG.Video_Recv_Height,i._videoHeight||0),NG(d,TG.Video_Recv_Width,i._videoWidth||0)),u&&NG(d,TG.Video_Recv_Frame_Rate_Output,u.frameRate);const n=null===(E=i._player)||void 0===E?void 0:E.rendFrameRate.toFixed(0);if(n&&NG(d,TG.Video_Render_Frame_Rate_Render,+n),NG(d,TG.Video_Recv_Jitter_Buffer,c.jitterBufferMs),NG(d,TG.Video_Recv_Current_Delay,c.currentDelayMs),NG(d,TG.Video_Recv_Firs,c.firsCount),NG(d,TG.Video_Recv_Nacks,c.nacksCount),NG(d,TG.Video_Recv_Plis,c.plisCount),i){d[TG.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const i=e.freezeTimeCounterList,n=e.renderFreezeAccTime,o=e.renderFreezeAccTime2,s=e.videoElementStatus;if(i&&i.length>0&&NG(d,gG.Video_Render_Freeze_Time,i.splice(0,1)[0]),r&&"visible"===KV.visibility&&s===Vk.PLAYING&&zL().supportRequestVideoFrameCallback){const t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),NG(d,gG.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,n);e.renderFreezeAccTime=Math.max(0,n-i),NG(d,gG.Video_Render_Freeze_Time_Render,VP("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof c.totalFreezesDuration){const e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;NG(d,TG.Video_Render_Freeze_Duration,1e3*e)}}}if(d[TG.Video_Recv_Player_Status]=Fk[i._player?i._player.videoElementStatus:"uninit"],t&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-t.totalInterFrameDelay,i=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=c.framesDecodeCount-t.framesDecodeCount,r=e/n*1e3,o=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(o)&&r+o>Math.max(3*r,r+150)&&(d[TG.Video_Recv_I_Frame_Delay]=o)}}return d}(a._videoSSRC,e,a.videoTrack,!0===r,this.needUploadRenderFreezeTime,t,i,n):void 0;if(o&&(d.video=o),a.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===a._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(l=t.estimatedPlayoutTimestamp)}}if(c.has(zx.AUDIO)&&a.audioTrack){const r=!a.hasAudio,o=a.audioTrack?function(e,t,i,n,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={};NG(c,RG.Audio_Recv_Jitter,a.jitterMs),NG(c,RG.Audio_Recv_Bytes_Retransmit,a.retransmittedBytesReceived),NG(c,RG.Audio_Recv_Packages_Retransmit,a.retransmittedPacketsReceived),NG(c,RG.Audio_Recv_Packages_Discarded,a.packetsDiscarded),NG(c,RG.Audio_Recv_Avg_Processing_Delay,a.avgProcessingDelayMs);const d=o&&o.audioRecv.find((t=>t.ssrc===e));if(d){const e=yG;null!=a.packets&&null!=d.packets&&NG(c,RG.Audio_Recv_Package_Rate,1e3*(a.packets-d.packets)/e),null!=a.packetsLost&&null!=d.packetsLost&&NG(c,RG.Audio_Recv_Package_Lost,a.packetsLost-d.packetsLost)}if(n){const e=a.receivedFrames,t=a.droppedFrames;null!=e&&null!=t&&(c[gG.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(r){const t=100*i._source.getAccurateVolumeLevel(),n=a.outputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));NG(c,TG.Audio_Render_Level,e)}NG(c,TG.Audio_Recv_PCM_Level,t),i&&(c[TG.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),NG(c,TG.Audio_Recv_Jitter_Buffer,a.jitterBufferMs),NG(c,TG.Audio_Recv_Current_Delay,a.jitterBufferMs),c[TG.Audio_Recv_Player_Status]=Fk[NM.getPlayerState(i.getTrackId())];const o=r.audioRecv.find((t=>t.ssrc===e));if(o&&(null!=o.bytes&&null!=a.bytes&&NG(c,TG.Audio_Recv_Bitrate,8*(a.bytes-o.bytes)/(yG*bG)),!s)){const e=a.concealedSamples-o.concealedSamples;e>0&&NG(c,TG.Audio_Recv_Concealed_Samples,e);const t=a.totalSamplesReceived-o.totalSamplesReceived;t>0&&NG(c,TG.Audio_Recv_Total_Samples_Received,t);const i=a.freezeSamples80-o.freezeSamples80;i>0&&NG(c,TG.Audio_Render_Freeze_Samples_80ms,i);const n=a.freezeSamples200-o.freezeSamples200;n>0&&NG(c,TG.Audio_Render_Freeze_Samples_200ms,n);const r=a.freezeMs80-o.freezeMs80;NG(c,TG.Audio_Render_Freeze_Time_80ms,r<0?0:r);const s=a.freezeMs200-o.freezeMs200;NG(c,TG.Audio_Render_Freeze_Time_200ms,s<0?0:s)}}return c}(a._audioSSRC,e,a.audioTrack,t,i,n,r):void 0;if(o&&(d.audio=o),a.audioTrack&&l){const t=e.audioRecv.find((e=>e.ssrc===a._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-l;d.audio?d.audio[RG.Audio_Recv_AV_Sync_TIME]=e:d.audio={[RG.Audio_Recv_AV_Sync_TIME]:e}}}}(d.video||d.audio)&&o.push(d)})),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 PU));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(yx.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=HI(e,2),i=t[0],n=t[1];if(n.has(zx.VIDEO)&&i.videoTrack){i.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(n.has(zx.AUDIO)&&i.audioTrack){i.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:VP("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const e of o){var s=HI(e,2);const t=s[0],i=s[1];i.has(zx.VIDEO)&&t.videoTrack&&(n=n.concat(await t.videoTrack.getProcessorUsage())),i.has(zx.AUDIO)&&t.audioTrack&&(n=n.concat(await t.audioTrack.getProcessorUsage()))}if(0===n.length)return;i.details=function(e,t){const i={};for(const s of e){var n;const e=s.id,a=s.value,c=s.level,d=s.direction,l=null!==(n=t.get(e))&&void 0!==n?n:0,u=2===a?l+VP("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:l;var r,o;t.set(e,u),i[e]?(2===a&&(i[e].value=a),c>i[e].level&&(i[e].level=c),"remote"===d&&(i[e].remoteUidCount+=1),i[e].totalTs=null!==(r=t.get(e))&&void 0!==r?r:0):i[e]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(e))&&void 0!==o?o:0}}return Object.keys(i).map((e=>{const t=i[e];return{id:e,level:t.level,value:t.value,totalTs:t.totalTs}}))}(n,e);const a=Date.now(),c=a>t?a:t+1;this.requestUpload&&this.requestUpload(yx.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:c})}),VP("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,KV.stopCollectStats()}}const kG=VP("ICE_RESTART_INTERVAL");let MG=new Map,UG=new Map,VG=[Xx.UDP_TCP_RELAY,Xx.TCP_RELAY,Xx.RELAY],xG=VP("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&zL().supportPCSetConfiguration;function FG(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=MG.get(e.id);i&&(window.clearTimeout(i),MG.delete(e.id));const n=UG.get(e.id);t&&n&&n.index===VG.length-1&&(gL.debug("[".concat(e.id,"] reset ICE restart policy")),UG.delete(e.id))}function BG(e,t,i){if(0===MG.size&&0===UG.size&&(Array.isArray(VP("RESTART_SEQUENCE"))&&VP("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){const n=e[i];if(e.filter((e=>e===n)).length!==t.filter((e=>e===n)).length)return!1}return!0}(VG,VP("RESTART_SEQUENCE"))&&(VG=VP("RESTART_SEQUENCE").filter((e=>{var t;if(Un(t=Object.values(Xx)).call(t,e))return!0})),gL.debug("use reconnection policy from config distribution, queues: ".concat(VG.join(" => ")))),xG=VP("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&zL().supportPCSetConfiguration),0===VG.length)return void i();let n,r=UG.get(e.id)||{},o=r.index,s=void 0===o?0:o,a=r.type;if(xG&&a===Xx.RELAY)return void i();let c=a&&s>=VG.length-1;if(xG)a=Xx.RELAY;else{if(c)return void i();a?(s++,a=VG[s]):(a=VG[0],s=0)}gL.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(a,", index: ").concat(s)),t(a),UG.set(e.id,{index:s,type:a}),n=window.setTimeout((()=>BG(e,t,i)),kG),MG.set(e.id,n)}var jG;function GG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function WG(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?GG(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):GG(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function HG(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=ZO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new KG(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function KG(e){function t(e){if(Object(e)!==e)return cp.reject(new TypeError(e+" is not an object."));var t=e.done;return cp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return KG=function(e){this.s=e,this.n=e.next},KG.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?cp.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?cp.reject(e):t(i.apply(this.s,arguments))}},new KG(e)}let YG=(jG=class extends JN{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(tF.StateChange,t,this._state)}constructor(e,t){super(),Zb(this,"isPlanB",void 0),Zb(this,"store",void 0),Zb(this,"statsUploader",void 0),Zb(this,"connection",void 0),Zb(this,"localTrackMap",new Map),Zb(this,"remoteUserMap",new Map),Zb(this,"localDataChannels",[]),Zb(this,"remoteDataChannelMap",new Map),Zb(this,"pendingLocalTracks",[]),Zb(this,"pendingRemoteTracks",[]),Zb(this,"pendingLocalDataChannels",[]),Zb(this,"pendingRemoteDataChannels",[]),Zb(this,"statsCollector",void 0),Zb(this,"shouldForwardP2PCreation",void 0),Zb(this,"iceFailedCount",0),Zb(this,"dtlsFailedCount",0),Zb(this,"mutex",void 0),Zb(this,"_state",eF.Disconnected),Zb(this,"_p2pBySDPEndPoint",!1),Zb(this,"_pcStatsUploadType",VP("NEW_ICE_RESTART")?Qx.FIRST_CONNECTION:Qx.OLD_FIRST_CONNECTION),Zb(this,"_isStartRestartIce",!1),Zb(this,"_restartTimer",void 0),Zb(this,"_isTryConnecting",!1),Zb(this,"_iceError",null),Zb(this,"_forceTurn",!1),Zb(this,"_isWaitPcToRePub",!1),Zb(this,"handleMuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==eF.Connected)return void i(new LN(PN.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,gL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?gL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(r.map((e=>HI(e,2)[1].id)));const s=this.createMuteMessage(r);await hD(this,tF.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),Zb(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==eF.Connected)return void i(new LN(PN.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,gL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!VP("DISABLE_DUAL_STREAM_USE_ENCODING")&&zL().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=mG(e,_D(this,tF.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new cp(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}this.store.enableInstantMuteRestore?gL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map((e=>HI(e,2)[1].id)));const s=this.createUnmuteMessage(r);await hD(this,tF.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),Zb(this,"handleUpdateVideoEncoder",(async(e,t,i,n)=>{let r;n||(r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(Zx.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==eF.Connected)return void t();const n=i.id,s=i.track;await this.connection.updateSendParameters(n,s),await this.connection.updateEncoderConfig(n,s),this.emit(tF.UpdateVideoEncoder,s),t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),Zb(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(Zx.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==eF.Connected)return void t();const r=i.id,o=i.track;await this.connection.updateSendParameters(r,o),this.emit(tF.UpdateVideoEncoder,o),t()}catch(e){i(e)}finally{n()}})),Zb(this,"handleUpdateVideoResolution",(async e=>{const t=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoResolution");try{var i,n;const r=this.localTrackMap.get(Zx.LocalVideoTrack),o=this.localTrackMap.get(Zx.LocalVideoLowTrack);if(!this.connection||!r||!o||r.track!==e||this.state!==eF.Connected||!VP("ENABLE_DUAL_STREAM_RESOLUTION_CORRECTION")||VP("DISABLE_DUAL_STREAM_USE_ENCODING")||!zL().supportDualStreamEncoding)return;const s=_D(this,tF.RequestLowStreamParameter)||{width:160,height:120,framerate:15,bitrate:50},a=o.track,c=null===(i=a._encoderConfig)||void 0===i?void 0:i.scaleResolutionDownBy,d=HF(s,a);if((null===(n=a._encoderConfig)||void 0===n?void 0:n.scaleResolutionDownBy)===d)return;a._encoderConfig=a._encoderConfig||{},a._encoderConfig.scaleResolutionDownBy=d,await this.connection.updateRtpSenderEncodings(a),YL.reportApiInvoke(this.store.sessionId,{name:"lowStreamResolutionCorrection",options:{actualWidth:e.videoWidth,actualHeight:e.videoHeight,lowStreamParameter:s,previousScaleResolutionDownBy:null!=c?c:null,scaleResolutionDownBy:d},tag:$N.TRACER}).onSuccess()}catch(e){gL.warn("[".concat(this.store.clientId,"] update low stream resolution failed"),e)}finally{t()}})),Zb(this,"handleReplaceMixingTrack",(async(e,t,i,n)=>{if(!this.connection||this.state!==eF.Connected)return void t();const r=aG([e]);let o;gL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof n&&n||(o=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t()}catch(e){i(e)}finally{var s;null===(s=o)||void 0===s||s()}})),Zb(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;gL.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let i=HI(t,2)[1].track;return e===i}));if(!this.connection||!i||this.state!==eF.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===Zx.LocalVideoTrack&&!VP("DISABLE_DUAL_STREAM_USE_ENCODING")&&zL().supportDualStreamEncoding){const t=this.localTrackMap.get(Zx.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cp(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),Zb(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),Zb(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),Zb(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),Zb(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),Zb(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new LG(this.store),this.bindStatsUploaderEvents(),this.mutex=new JD("P2PChannel-mutex",this.store.clientId),this.isPlanB=!zL().supportUnifiedPlan||VP("CHROME_FORCE_PLAN_B")&&IN(),this.shouldForwardP2PCreation=VP("FORWARD_P2P_CREATION")&&zL().supportPCSetConfiguration&&(CN()||VP("ENABLE_JOIN_V4")),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var i;this.state=eF.New,this._forceTurn=uG(e),gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if((!this.shouldForwardP2PCreation||n||t)&&((n||t)&&this.connection&&(gL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new LN(PN.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=VP("NEW_ICE_RESTART")?Qx.FIRST_CONNECTION:Qx.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)}markSDPEndpointConnection(){this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new LN(PN.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==eF.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=eF.Connected,t}if(this.connection instanceof EG||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name)if(this.store.flexiblePC);else{const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),i=PB(e.iceParameters.iceUfrag,e.iceParameters.icePwd);i||gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const n=this.connection.checkIceParameters(e.iceParameters),r=t||!i||n&&!(this.connection instanceof EG);if(r||n){gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(r?"try next":"restart ICE"));return YL.reportApiInvoke(this.store.sessionId,{name:t?QN.MISMATCH_DTLS_PARAMETERS:QN.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:$N.TRACER}).onSuccess(),void this.emit(tF.RequestReconnect)}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let i=HI(e,1)[0];return Un(t=[Zx.LocalVideoLowTrack,Zx.LocalVideoTrack]).call(t,i)})),i=t.map((e=>HI(e,2)[1].id)),n=t.map((e=>HI(e,1)[0]));if(this.connection instanceof EG||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(YL.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Un(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Un(e).call(e,t)));t&&(this.store.codec=t,gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof EG&&"closed"!==this.connection.peerConnectionState&&Un(e=[eF.New,eF.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==eF.Connected){if(this.state===eF.Disconnected)throw new LN(PN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Un(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,i){var n=this;return XO((function*(){const r=yield QO(n.mutex.lock("From P2PChannel.publish"));try{var o;const s=n.connection&&Un(o=["disconnected","failed"]).call(o,n.connection.peerConnectionState);if(!n.connection||n.state!==eF.Connected||s){if(n.state===eF.Disconnected)throw new LN(PN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return n.pendingLocalTracks=n.pendingLocalTracks.concat(t),void(s&&(n._isWaitPcToRePub=!0))}n.store.pubId=n.store.pubId+1,Aj.markPublishStart(n.store.clientId,n.store.pubId);const a=n.filterTobePublishedTracks(e,t,i);if(0===a.length)return void(yield QO(n.tryToUnmuteAudio(e)));yield*$O(HG(n.doPublish(n.connection,a)))}finally{r()}}))()}doPublish(e,t){var i=this;return XO((function*(){t.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===Zx.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>e.track)),r=yield QO(e.send(n,i.store.codec,i.store.audioCodec)),o=(yield QO(r.next())).value,s=i.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===PN.WS_ABORT&&t.forEach((e=>{let t=e.track;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(s,a,n),d=(yield QO(r.next(c))).value;if(i.state===eF.Disconnected)throw new LN(PN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");VP("ENABLE_AUDIO_METADATA");n.forEach((async e=>{e.getRTCRtpTransceiver()})),t.forEach((e=>{let t=e.type;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===Zx.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i||!this.connection)return;if(!(i.track instanceof yV))return gL.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const n=i.track,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=HF(e,t)),i.maxFramerate=e.framerate?FF(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==Zx.LocalVideoLowTrack||!VP("DISABLE_DUAL_STREAM_USE_ENCODING")&&zL().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return gL.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=FF(t.width)),t.height&&(i.height=FF(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=tM((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),FF(t.framerate)))}(t,e)}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&"object"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),gL.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return XO((function*(){if(!t.connection||t.state!==eF.Connected)return;const i=yield QO(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(Zx.LocalVideoTrack);if(!r)throw new LN(PN.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(Zx.LocalVideoLowTrack))throw new LN(PN.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:Zx.LocalVideoLowTrack}];if(yield*$O(HG(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(Zx.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield QO(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(gL.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await uD(this,tF.RequestRePublish,this.pendingLocalTracks),this.emit(tF.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(gL.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await uD(this,tF.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const t=this.pendingRemoteTracks[e],i=t.user,n=t.kind;(n!==zx.AUDIO||i._audio_added_&&i._audioSSRC)&&(n!==zx.VIDEO||i._video_added_&&i._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await uD(this,tF.RequestReSubscribe,this.pendingRemoteTracks);else for(const e of this.pendingRemoteTracks){const t=e.user,i=e.kind;await this.subscribe(t,i,i===zx.VIDEO?t._videoSSRC:t._audioSSRC)}this.pendingRemoteTracks.forEach((e=>{let t=e.user;this.emit(tF.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==eF.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==eF.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!==eF.Connected)return;const e=this.localTrackMap.get(Zx.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[Zx.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>HI(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=HI(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=HI(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==eF.Connected)throw new LN(PN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let n=i.user,r=i.id;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var o;if(!this.connection||this.state!==eF.Connected)throw new LN(PN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c,d,l;const u=this.connection.getPreMedia(i);if(u)gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=u.transceiver,s=u.track,a=u.mid,d=u.player,l=u.audioTrackId,u.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:u.firstVideoRender});else if(r){const i=r.find((e=>e.stream_type===t));if(!i)throw new LN(PN.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);(this.connection instanceof EG||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=n.transceiver),s=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);(this.connection instanceof EG||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),s=r.track,a=r.id}t===zx.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new HV(s,e.uid,e._uintid,this.store),gL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l&&(e._audioTrack._reusePreAudioElement(l,!0),u&&(u.audioTrackId=void 0)),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new WV(s,e.uid,e._uintid,this.store,d),gL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(yk.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(yk.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(yk.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(yk.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack));const h=this.remoteUserMap.get(e);h?h.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const p=this.pendingRemoteTracks.findIndex((i=>{let n=i.user,r=i.kind;return n.uid===e.uid&&t===r}));-1!==p&&(this.pendingRemoteTracks.splice(p,1),this.emit(tF.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==eF.Connected)throw new LN(PN.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let i=e.user,n=e.mediaType;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=[],i=new Map;e.forEach((e=>{if(!this.connection)return;const n=this.connection.getPreMedia(e.ssrcId);if(n){const t=n.track,r=n.mid,o=n.transceiver,s=n.player,a=n.audioTrackId;i.set(e.ssrcId,{track:t,id:r,transceiver:o,player:s,audioTrackId:a})}else t.push(e)}));const n=await this.connection.batchReceive(t.map((e=>{let t=e.user;return{kind:e.mediaType,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtxSsrcId}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{i.set(e.ssrcId,n[t])}));for(const t of e){const e=t.user,n=t.mediaType,r=t.ssrcId,o=i.get(r);if(!o)return void gL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(e.uid," subscribe data,").concat(n,", ").concat(r));const s=o.track,a=o.id,c=o.transceiver,d=o.player,l=o.audioTrackId;if(n===zx.AUDIO){if(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new HV(s,e.uid,e._uintid,this.store),gL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l){e._audioTrack._reusePreAudioElement(l,!0);const t=this.connection.getPreMedia(r);t&&(t.audioTrackId=void 0)}c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)}else e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new WV(s,e.uid,e._uintid,this.store,d),gL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack);const u=this.remoteUserMap.get(e);u?u.set(n,a):this.remoteUserMap.set(e,new Map([[n,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex((t=>{let i=t.user,r=t.kind;return i.uid===e.uid&&n===r}));-1!==h&&(this.pendingRemoteTracks.splice(h,1),this.emit(tF.MediaReconnectEnd,e.uid))}}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let n=i.user,r=i.kind;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===eF.Connected||i||n.forEach((t=>{let i=t.kind;var n;if(i===zx.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===zx.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==eF.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>HI(e,2)[1].id)));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let t=HI(e,2),n=t[0],r=t[1].kind;var o,s;r===zx.VIDEO&&n._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(n._videoSSRC,!1));if(r===zx.VIDEO)this.unbindRemoteTrackEvents(n._videoTrack),i||(null===(s=n._videoTrack)||void 0===s||s._destroy(),n._videoTrack=void 0);else if(r===zx.AUDIO){var a;if(this.unbindRemoteTrackEvents(n._audioTrack),!i)null===(a=n._audioTrack)||void 0===a||a._destroy(),n._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const i of e){const e=i.user,n=i.mediaType,r=this.pendingRemoteTracks.filter((t=>{let i=t.user,r=t.kind;return void 0!==n?i.uid===e.uid&&n===r:i.uid===e.uid}));r.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(r)}if(!this.connection||this.state!==eF.Connected)return void t.forEach((e=>{let t=e.user,i=e.kind;var n;if(i===zx.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===zx.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=sr(e).call(e,((e,t)=>{let i=t.user,n=t.mediaType;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>HI(e,2)[1].id)));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let t=HI(e,2),i=t[0],n=t[1].kind;var r,o;n===zx.VIDEO&&i._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(n===zx.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),null===(o=i._videoTrack)||void 0===o||o._destroy(),i._videoTrack=void 0;else if(n===zx.AUDIO){var s;this.unbindRemoteTrackEvents(i._audioTrack),null===(s=i._audioTrack)||void 0===s||s._destroy(),i._audioTrack=void 0}})),n}isPreSubScribe(e){if(!this.connection||this.state!==eF.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void gL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void gL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===zx.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void gL.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||gL.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(Zx.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(Zx.LocalAudioTrack);if((null==t?void 0:t.track)instanceof kU){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>HI(e,1)[0]!==Zx.LocalAudioTrack)).filter((t=>{let i=HI(t,1)[0];return!(e&&i===Zx.LocalVideoLowTrack)})).map((e=>HI(e,2)[1].track)).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let i=HI(t,1)[0];return!(e&&i===Zx.LocalVideoLowTrack)})).map((e=>HI(e,2)[1].track))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(Zx.LocalAudioTrack),o=n?this.localTrackMap.get(Zx.LocalVideoLowTrack):this.localTrackMap.get(Zx.LocalVideoTrack);YL.publish(this.store.sessionId,{eventElapse:Aj.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(gk.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find((e=>e instanceof DU)),a=n?null===(o=this.localTrackMap.get(Zx.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof yV));YL.publish(this.store.sessionId,{eventElapse:Aj.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(gk.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===zx.VIDEO?i._videoSSRC:i._audioSSRC;r&&YL.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===zx.VIDEO,audio:n===zx.AUDIO,peerid:i.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:Aj.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){gL.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new JD("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(Zx.LocalAudioTrack);if((null==e?void 0:e.track)instanceof kU){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=eF.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(Zx.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(Zx.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 yV||t&&t.track instanceof DU?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=HI(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(Zx.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=t_(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(gL.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=eF.Reconnecting,VP("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=HI(e,1)[0];var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let i=HI(e,2),n=i[0],r=i[1].track;switch(n){case Zx.LocalVideoTrack:Un(t=r._hints).call(t,gk.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case Zx.LocalAudioTrack:r instanceof kU?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case Zx.LocalVideoLowTrack:}})),this.emit(tF.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=HI(e,2),i=t[0],n=t[1];Array.from(rL(n).call(n)).forEach((e=>{this.setPendingRemoteMedia(i,e)})),this.emit(tF.MediaReconnectStart,i.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=HI(e,2),i=t[0],n=t[1];Array.from(rL(n).call(n)).forEach((e=>{this.setPendingRemoteDataChannel(i,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),gL.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const n=i.user,r=i.id;if((e instanceof Pj?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const n=i.user,r=i.kind;if((e instanceof Pj?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return XO((function*(){if(!t.connection||t.state!==eF.Connected)return;const i=yield QO(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield QO(t.connection.restartICE(e));const r=yield QO(n.next());if(r.done)return;const o=r.value,s=yield o;switch(lG(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case Xx.UDP_TCP_RELAY:t._pcStatsUploadType=Qx.UDP_TCP_RESTART;break;case Xx.TCP_RELAY:t._pcStatsUploadType=Qx.TCP_RESTART;break;case Xx.RELAY:t._pcStatsUploadType=Qx.RELAY_RESTART;break;default:t._pcStatsUploadType=Qx.OLD_RESTART}t._isTryConnecting=!0,n.next(s)}catch(e){var r;yield QO(null===(r=n)||void 0===r?void 0:r.throw(e))}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(Zx.LocalVideoTrack),i=this.localTrackMap.get(Zx.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!r)return 1;const o=pD(this,tF.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(gk.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return zV[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let n=HI(i,1)[0];const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=pD(this,tF.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 cp(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(gL.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==eF.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let i=HI(t,2)[1].track;return e===i}));if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===Zx.LocalVideoTrack&&!VP("DISABLE_DUAL_STREAM_USE_ENCODING")&&zL().supportDualStreamEncoding){const t=this.localTrackMap.get(Zx.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cp(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=vD(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(Zx.LocalAudioTrack);for(const r of e){if(r instanceof yV&&(this.localTrackMap.has(Zx.LocalVideoTrack)||s?new LN(PN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:Zx.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:Zx.LocalVideoLowTrack})}if(r instanceof DU)if(a){const e=a.track;if(e instanceof kU)sG([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=aG([e,r]);gL.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 kU)sG([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&zL().webAudioMediaStreamDest&&!r._bypassWebAudio){o=aG(o?[r,o]:[r])}else o=r}return o&&(gL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),n.push({track:o,type:Zx.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=vD(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof DU){const e=this.localTrackMap.get(Zx.LocalAudioTrack);if(!e)continue;e.track instanceof kU?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([Zx.LocalAudioTrack,e]),e.track.close())):t.push([Zx.LocalAudioTrack,e])}if(i instanceof yV){const e=this.localTrackMap.get(Zx.LocalVideoTrack);if(!e)continue;t.push([Zx.LocalVideoTrack,e]);const i=this.localTrackMap.get(Zx.LocalVideoLowTrack);i&&t.push([Zx.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=vD(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=vD(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case Zx.LocalVideoTrack:t.addListener(Sk.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Sk.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Sk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Sk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(Sk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Sk.VIDEO_RESOLUTION_UPDATED,this.handleUpdateVideoResolution),t.addListener(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Zx.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case Zx.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof kU?e.trackList.forEach((e=>{e.addListener(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Sk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Sk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(Sk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(Sk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=HI(e,2),i=t[0];return{track:t[1].track,type:i}}))),e.forEach((e=>{let t=e.track;switch(e.type){case Zx.LocalVideoTrack:t.off(Sk.GET_STATS,this.handleGetLocalVideoStats),t.off(Sk.GET_RTC_STATS,this.handleGetRTCStats),t.off(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Sk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Sk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(Sk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Sk.VIDEO_RESOLUTION_UPDATED,this.handleUpdateVideoResolution),t.off(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Zx.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case Zx.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof kU?e.trackList.forEach((e=>{e.off(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Sk.GET_STATS,this.handleGetLocalAudioStats),e.off(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Sk.GET_STATS,this.handleGetLocalAudioStats),e.off(Sk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Sk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Sk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Sk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(Sk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Sk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof WV&&t.addListener(Sk.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof HV&&t.addListener(Sk.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Sk.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=HI(e,2),i=t[0],n=t[1];n.has(zx.AUDIO)&&this.unbindRemoteTrackEvents(i._audioTrack),n.has(zx.VIDEO)&&this.unbindRemoteTrackEvents(i._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,o,s=e.track;switch(e.type){case Zx.LocalAudioTrack:r=Vx.Audio,o={dtx:s instanceof PU&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case Zx.LocalVideoTrack:r=Un(n=s._hints).call(n,gk.SCREEN_TRACK)?Vx.Screen:Vx.High,o=WG(WG({},BF(s)),{},{codec:this.store.codec,svc_mode:JF()});break;case Zx.LocalVideoLowTrack:r=Vx.Low,o=WG(WG({},BF(s)),{},{codec:this.store.codec,svc_mode:JF()})}return{stream_type:r,attributes:o,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,n=HI(e,2),r=n[0],o=n[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case Zx.LocalVideoTrack:i=Un(t=s._hints).call(t,gk.SCREEN_TRACK)?Vx.Screen:Vx.High;break;case Zx.LocalAudioTrack:i=Vx.Audio;break;case Zx.LocalVideoLowTrack:i=Vx.Low}return{stream_type:i,ssrcs:a,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let n=e.track,r=e.type;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=HI(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(tF.PeerConnectionStateChange,t),"connecting"===t&&e instanceof EG&&!rN()&&VP("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),VP("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 EG&&FG(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=Qx.DISCONNECTED_OR_FAILED;if("CONNECTED"===pD(this,tF.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));YL.reportApiInvoke(this.store.sessionId,{name:QN.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:$N.TRACER}).onSuccess(),this.republish()}}if(VP("NEW_ICE_RESTART")&&e instanceof EG&&!rN()&&!this._forceTurn&&!this.store.useDcSignal){if(Un($x).call($x,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(lG(e)){gL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===pD(this,tF.QueryClientConnectionState)&&this.emit(tF.RequestRestartICE,t)}},i=()=>{lG(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),gL.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(tF.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{BG(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&VP("ICE_RESTART")){"CONNECTED"===pD(this,tF.QueryClientConnectionState)&&this.emit(tF.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(gL.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(tF.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(gL.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(tF.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=t=>{"connected"!==t||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(t,")")),YL.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:t,tag:$N.TRACER}).onSuccess(),this.emit(tF.IceConnectionStateChange,{state:t,remoteUfrag:this.connection===e&&e instanceof EG?e.remoteIceUfrag:void 0})},e.onICETransportStateChange=e=>{gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onAudioMetadata=e=>{this.safeEmit(tF.AudioMetadata,e)},e.onAudioPts=e=>{this.safeEmit(tF.AudioPts,e)},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(yk.FIRST_FRAME_DECODED),YL.firstRemoteFrame(this.store.sessionId,yL.FIRST_AUDIO_DECODE,AL.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:Aj.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&YL.firstRemoteFrame(this.store.sessionId,yL.FIRST_AUDIO_RECEIVED,AL.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:Aj.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{var n;const r=Array.from(rL(n=this.remoteUserMap).call(n)).find((t=>t._videoSSRC===e));r&&this.store.firstVideoFrameDecoded(r.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoRender=e=>{var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&(this.store.firstVideoFrameDecoded(i.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(i),this.emit(tF.FirstVideoPreRender,i.uid,e))},e.onFirstVideoReceived=e=>{var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&(this.store.firstVideoFrameDecoded(i.uid,{firstReceived:Date.now()}),YL.firstRemoteFrame(this.store.sessionId,yL.FIRST_VIDEO_RECEIVED,AL.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:Aj.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;const i=Array.from(rL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&this.emit(tF.FirstVideoBufferReady,i.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(tF.ConnectionTypeChange,i),gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(KF(t))," -> ").concat(JSON.stringify(KF(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{gL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(KF(t))," -> ").concat(JSON.stringify(KF(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return WG(WG({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){gL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===eF.Connected?(gL.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 EG&&function(e){UG.delete(e.id),FG(e)}(e),e.close(),this.emit(tF.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=dG(this.store,e),this.emit(tF.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(Zx.LocalAudioTrack);if(e instanceof DU&&(null==i?void 0:i.track)instanceof kU)return i.track.isActive||t.push([Zx.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let i=HI(t,2)[1].track;return e===i}));if(n&&(t.push(n),n[0]===Zx.LocalVideoTrack)){const e=this.localTrackMap.get(Zx.LocalVideoLowTrack);e&&t.push([Zx.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(Zx.LocalAudioTrack);if(e instanceof DU&&(null==i?void 0:i.track)instanceof kU)return i.track.isActive&&t.push([Zx.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let i=HI(t,2)[1].track;return e===i}));if(n)if(n[0]===Zx.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(Zx.LocalVideoLowTrack);e&&t.push([Zx.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,n=HI(e,2),r=n[0],o=n[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case Zx.LocalAudioTrack:i=Vx.Audio;break;case Zx.LocalVideoTrack:i=Un(t=s._hints).call(t,gk.SCREEN_TRACK)?Vx.Screen:Vx.High;break;case Zx.LocalVideoLowTrack:i=Vx.Low}return{stream_type:i,ssrcs:a,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,n=HI(e,2),r=n[0],o=n[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case Zx.LocalAudioTrack:i=Vx.Audio;break;case Zx.LocalVideoTrack:i=Un(t=s._hints).call(t,gk.SCREEN_TRACK)?Vx.Screen:Vx.High;break;case Zx.LocalVideoLowTrack:i=Vx.Low}return{stream_type:i,ssrcs:a,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let n=HI(t,2),r=n[0],o=n[1];i.push([e,{kind:r,id:o}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let i=HI(e,2),n=i[0],r=i[1],o=r.kind;switch(r.id,o){case zx.VIDEO:return void(n._videoSSRC&&t.push({stream_type:zx.VIDEO,ssrcId:n._videoSSRC}));case zx.AUDIO:return void(n._audioSSRC&&t.push({stream_type:zx.AUDIO,ssrcId:n._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let i=HI(e,2),n=i[0],r=i[1].kind;if(t.has(n)){let e=t.get(n);r===zx.VIDEO?e|=Bx.Video:e|=Bx.Audio,t.set(n,e)}else r===zx.VIDEO?t.set(n,Bx.Video):t.set(n,Bx.Audio)})),{users:Array.from(t.entries()).map((e=>{let t=HI(e,2),i=t[0],n=t[1];return{stream_id:i.uid,stream_type:n}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let t=HI(e,2),i=t[0],n=t[1].kind;const r=this.remoteUserMap.get(i);r&&(r.delete(n),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(i))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(Zx.LocalVideoTrack),i=this.localTrackMap.get(Zx.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new cp(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new cp(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof EG&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof EG)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof EG&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var r;let o=e.stream_type;const s=null===(r=t.find((e=>{let t=e.stream_type;return o===t})))||void 0===r?void 0:r.attributes;if(s&&VP("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(Un(e).call(e,gk.SCREEN_TRACK)||Un(e).call(e,gk.SCREEN_LOW_TRACK))&&(s.remb=!1,gL.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof DU){var t;const n=this.filterTobeUnmutedTracks(e[i]);if(0===n.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(n.map((e=>HI(e,2)[1].id))));const r=this.createUnmuteMessage(n);return void await hD(this,tF.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(tF.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(tF.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 kD(QD(this.dtlsFailedCount,XD)),this.emit(tF.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await uD(this,tF.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(tF.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(Zx.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof yV))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof yV)).length>1)throw new LN(PN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof DU)).length>1&&(e.some((e=>e instanceof DU&&e._bypassWebAudio))||!zL().webAudioMediaStreamDest))throw new LN(PN.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 yV&&this.pendingLocalTracks.some((e=>e instanceof yV)))throw new LN(PN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof DU&&this.pendingLocalTracks.some((e=>e instanceof DU))&&(!zL().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof DU&&e._bypassWebAudio))))throw new LN(PN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var i;const n=!VP("DISABLE_DUAL_STREAM_USE_ENCODING")&&zL().supportDualStreamEncoding,r=WG(WG({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=n?e._mediaStreamTrack.clone():mG(e,r);const s=MD(8,"track-low-"),a=new yV(o,WG(WG({},n&&{scaleResolutionDownBy:HF(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(Ck.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,Tk.LOW_STREAM)})),a._hints.push(gk.LOW_STREAM),Un(i=e._hints).call(i,gk.SCREEN_TRACK)&&a._hints.push(gk.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(Sk.NEED_CLOSE,(()=>{a.close()})),a}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof EG){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,d=this.connection,l=d.iceConnectionState,u=d.dtlsTransportState,h=d.peerConnectionState,p=await this.connection.getSelectedCandidatePair(),_=p.local,E=p.remote;YL.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:l,dtlsstate:u,connectionstate:h,intSucc:t?1:2,error:this._iceError||n||"",selectedLocalCandidateProtocol:null!==(r=null==_?void 0:_.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(o=_.candidateType)&&void 0!==o?o:"",selectedLocalCandidateAddress:"".concat(_.address,":").concat(_.port),selectedRemoteCandidateProtocol:null!==(s=E.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(a=E.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(E.address,":").concat(E.port),restartCnt:i,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,i=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!i)return;const n=i.isInternalUpload,r=i.isExternalUpload;if(n&&r)return;const o=i.subscribeEnd,s=i.firstPreRender,a=i.peerPublishDuration,c=i.peerPubStatusMs;let d=i.firstRender,l=void 0===d?0:d;if(o&&(l||s)&&a&&c){i.isInternalUpload=!0;const n=i.playEnd;n&&(i.isExternalUpload=!0);const r=i.firstPreRender,s=void 0===r?0:r;l=s||l;const d=e.videoTrack,u={peer:e._uintid,width:(null==d?void 0:d._videoWidth)||0,height:(null==d?void 0:d._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:a,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:i.userJoinNotify||0,videoAddNotify:i.videoAddNotify||0,subscribeStart:i.subscribeStart||0,subscribeEnd:i.subscribeEnd||0,firstReceived:i.firstReceived||0,firstDecoded:i.firstDecoded||0,firstPreRender:s||0,firstRender:n?Math.max(l,n):Math.max(l,o),playStart:i.playStart||0,playEnd:i.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:ZL(this.store),firstReceivedEncodedFrame:i.firstReceivedEncodedFrame||0,frameType:i.frameType||"",rtpTimestamp:i.rtpTimestamp||0,framePayloadType:i.framePayloadType||0,frameDataLength:i.frameDataLength||0,mimeType:i.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};YL.firstXLAPeerFirstVideoFrame(this.store.sessionId,u)}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(rL(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));YL.firstRemoteVideoDecode(this.store.sessionId,yL.FIRST_VIDEO_DECODE,AL.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:Aj.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=HI(e,2),i=t[0],n=t[1].track;i===Zx.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,Tk.LOW_STREAM):n._updateRtpTransceiver(void 0)}))}},fx(jG.prototype,"startP2PConnection",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"startP2PConnection"),jG.prototype),fx(jG.prototype,"connect",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"connect"),jG.prototype),fx(jG.prototype,"updateRemoteRTPCapabilities",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"updateRemoteRTPCapabilities"),jG.prototype),fx(jG.prototype,"publishDataChannel",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"publishDataChannel"),jG.prototype),fx(jG.prototype,"unpublish",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unpublish"),jG.prototype),fx(jG.prototype,"unpublishDataChannel",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unpublishDataChannel"),jG.prototype),fx(jG.prototype,"unpublishLowStream",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unpublishLowStream"),jG.prototype),fx(jG.prototype,"subscribeDataChannel",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"subscribeDataChannel"),jG.prototype),fx(jG.prototype,"subscribe",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"subscribe"),jG.prototype),fx(jG.prototype,"massSubscribe",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"massSubscribe"),jG.prototype),fx(jG.prototype,"unsubscribe",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unsubscribe"),jG.prototype),fx(jG.prototype,"unsubscribeDataChannel",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unsubscribeDataChannel"),jG.prototype),fx(jG.prototype,"massUnsubscribe",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"massUnsubscribe"),jG.prototype),fx(jG.prototype,"muteRemote",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"muteRemote"),jG.prototype),fx(jG.prototype,"unmuteRemote",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"unmuteRemote"),jG.prototype),fx(jG.prototype,"hasRemoteMediaWithLock",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"hasRemoteMediaWithLock"),jG.prototype),fx(jG.prototype,"disconnectForReconnect",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"disconnectForReconnect"),jG.prototype),fx(jG.prototype,"updateBitrateLimit",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"updateBitrateLimit"),jG.prototype),fx(jG.prototype,"remoteMediaSsrcChanged",[qG],Object.getOwnPropertyDescriptor(jG.prototype,"remoteMediaSsrcChanged"),jG.prototype),jG);function qG(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function JG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function zG(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?JG(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):JG(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const XG=Date.now(),QG=20,$G=new Map,ZG=new Map;async function eW(e){const t=$G.get(e),i=Array.isArray(t)&&t[t.length-1],n=ZG.get(e);if(!i)return void(n.isSyncing=!1);const r={uid:i.uid,payload:i.payload};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const o=i.sendTs-n.firstSendTs,s=o-(Date.now()-n.firstRecvTs);s>0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(t.pop(),tW(i.context,r),a=0):a=Math.min(a,QG),setTimeout((()=>t.length&&eW(e)),a)}function tW(e,t){e.safeEmit(sD.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function iW(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return tW(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=$G.get(n)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=zG(zG({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),$G.set(n,r);let a=!1;var c;ZG.has(n)?a=!(null===(c=ZG.get(n))||void 0===c||!c.isSyncing):ZG.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||eW(n)}const nW=Jw().name;async function rW(){}var oW,sW,aW,cW,dW,lW,uW,hW,pW,_W,EW,fW,mW,SW,gW,TW,RW,vW,CW,IW,yW,AW,bW,OW,wW,NW,DW,PW,LW,kW,MW,UW,VW,xW,FW,BW,jW,GW,WW,HW,KW,YW,qW;function JW(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function zW(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?JW(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):JW(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}JD.setLogger(gL);let XW=(oW=KL(),sW=KL({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof qk))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),aW=KL({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==Ak.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),cW=KL({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),dW=KL({argsMap:(e,t,i)=>[t,i]}),lW=KL({argsMap:(e,t)=>t.map((e=>{let t=e.user,i=e.mediaType;return[null==t?void 0:t.uid,i]}))}),uW=KL({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),hW=KL({argsMap:(e,t)=>t.map((e=>{let t=e.user,i=e.mediaType;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),pW=KL(),_W=KL(),EW=KL(),fW=KL(),mW=KL(),SW=KL(),gW=KL(),TW=KL(),RW=KL(),vW=KL(),CW=KL(),IW=KL(),yW=KL(),AW=KL(),bW=KL(),OW=KL(),wW=KL({argsMap:(e,t)=>[t]}),NW=KL(),DW=KL(),PW=KL(),LW=KL(),kW=KL(),MW=KL(),UW=KL(),VW=KL(),xW=KL({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),FW=KL(),BW=KL(),jW=KL(),GW=KL(),WW=KL(),HW=KL(),KW=KL({reportResult:!0}),YW=KL(),qW=class extends JN{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){super(),Zb(this,"store",void 0),Zb(this,"_uid",void 0),Zb(this,"_channelName",void 0),Zb(this,"_uintUid",void 0),Zb(this,"_users",[]),Zb(this,"_config",void 0),Zb(this,"_clientId",void 0),Zb(this,"_appId",void 0),Zb(this,"_sessionId",null),Zb(this,"_key",void 0),Zb(this,"_rtmConfig",{}),Zb(this,"_joinInfo",void 0),Zb(this,"_gateway",void 0),Zb(this,"_statsCollector",void 0),Zb(this,"_configDistribute",void 0),Zb(this,"_leaveMutex",void 0),Zb(this,"_publishMutex",void 0),Zb(this,"_renewTokenMutex",void 0),Zb(this,"_subscribeMutex",void 0),Zb(this,"_decodeRecoveryState",new Map),Zb(this,"_encryptionMode","none"),Zb(this,"_encryptionSecret",null),Zb(this,"_encryptionSalt",null),Zb(this,"_encryptDataStream",!1),Zb(this,"_encryptDataStreamKey",null),Zb(this,"_encryptDataStreamIv",null),Zb(this,"_proxyServer",void 0),Zb(this,"_turnServer",{servers:[],mode:"auto"}),Zb(this,"_cloudProxyServerMode","disabled"),Zb(this,"_isDualStreamEnabled",!1),Zb(this,"_defaultStreamFallbackType",void 0),Zb(this,"_lowStreamParameter",void 0),Zb(this,"_streamFallbackTypeCacheMap",new Map),Zb(this,"_remoteStreamTypeCacheMap",new Map),Zb(this,"_axiosCancelSource",Vw.CancelToken.source()),Zb(this,"_audioVolumeIndicationInterval",void 0),Zb(this,"_networkQualityInterval",void 0),Zb(this,"_userOfflineTimeout",void 0),Zb(this,"_streamRemovedTimeout",void 0),Zb(this,"_rteDetailInterval",void 0),Zb(this,"_liveTranscodeStreamingClient",void 0),Zb(this,"_liveRawStreamingClient",void 0),Zb(this,"_channelMediaRelayClient",void 0),Zb(this,"_networkQualitySensitivity","normal"),Zb(this,"_p2pChannel",void 0),Zb(this,"_useLocalAccessPoint",!1),Zb(this,"_setLocalAPVersion",void 0),Zb(this,"_joinAndNotLeaveYet",!1),Zb(this,"_numberOfJoinCount",0),Zb(this,"_joinResponse",null),Zb(this,"_earlyJoinAttempt",void 0),Zb(this,"_remoteDefaultVideoStreamType",void 0),Zb(this,"_inspect",void 0),Zb(this,"_moderation",void 0),Zb(this,"_license",void 0),Zb(this,"_pendingPublishedUsers",[]),Zb(this,"ntpAlignErrorCount",0),Zb(this,"remoteInboundOffset",0),Zb(this,"_peerConnectionState",void 0),Zb(this,"_pendingRtpCapabilityChange",void 0),Zb(this,"_fallbackServerInfo",void 0),Zb(this,"_dualStreamMode",void 0),Zb(this,"_handleLocalTrackEnable",((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),Zb(this,"_handleLocalTrackDisable",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),Zb(this,"_handleUserOnline",(e=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(e.uid,this.channelName))return void gL.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&gL.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(sD.USER_JOINED,t));else{const t=new Pj(e.uid,e.uint_id||e.uid);this._users.push(t),gL.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(sD.USER_JOINED,t)}})),Zb(this,"_handleUserOffline",(e=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(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:RD(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),gL.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(sD.USER_LEAVED,t,e.reason))})),Zb(this,"_handleAddAudioOrVideoStream",((e,t,i,n,r,o,s,a)=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void gL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));gL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=o||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==i&&(c._audioSSRC=i),void 0!==n&&(c._cname=n),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==i&&(c._videoSSRC=i),void 0!==n&&(c._cname=n),void 0!==a&&(c._rtxSsrcId=a),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(gL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(sD.USER_PUBLISHED,c,e)),"video"===e?YL.onGatewayStream(this._sessionId,yL.ON_ADD_VIDEO_STREAM,AL.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):YL.onGatewayStream(this._sessionId,yL.ON_ADD_AUDIO_STREAM,AL.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,i).then((t=>{if(t&&(gL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof YG))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{gL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(gL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{gL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(r);"video"===e&&("unknown"===l?this.safeEmit(sD.AV1_DECODABLE_RESULT,!1):tN()||oN()||(null==l?void 0:l.toLocaleLowerCase())!==jP.av1||dj().then((e=>{VP("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(sD.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))})),Zb(this,"_handleRemoveStream",(e=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void gL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));gL.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{gL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(sD.USER_UNPUBLISHED,t,"audio"),gL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(sD.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{gL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(sD.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{gL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(sD.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 YG&&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),YL.onGatewayStream(this._sessionId,yL.ON_REMOVE_STREAM,AL.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()})),Zb(this,"_handleSetStreamLocalEnable",((e,t,i)=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void gL.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));gL.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";gL.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(sD.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";gL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(sD.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(gL.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(sD.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),gL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(sD.USER_UNPUBLISHED,n,e)):void 0})),Zb(this,"_handleMuteStream",((e,t,i)=>{if(VP("BLOCK_LOCAL_CLIENT")&&$V(e,this.channelName))return;gL.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void gL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{this.store.aiClientMode&&(i?DB.mute():DB.unmute());const t=n._audio_muted_?"mute-audio":"unmute-audio";gL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(sD.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";gL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(sD.USER_INFO_UPDATED,e,t)}}const o="audio"===t?n.hasAudio:n.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?n._audioSSRC:n._videoSSRC)?(gL.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(sD.USER_PUBLISHED,n,t)):void gL.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message  before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),gL.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(sD.USER_UNPUBLISHED,n,t)}})),Zb(this,"_handleP2PLost",(async e=>{gL.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?this._gateway.reconnect("tryNext"):await this._p2pChannel.requestReconnect():gL.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),Zb(this,"_handleTokenWillExpire",(()=>{gL.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(sD.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),Zb(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),gL.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),Zb(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(sD.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(sD.NETWORK_QUALITY,e)})),Zb(this,"_handleP2PAddAudioOrVideoStream",((e,t,i,n)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void gL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));gL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const o="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._audioMid=n)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._videoMid=n)),("audio"===e?r.hasAudio:r.hasVideo)&&!o&&(gL.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(sD.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(gL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{gL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||MD(5,"client-"),this.store=new class{constructor(e,t,i,n,r){ON(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,mediaDcId:555,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:wP.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,autoReceiveAndPlayAudio:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!r,aiClientMode:!1,preSubOptions:void 0,flexiblePC:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case BP.SET_SESSION_ID:return NN(NN({},e),{},{sessionId:t.sessionId});case BP.SET_P2P_ID:return NN(NN({},e),{},{p2pId:t.p2pId});case BP.SET_UID:return NN(NN({},e),{},{uid:t.uid});case BP.SET_INT_UID:return NN(NN({},e),{},{intUid:t.intUid});case BP.SET_PUB_ID:return NN(NN({},e),{},{pubId:t.pubId});case BP.KEY_METRIC_CLIENT_CREATED:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{clientCreated:t.metric})});case BP.KEY_METRIC_JOIN_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinStart:t.metric})});case BP.KEY_METRIC_PRELOAD_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{preloadStart:t.metric})});case BP.KEY_METRIC_PRELOAD_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{preloadEnd:t.metric})});case BP.KEY_METRIC_JOIN_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinEnd:t.metric})});case BP.KEY_METRIC_REQUEST_AP_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{requestAPStart:t.metric})});case BP.KEY_METRIC_REQUEST_AP_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{requestAPEnd:t.metric})});case BP.KEY_METRIC_REQUEST_SUA_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case BP.KEY_METRIC_BEFORE_CONNECT:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{beforeConnect:t.metric})});case BP.KEY_METRIC_PEER_RECEIVER:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{peerReceiver:t.metric})});case BP.KEY_METRIC_SIGNAL_CONNECTED:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{signalConnected:t.metric})});case BP.KEY_METRIC_JOIN_REQ:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinReq:t.metric})});case BP.KEY_METRIC_JOIN_REP:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinRep:t.metric})});case BP.KEY_METRIC_JOIN_GATEWAY_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case BP.KEY_METRIC_JOIN_GATEWAY_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case BP.KEY_METRIC_PEER_CONNECTION_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case BP.KEY_METRIC_PEER_CONNECTION_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case BP.KEY_METRIC_DESCRIPTION_START:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{descriptionStart:t.metric})});case BP.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case BP.KEY_METRIC_ICE_CONNECTION_END:return NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case BP.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=NN(NN({},i[n]),t.metric),NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{publish:[...i]})})):NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case BP.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==n?(i[n]=NN(NN({},i[n]),t.metric),NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{subscribe:[...i]})})):NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case BP.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const i=e.keyMetrics.firstVideoFrameDecoded,n=i.findIndex((e=>e.userId===t.metric.userId));return-1!==n?(i[n]=NN(NN({},i[n]),t.metric),NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...i]})})):NN(NN({},e),{},{keyMetrics:NN(NN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case BP.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case BP.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case BP.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=NN(NN({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case BP.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case BP.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case BP.SET_USE_P2P:return NN(NN({},e),{},{useP2P:t.val});case BP.SET_TRANSPORT_TYPE:return NN(NN({},e),{},{p2pTransport:t.val});case BP.SET_RTE_URL:return NN(NN({},e),{},{rteUrl:t.rteUrl});case BP.SET_RTE_SID:return NN(NN({},e),{},{rteSid:t.rteSid});default:return e}}(this.state,e)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(e){this.state.useDcSignal=e}get aiClientMode(){return this.state.aiClientMode}set aiClientMode(e){this.state.aiClientMode=e}set autoSubscribe(e){this.state.autoSubscribe=e}get autoSubscribe(){return this.state.autoSubscribe}set autoReceiveAndPlayAudio(e){this.state.autoReceiveAndPlayAudio=e}get autoReceiveAndPlayAudio(){return this.state.autoReceiveAndPlayAudio}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:BP.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:BP.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:BP.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:BP.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:BP.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set mediaDcId(e){this.state.mediaDcId=e}get mediaDcId(){return this.state.mediaDcId}set uid(e){this.dispatch({type:BP.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:BP.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:BP.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:BP.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:BP.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:BP.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 flexiblePC(e){this.state.flexiblePC=e}get flexiblePC(){return this.state.flexiblePC}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:BP.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:BP.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:BP.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:BP.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:BP.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:BP.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:BP.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:BP.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:BP.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:BP.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:BP.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:BP.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:BP.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:BP.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:BP.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:BP.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:BP.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:BP.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:NN({userId:e},t)})}descriptionStart(){this.dispatch({type:BP.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:BP.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:BP.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:BP.KEY_METRIC_PUBLISH,metric:NN(NN({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:BP.KEY_METRIC_SUBSCRIBE,metric:NN(NN(NN(NN(NN({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,i,n){e.forEach((e=>{this.dispatch({type:BP.KEY_METRIC_SUBSCRIBE,metric:NN(NN(NN({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:BP.RECORD_JOIN_CHANNEL_SERVICE,record:NN(NN({},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:BP.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:BP.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:BP.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:BP.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===VP("SIGNAL_CHANNEL")&&OB("DataChannelConnection"));const i=!CN()&&!rN();let n;if(!i&&e.aiClientMode&&gL.warning("[".concat(t,"] aiClientMode is only supported on desktop Chrome, Safari, and Edge. ")+"falling back to WebRTC audio reception."),this.store.aiClientMode=i&&!!e.aiClientMode&&OB("AiAudioModeExtension"),this._leaveMutex=new JD("client-leave",this._clientId),this._publishMutex=new JD("client-publish",this._clientId),this._renewTokenMutex=new JD("client-renewtoken",this._clientId),this._subscribeMutex=new JD("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),gL.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(bP," build: ").concat(LP,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{oD(e.clientRoleOptions),n=Object.assign({},e.clientRoleOptions)}catch(e){gL.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var r;this._statsCollector=new wj(this.store),this._statsCollector.onStatsException=(e,t,i)=>{gL.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),e===yj.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof AV&&VP("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),e===yj.RECV_VIDEO_DECODE_FAILED&&VP("ENABLE_DECODE_RECOVERY")&&this._tryDecodeRecovery(i),e===yj.RECV_VIDEO_DECODE_FAILED+2e3&&this._decodeRecoveryState.delete(i),this.safeEmit(sD.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));if(r){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(r.uid,{peerPublishDuration:i,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(r)),YL.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(VP("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof yV));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?VP("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new UB(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||XD,httpRetryConfig:e.httpRetryConfig||XD,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:n}),this._configDistribute=new Cj(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(r={store:this.store,statsCollector:this._statsCollector},bB("P2PChannel").create(r)),this._handleP2PEvents()):this._p2pChannel=new YG(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,r){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];UP("JOIN_GATEWAY_USE_443PORT_ONLY",o),UP("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof IF&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,i){Bw.get(e)||Bw.set(e,[]),jw.get(e)||jw.set(e,t),Gw.get(e)||Gw.set(e,0);const n=Bw.get(e),r=jw.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(Gw.get(e)===r){const e=Fw();n.push(e),await e.promise}Gw.set(e,Gw.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a<o;a++)s[a-3]=arguments[a];const c=await i(...s);return Gw.set(e,Gw.get(e)-1),Gw.get(e)===r-1&&n.length>0&&(n[0].resolve(),n.shift()),0===Gw.get(e)&&(Bw.set(e,[]),jw.set(e,0),Gw.set(e,0)),c}("client.join",VP("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r)}async join(e,t,i,n,r){gL.scheduleUploadStart();const o=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const s="HTTPS"===(ZD||ZD||(ZD=(window.location.protocol.split(":")[0]||"").toUpperCase(),ZD)),a=rP()?window.isSecureContext:"Browser Not Support";if(!rP()&&!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";gL.warning(e)}let c;YL.setAppId(e);try{if(!i&&null!==i)throw new qL(PN.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));if(i&&xN(i,"token",1,2047),xN(e,"appid",1,2047),wx(t),n&&Nx(n),r)if("string"==typeof r)xN(r,"optionalInfo",1,256),c=r;else{if("object"!=typeof r)throw new qL(PN.INVALID_PARAMS,"Invalid options: options is not a string or object");{const e=r.autoSubscribe,t=r.enableInstantMuteRestore,i=r.networkQualityProbe,n=r.preSubOptions,o=r.autoReceiveAndPlayAudio;void 0!==e&&(kN(e,"autoSubscribe"),gL.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),void 0!==o&&(kN(o,"autoReceiveAndPlayAudio"),gL.info("[".concat(this._clientId,"] join: autoReceiveAndPlayAudio: ").concat(o)),o&&(this.store.autoSubscribe=!0,this.store.autoReceiveAndPlayAudio=!0)),t&&(kN(t,"enableInstantMuteRestore"),gL.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),i&&(kN(i,"networkQualityProbe"),gL.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(i)),this.store.networkQualityProbe=i),Array.isArray(n)&&(FN(n,"preSubOptions"),n.forEach((e=>{Nx(e.uid),function(e,t){if("string"!=typeof e&&!(e instanceof HTMLElement||e instanceof HTMLVideoElement))throw new LN(PN.INVALID_PARAMS,"".concat(t," should be a string or a HTML element"))}(e.element,"element")})),gL.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(n.map((e=>"".concat(e.uid,": ").concat("string"==typeof e.element?e.element:e.element.id))).join(","))),this.store.preSubOptions=n),this.store.aiClientMode&&this.store.autoSubscribe&&(gL.info("[".concat(this._clientId,"] join: enable AIQoS preload playback for aiClientMode + autoSubscribe")),this.store.autoReceiveAndPlayAudio=!0)}}}catch(r){throw YL.reportApiInvoke(UD(),{clientId:this._clientId,name:QN.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:$N.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){gL.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),gL.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw YL.reportApiInvoke(UD(),{clientId:this._clientId,name:QN.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:$N.TRACER}).onError(r),r}const d=(this._clientId,mj);try{this._gateway.state="CONNECTING",this.store.preloadStart();const r=await rW(this._cloudProxyServerMode);if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const p=(null==r?void 0:r.sid)||UD();gL.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=p,this.store.sessionId=this._sessionId);const _=YL.reportApiInvoke(this._sessionId,{id:this._clientId,clientId:this._clientId,name:QN.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:$N.TRACER}),E=zW(zW(zW({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!r},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:VP("AP_REQUEST_DETAIL")||void 0,apRequestDetailExtend:VP("AP_REQUEST_DETAIL_EXTEND")});if(this._useLocalAccessPoint&&(E.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(E.stringUid=n,this._uintUid?(E.uid=this._uintUid,this._uintUid=void 0):E.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(E.aesmode=this._encryptionMode,E.aespassword=await(async e=>{const t=function(e){const t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}(),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=KN(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return function(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(E.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=VP("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(E.appId+this._encryptionSecret+this._encryptionSecret):e.encode(E.appId+E.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,o=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:HP,hash:"SHA-256",salt:i},n,r+WP);return new Uint8Array(o).subarray(r/8)}(this._encryptionMode,t,OD(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:HP,hash:"SHA-256",salt:i},n,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"])}(this._encryptionMode,t,OD(this._encryptionSalt))}else a?gL.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):gL.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,gL.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:E.stringUid});const f=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&f===this._sessionId&&YL.joinChannelTimeout(this._sessionId,5)}),5e3);try{var l;let n;const o=E.cloudProxyServer;if(Un(l=["proxy3","proxy4","proxy5"]).call(l,o)){const e=VP("PROXY_SERVER_TYPE3");Array.isArray(e)?E.proxyServer=e[0]:E.proxyServer=e}YL.setProxyServer(E.proxyServer),gL.setProxyServer(E.proxyServer),this.store.requestAPStart(),this.store.flexiblePC=!!VP("FLEXIBLE_PC");if(n);else if(r){if(gL.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(E.stringUid?", ".concat(E.stringUid," => ").concat(r.intUid):""," ")),E.stringUid&&!E.uid&&(E.uid=r.intUid),n={gatewayInfo:r.ap.gatewayInfo},VP("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===E.turnServer.mode)if(0===r.ap.proxyInfo.addresses.length)gL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await WF(r.ap.proxyInfo,r.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||NP.tcpport,udpport:e.udpport||NP.udpport,username:e.username||NP.username,password:e.password||NP.password,forceturn:!1,security:!0})));E.turnServer={mode:"manual",servers:e}}E.stringUid}else if(E.stringUid&&!E.uid){let e;var u=HI(await cp.all([hj(E.stringUid,E,this._axiosCancelSource.token,this._config.httpRetryConfig||XD,this.store).finally((()=>{this.store.requestSUAEnd()})),uj(E,this._axiosCancelSource.token,this._config.httpRetryConfig||XD,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),2);e=u[0],n=u[1],gL.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(E.stringUid," => ").concat(e)),E.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await uj(E,this._axiosCancelSource.token,this._config.httpRetryConfig||XD,!0,this.store);if(!this._joinAndNotLeaveYet)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(E,this._axiosCancelSource.token),this._configDistribute.on(Kx.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(Kx.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(Kx.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{var t;Un(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(Kx.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(sD.FALLBACK_TO_HLS,aD.CONFIG)})),this._configDistribute.on(Kx.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{gL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=i||e;const s=n.gatewayInfo,a=E.uid?E.uid:s.uid;this._joinInfo=zW(zW({},E),{},{cid:s.cid,uid:a,vid:s.vid,apResponse:s.res,apGatewayAddress:s.apGatewayAddress,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs}),this.store.intUid=a,this.store.cid=s.cid;this._joinInfo.apResponse.signalResponse,this._joinInfo.apResponse.addresses[0];const c=qF;this._earlyJoinAttempt=c?void E.role:void 0,this._earlyJoinAttempt?this._joinResponse=this._earlyJoinAttempt.preJoinResponse:this.store.flexiblePC=!!VP("FLEXIBLE_PC");const p=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));_.onSuccess(p),this._appId=e,this._channelName=E.cname,this._uid=p,this.store.uid=p,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!tN()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(tN()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const f=E.stringUid?"string uid: ".concat(E.stringUid,",uid: ").concat(E.uid):"uid: ".concat(this._uid);return gL.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(f)),this.store.joinEnd(),h=this,Un(XV).call(XV,h)||XV.push(h),"disabled"===this._cloudProxyServerMode&&zL().supportWebCrypto&&VP("ENABLE_PRELOAD")&&this._joinInfo,this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&YL.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&YL.reportRteDetail(this._sessionId)}),VP("RTE_DETAIL_REPORT_INTERVAL")||6e4),d.markJoined(),p}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===PN.OPERATION_ABORTED?gL.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):gL.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==PN.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),_.onError(t),t}}finally{}var h}async _joinGateway(){if(!this._joinInfo||!this._key)throw new qL(PN.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key)}catch(e){if(e.code===PN.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,tD.FALLBACK),gL.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new qL(PN.INVALID_OPERATION);return YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:$N.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){gL.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!tN()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(tN()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=XV.indexOf(e);-1!==t&&XV.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return gL.info("[".concat(this._clientId,"] Leaving channel repeated, success")),t(),void gj(this._clientId);await this._gateway.leave("CONNECTED"!==this.connectionState,tD.LEAVE),gL.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e(),gj(this._clientId)}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof qk))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new qL(PN.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new qL(PN.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof qk))throw new qL(PN.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new qL(PN.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}gL.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof yV&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),gL.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw gL.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{n()}}async _publishDataChannel(e){if(null==e)throw new qL(PN.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));UN(e.id,"id",0,65535,!0),kN(e.ordered,"ordered"),xN(e.metadata,"metadata",0,512),gL.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 qL(PN.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 qL(PN.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&VP("FORCE_TURN")&&!VP("TURN_ENABLE_TCP")&&!VP("TURN_ENABLE_UDP"))throw new qL(PN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return wB(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw gL.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new qL(PN.CREATE_DATACHANNEL_ERROR);try{await cp.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==PN.DISCONNECT_P2P)throw e}}return gL.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw gL.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new qL(PN.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof qk))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);gL.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(aF.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),gL.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw gL.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),gL.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&await this._gateway.unpublishDataChannel(i),gL.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw gL.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof Pj)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(MN(t,"mediaType",["audio","video"]),this.store.useP2P)throw new qL(PN.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===zx.AUDIO,n=t===zx.VIDEO,r=await this._subscribeMutex.lock();try{const o=await this._gateway.presubscribe(e,t,!0),s=o.ssrcId,a=o.ortc,c=o.rtxSsrcId,d=o.cname,l=o.uint_id;if(null==s)throw new qL(PN.UNEXPECTED_RESPONSE,"no ssrc id");let u=this._users.find((t=>t.uid===e));u||(u=new Pj(e,l||e),u._is_pre_created=!0,this._users.push(u)),d&&(u._cname=d),u._uintid||(u._uintid=l||e),i&&(u._audioSSRC=s,u._audio_pre_subscribed=!0,a&&(u._audioOrtc=a)),n&&(u._videoSSRC=s,u._video_pre_subscribed=!0,a&&(u._videoOrtc=a),null!=c&&(u._rtxSsrcId=c)),gL.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(s)),await this._p2pChannel.subscribe(u,t,s,c,a);const h=i?u._audioTrack:u._videoTrack;if(!h)throw new qL(PN.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(u._trust_audio_stream_added_state_=!0,u._audio_added_=!0),n&&(u._trust_video_stream_added_state_=!0,u._video_added_=!0),h}catch(t){throw gL.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var i;if(UN(t,"channelId",0,65535,!0),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n)throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new qL(PN.INVALID_REMOTE_USER,"user is not published");const r=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!r)throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new qL(PN.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();gL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Un(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new qL(PN.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)!==PN.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return gL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,i){if(MN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");throw gL.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 qL(PN.INVALID_REMOTE_USER,"user is not published");throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new qL(PN.REMOTE_USER_IS_NOT_PUBLISHED);throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const r=await this._subscribeMutex.lock();gL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}gL.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=>{gL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new qL(PN.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw gL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}_tryDecodeRecovery(e){const t=this._decodeRecoveryState.get(e)||{attempts:0,inProgress:!1},i=VP("DECODE_RECOVERY_MAX_ATTEMPTS");if(t.attempts>=i||t.inProgress)return;t.inProgress=!0,t.attempts++,this._decodeRecoveryState.set(e,t);const n=VP("DECODE_RECOVERY_BASE_INTERVAL"),r=1===t.attempts?0:Math.min(n*Math.pow(2,t.attempts-2),6e4),o=async()=>{const n=this._users.find((t=>t.uid===e));if(n&&n.hasVideo&&"CONNECTED"===this.connectionState){if(this._decodeRecoveryState.has(e)){gL.info("[".concat(this._clientId,"] decode recovery attempt ").concat(t.attempts,"/").concat(i," for uid: ").concat(e));try{this._p2pChannel instanceof YG&&(await this._p2pChannel.unsubscribe(n,zx.VIDEO,!0),await this._gateway.tryUnsubBeforeResub(n.uid,{stream_type:zx.VIDEO,ssrcId:n._videoSSRC}).catch((e=>{gL.warning("[".concat(this._clientId,"] decode recovery gateway unsub failed, continue resub"),e.toString())})),await this._subscribe(n,"video",!0)),gL.info("[".concat(this._clientId,"] decode recovery resub success for uid: ").concat(e))}catch(t){gL.error("[".concat(this._clientId,"] decode recovery resub failed for uid: ").concat(e),t.toString())}finally{t.inProgress=!1}}}else t.inProgress=!1};0===r?o():setTimeout((()=>o()),r)}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(MN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");throw gL.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 qL(PN.INVALID_REMOTE_USER,"user is not published");throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new qL(PN.REMOTE_USER_IS_NOT_PUBLISHED);throw gL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let r="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?zx.AUDIO:zx.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const c=await this._subscribeMutex.lock();gL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==r&&(r=i,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?zx.AUDIO:zx.VIDEO,ssrcId:r}),Aj.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,s,o);try{this._p2pChannel.isPreSubScribe(r)||await this._gateway.subscribe(e.uid,a,!0)}catch(i){if((null==i?void 0:i.code)!==PN.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}gL.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=>{gL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(this.store.aiClientMode&&"audio"===t&&i&&(i.play=()=>{DB.play()},i.stop=()=>{DB.stop()}),!i)throw new qL(PN.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),i}catch(t){throw gL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(FN(e,"subscribeList"),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();gL.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const r=(e=[...e]).map((e=>({user:e.user,mediaType:e.mediaType}))),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const n=e[t],o=n.user,s=n.mediaType;if(MN(s,"mediaType",["audio","video"]),!o){const e=new qL(PN.INVALID_PARAMS,"user property does not exist in subscribeList item");throw gL.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}const a=this._users.find((e=>e===o));if(!a){const i=new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");gL.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const i=new qL(PN.REMOTE_USER_IS_NOT_PUBLISHED);gL.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=i,e.splice(t,1);continue}const c=Bx.Video|Bx.LowVideo,d=i.get(o);if(d){if("video"===s?d&c:d&Bx.Audio){e.splice(t,1),gL.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,d|("video"===s?c:Bx.Audio))}else i.set(o,"video"===s?c:Bx.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.user,o=n.mediaType,s=Bx.Video|Bx.LowVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const n=i.get(r);i.set(r,"video"===o?n^s:n^Bx.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=sr(s=Array.from(i.entries())).call(s,((e,t)=>{let i=HI(t,2),n=i[0],r=i[1];if(0===r)return e;const o={stream_id:n.uid,stream_type:r};return r&Bx.Audio&&(o.audio_ssrc=n._audioSSRC),r&Bx.Video&&(o.video_ssrc=n._videoSSRC),e.push(o),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let t=e.user,i=e.mediaType;return{user:t,mediaType:i,ssrcId:i===zx.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===zx.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let t=e.stream_id,n=e.video_error_code,r=e.audio_error_code,o=e.error_code;(n||r||o)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:o})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let i=HI(t,2),n=i[0],r=i[1];const o=this.remoteUsers.find((e=>e.uid===n));if(o){let t;r.error_code||r.video_error_code&&r.audio_error_code?t=void 0:r.video_error_code?t=zx.VIDEO:r.audio_error_code&&(t=zx.AUDIO),e.push({user:o,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=hF(i);gL.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new qL(PN.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var i;YL.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===zx.VIDEO,audio:e.mediaType===zx.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===zx.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)})),gL.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),n()}}async unsubscribe(e,t,i){if(!(e instanceof Pj)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&MN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");throw gL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}gL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const r=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&RD(this._users,e),gL.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===PN.DISCONNECT_P2P)return void gL.warning("disconnecting p2p, abort unsubscribe request.");throw gL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&UN(t,"id",0,65535,!0),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new qL(PN.INVALID_REMOTE_USER,"user is not in the channel");throw gL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let n;if("number"==typeof t){const i=e._dataChannels.find((e=>e.id===t));i&&(n=[i])}else n=e._dataChannels;if(void 0===n){const i=new qL(PN.REMOTE_USER_IS_NOT_PUBLISHED);throw gL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}gL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(n.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,n);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),gL.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===PN.DISCONNECT_P2P)return void gL.warning("disconnecting p2p, abort unsubscribe request.");throw gL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(FN(e,"unsubscribeList"),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");gL.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const n=e[i],r=n.user,o=n.mediaType;if(!r){const e=new qL(PN.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw gL.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}MN(o,"mediaType",["video","audio",void 0]);const s=this._users.find((e=>e===r));if(!s){gL.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(r.uid,", user is not in the channel")),e.splice(i,1);continue}const a=Bx.Video|Bx.LowVideo;if(t.has(r)){const n=t.get(r);let s;switch(o){case"video":s=n&a;break;case"audio":s=n&Bx.Audio;break;default:s=n&(Bx.Audio|a)}if(s){gL.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(r.uid,",mediaType:").concat(o," twice.")),e.splice(i,1);continue}o?"audio"===o?t.set(r,n|Bx.Audio):"video"===o&&t.set(r,n|a):t.set(r,n|Bx.Audio|a)}else o?"audio"===o?t.set(r,Bx.Audio):"video"===o&&t.set(r,a):t.set(r,Bx.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),gL.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===PN.DISCONNECT_P2P)return void gL.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw gL.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new LN(PN.INVALID_PARAMS);BN(e.width)||VN(e.width,"streamParameter.width"),BN(e.height)||VN(e.height,"streamParameter.height"),BN(e.framerate)||VN(e.framerate,"streamParameter.framerate"),BN(e.bitrate)||UN(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&gL.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),gL.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,Zx.LocalVideoLowTrack)}async setDualStreamMode(e,t){MN(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{gL.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):gL.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case rD.AUTO_SIMULCAST_STREAM:gL.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case rD.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case rD.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw gL.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!zL().supportDualStream)throw YL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new qL(PN.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new qL(PN.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw YL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=rD.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{gL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),YL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),gL.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void gL.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(Zx.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw YL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=rD.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{gL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),YL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),gL.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){MN(e,"role",["audience","host"])}(e),t&&oD(t),"rtc"===this.mode||"p2p"===this.mode)throw gL.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new qL(PN.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new qL(PN.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new qL(PN.INVALID_OPERATION,"can not set client role to audience when publishing stream");const i=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==i&&VP("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",cD.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),gL.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===i&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof YG){const e=this._pendingRtpCapabilityChange.video_codec;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>{var t;return Un(t=Object.keys(jP)).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&&oD(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{gL.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(xN(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new qL(PN.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,YL.setProxyServer(this._proxyServer),gL.setProxyServer(this._proxyServer),gL.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 qL(PN.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new qL(PN.INVALID_OPERATION,"You have already set the proxy")}if(iD(e))return this._turnServer={servers:e,mode:"original-manual"},void gL.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>nD(e))),this._turnServer={servers:e,mode:"manual"},gL.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new qL(PN.INVALID_OPERATION,"you should set license before join channel")}if(xN(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new qL(PN.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,gL.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new qL(PN.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new qL(PN.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new qL(PN.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,gL.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"Stop proxy server after leave channel");YL.setProxyServer(),gL.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",gL.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 qL(PN.INVALID_PARAMS,"accessPoints is required.");FN(e.accessPoints.serverList,"accessPoints.serverList"),xN(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{UN(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new qL(PN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");VP("CLOSE_AFB_FOR_LOCAL_AP")&&(UP("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),UP("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),s=o.map((e=>"".concat(e,":").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,UP("WEBCS_DOMAIN",s),UP("WEBCS_DOMAIN_BACKUP_LIST",s),UP("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(FN(e.report.hostname,"report.hostname"),UP("EVENT_REPORT_DOMAIN",e.report.hostname[0]),UP("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(UP("EVENT_REPORT_DOMAIN",o[0]),UP("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),UP("STATS_COLLECTOR_PORT",a),e.report?UP("ENABLE_EVENT_REPORT",!0):UP("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(FN(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),UP("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(FN(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),UP("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?UP("ENABLE_CONFIG_DISTRIBUTE",!0):UP("ENABLE_CONFIG_DISTRIBUTE",!1),gL.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(FN(e,"serverList"),xN(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new qL(PN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,UP("WEBCS_DOMAIN",e),UP("WEBCS_DOMAIN_BACKUP_LIST",e),UP("GATEWAY_DOMAINS",[t]),UP("EVENT_REPORT_DOMAIN",e[0]),UP("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),UP("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),gL.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(MN(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 gL.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else gL.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){MN(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 gL.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}gL.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){MN(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw gL.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}gL.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){!function(e){MN(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),xN(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Un(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new qL(PN.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new qL(PN.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(kN(n,"encryptDataStream"),!Un(r).call(r,e))throw new qL(PN.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||gL.warning("The secret is not strong:\n      The secret must contain at least 1 lowercase alphabetical character,\n      The secret must contain at least 1 uppercase alphabetical character,\n      The secret must contain at least 1 numeric character,\n      The secret must contain at least one special character,\n      The secret must be eight characters or longer.\n      "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=wD(i))}async renewToken(e){if(xN(e,"token",1,2047),!this._key||!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(VP("USE_NEW_TOKEN")){gL.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await Ej(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||XD);gL.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else gL.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});gL.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,gL.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?gL.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(sD.VOLUME_INDICATOR,e)}),VP("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 qL(PN.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new qL(PN.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 qL(PN.LIVE_STREAMING_TASK_CONFLICT);const i=t?Dx.TRANSCODE:Dx.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(Dx.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new qL(PN.INVALID_PARAMS,"can not find live streaming url to stop");await cp.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){Dj(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){Dj(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 YG&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Un(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=sr(n=Array.from(i)).call(n,((e,t)=>e+t),0),o={serverTs:0,seq:YP++,length:i.length,checkSum:r},s=new Uint8Array(GD(r,2)),a=new ArrayBuffer(KP),c=new DataView(a);c.setUint32(0,o.serverTs),c.setUint16(4,o.seq),c.setUint16(6,o.length),c.setUint16(8,o.checkSum);const d=16-i.length%16;i=ND(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:GP,additionalData:s},t,i);return ND(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new qL(PN.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(Ix.DATA_STREAM,{payload:wD(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-XG},!i)}sendMetadata(e){if(!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new qL(PN.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(Ix.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:wD(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(RL),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"can not send custom report, not joined");await YL.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(VP("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((i=>{Un(t).call(t,i)||delete e[i]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){MN(t.spatialLayer,"spatialLayer",[0,1,2,3]),MN(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw gL.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const t=e.apRTM,i=void 0!==t&&t,n=e.rtmFlag;if(kN(i,"apRTM"),UN(n,"rtmFlag",0),this._rtmConfig.apRTM=i,this._rtmConfig.rtmFlag=n,gL.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=i,this._joinInfo.rtmFlag=n,this._gateway.setRTM2Flag(n)}_reset(){if(gL.debug("[".concat(this._clientId,"] reset client")),function(e){const t=QV.indexOf(e);-1!==t&&QV.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.flexiblePC=!1,this.store.autoSubscribe=!1,this.store.autoReceiveAndPlayAudio=!1,this._pendingRtpCapabilityChange=void 0,this._earlyJoinAttempt=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=Vw.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._decodeRecoveryState.clear(),this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&this._joinInfo,this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&YL.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&YL.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 JD("client-publish",this._clientId),this._subscribeMutex=new JD("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;const n=e||UD();e?gL.debug("[".concat(this._clientId,"] new Session ").concat(n)):gL.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,YL.addSid(n);const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:5,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};YL.sessionInit(this._sessionId,zW({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new qL(PN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&VP("FORCE_TURN")&&!VP("TURN_ENABLE_TCP")&&!VP("TURN_ENABLE_UDP"))throw new qL(PN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");gL.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(aF.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0)}catch(e){if(e.code!==PN.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof yV&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig,t._optimizationMode).catch((e=>{gL.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)===PN.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new qL(PN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));gL.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==PN.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===PN.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new qL(PN.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},bB("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.ON_LIVE_STREAM_ERROR,options:[e,t],tag:$N.TRACER}).onSuccess(),this.safeEmit(sD.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.ON_LIVE_STREAM_WARNING,options:[e,t],tag:$N.TRACER}).onSuccess(),this.safeEmit(sD.LIVE_STREAMING_WARNING,e,t)},e.on(Px.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new qL(PN.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const r=VP("UAP_AP").slice(0,VP("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 ZB(r,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,XD).then(t).catch(i)})),e};return e===Dx.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new qL(PN.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const t=this.getLocalVideoStats(),i=t.sendResolutionWidth,n=t.sendResolutionHeight,r=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:i,height:n}},bB("ChannelMediaRelay").create(e));r.on("state",(e=>{e===Mx.RELAY_STATE_FAILURE&&r&&r.dispose(),this.safeEmit(sD.CHANNEL_MEDIA_RELAY_STATE,e)})),r.on("event",(e=>{this.safeEmit(sD.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=r,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],i=[];this._users.forEach((n=>{const r=n._dataChannels;r.forEach((i=>{e.some((e=>e.uid===n._uintid&&e.stream_id===i.id&&e.metadata===i.metadata))||t.push({uid:n._uintid,stream_id:i.id,ordered:i.ordered,max_retrans_times:i.maxRetransmits,metadata:i.metadata})})),e.filter((e=>e.uid===n._uintid)).forEach((e=>{if(!r.some((t=>n._uintid===e.uid&&t.id===e.stream_id&&t.metadata===e.metadata))){const r=t.findIndex((t=>n._uintid===t.uid&&t.stream_id===e.stream_id));-1!==r&&(i.push(e),t.splice(r,1))}}))})),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(i),this._handleDataChannelAdded(e,!0),gL.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map((e=>e.stream_id)))),this.safeEmit(sD.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){const i=[];Array.isArray(e)&&e.length>0&&(gL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," added")),e.forEach((e=>{const n=e.uid,r=e.stream_id,o=e.ordered,s=e.max_retrans_times,a=e.metadata,c=this._users.find((e=>e._uintid===n));if(!c)return void gL.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));gL.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(n)),Un(i).call(i,c)||i.push(c),c._uintid||(c._uintid=n);if(-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id))){const t=c._dataChannels.find((t=>t.id===e.stream_id));null==t||t._updateDataChannelConfig(zW(zW({},null==t?void 0:t.getConfig()),{},{metadata:e.metadata}))}else{const e={id:r,ordered:!!o,maxRetransmits:s,metadata:a},i=function(e){return wB(e,!0)}(e);c._dataChannels.push(i),gL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(sD.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(gL.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=>{gL.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(gL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," updated")),e.forEach((e=>{var t;const i=e.uid,n=e.stream_id,r=e.metadata,o=this._users.find((e=>e._uintid===i));if(!o)return void gL.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const s=o._dataChannels.find((e=>e.id===n));gL.debug("[".concat(this._clientId,"] data_channel: ").concat(n," updated with uid ").concat(i,", last metadata: ").concat(null==s||null===(t=s._config)||void 0===t?void 0:t.metadata,", new metadata: ").concat(r)),this.safeEmit(sD.USER_UNPUBLISHED,o,"datachannel",null==s?void 0:s._config),this.safeEmit(sD.USER_PUBLISHED,o,"datachannel",{id:n,ordered:!!e.ordered,maxRetransmits:e.max_retrans_times,metadata:r})})))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(gL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," deleted")),e.forEach((e=>{const t=e.uid;e.stream_id;const i=this._users.find((e=>e._uintid===t));if(!i)return void gL.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const n=i._dataChannels.find((t=>t.id===e.stream_id));n&&(gL.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),i._dataChannels=i._dataChannels.filter((e=>e.id!==n.id)),this._p2pChannel.unsubscribeDataChannel(i,[n]).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,i.uid)})),gL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel , id:").concat(n.id)),this.safeEmit(sD.USER_UNPUBLISHED,i,"datachannel",n._config))})))}_handleUpdateDataChannel(e){const t=e.added,i=e.deleted;this._handleDataChannelDeleted(null!=i?i:[]),this._handleDataChannelAdded(null!=t?t:[])}_getEncodingName(e){var t,i;if(!this._joinResponse)return;const n=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!n)return;for(const t of n){var r;if(t.payloadType===e)return null==t||null===(r=t.rtpMap)||void 0===r?void 0:r.encodingName}const o=null===(i=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===i?void 0:i.videoCodecs;if(o)for(const t of o){var s;if(t.payloadType===e)return null==t||null===(s=t.rtpMap)||void 0===s?void 0:s.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){gL.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{gL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(sD.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else gL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(xx.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void gL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach((e=>{const n=t[e],r=n.value,o=n.type,s=n.expires;s&&s<=i||o||ZV()||!Object.prototype.hasOwnProperty.call(DP,e)||(FP[e]=r,MP[e]=r,gL.debug("Update gateway parameters from config distribute",e,r))}))}catch(e){gL.error("Error update config from local cache",e.message)}}()})),this._gateway.on(xx.DISCONNECT_P2P,(async()=>{this._earlyJoinAttempt=void 0,await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(xx.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===tD.FALLBACK)return;const r=()=>{this.safeEmit(sD.CONNECTION_STATE_CHANGE,e,t,i)};if(YL.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{clientId:this._clientId,name:QN.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:$N.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),gL.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=>{gL.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{gL.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),VP("VOS_CONFIGURE")&&Array.isArray(VP("VOS_CONFIGURE"))&&VP("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(VP("VOS_CONFIGURE")).catch((e=>{gL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),gL.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((()=>{gL.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{gL.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{gL.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=>{gL.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_||(gL.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,zx.AUDIO,!1)),e._trust_video_mute_state_||(gL.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,zx.VIDEO,!1)),e._trust_audio_enabled_state_||(gL.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(gL.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(gL.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(gL.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(gL.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(xx.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new qL(PN.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,YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:$N.TRACER}).onSuccess(),gL.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await rW(zW(zW({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,this._joinInfo.preload=!0):(t=await lj(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||XD,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,this._earlyJoinAttempt=void 0);const i=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{const t=HI(e.address.split(":"),2),n=t[0],r=t[1];this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r})})),e(i)}catch(e){t(e)}})),this._gateway.on(xx.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(sD.NETWORK_QUALITY,e)})),this._gateway.on(xx.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(sD.STREAM_TYPE_CHANGED,e,t);YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.STREAM_TYPE_CHANGE,options:[e,t],tag:$N.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(xx.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(xx.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?this._p2pChannel.updateConnectionConfiguration(e):i=await this._p2pChannel.startP2PConnection(e),t(i)}catch(e){i(e)}})),this._gateway.on(xx.JOIN_RESPONSE,((e,t)=>{var i;if(this.store.useP2P)return;let n;this._joinResponse=zW(zW(zW({},this._joinResponse),e),{},{ortc:e.ortc||(null===(i=this._joinResponse)||void 0===i?void 0:i.ortc)}),e.attributes?n=e.attributes.userAttributes.preSubSsrcs:gL.debug("no attributes in joinResponse");const r=rB(this._joinResponse.ortc,t,n),o=this._joinInfo;this._p2pChannel.connect(r).catch((e=>{if(this._joinInfo===o)throw e;gL.debug("[".concat(this._clientId,"] ignore P2P connect from a stale join"),e)}))})),this._gateway.on(xx.PRE_CONNECT_PC,(async(e,t,i)=>{const n=e.candidates,r=e.fingerprint,o=e.turnServer,s=e.rtpCapabilities,a=e.originalPreSubSsrcs;if(this._joinInfo&&n.length>0&&!this._p2pChannel.isPlanB){const d=this._joinInfo.apResponse,l=d.cert,u=d.cid,h="".concat(u,"_").concat(l),p=e.iceUfrag||h,_=e.icePwd||h;if(!PB(p,_))return gL.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(p.length," / ").concat(_.length)),void t();let E;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),gL.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),e.isSDPEndpoint&&this._p2pChannel instanceof YG&&this._p2pChannel.markSDPEndpointConnection(),Array.isArray(a)&&a.length>0&&(E=oB(a));try{var c;t(await this._p2pChannel.connect(zW({iceParameters:{iceUfrag:p,icePwd:_},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(c=VP("FINGERPRINT"))&&void 0!==c?c:r}]},candidates:n,rtpCapabilities:s?ID(s):{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},E?{preSSRCs:E}:{})))}catch(e){e.code&&e.code===PN.EXCHANGE_SDP_FAILED&&(gL.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)),i(e)}}})),this._gateway.on(xx.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(sD.FALLBACK_TO_HLS,aD.VOSERROR)})),this._gateway.on(xx.RESET_SIGNAL,(()=>{this._p2pChannel instanceof YG&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(xx.DATACHANNEL_FAILBACK,(()=>{YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.DATACHANNEL_FAILBACK,options:{},tag:$N.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(Ax.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(Ax.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(Ax.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(Ax.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(Ax.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(Ax.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{var t;this._handleFullDatachannel(null!==(t=e.datastreams)&&void 0!==t?t:[])})),this._gateway.signal.on(Ax.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(Ax.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(Ax.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,zx.AUDIO,!0))),this._gateway.signal.on(Ax.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,zx.AUDIO,!1))),this._gateway.signal.on(Ax.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,zx.VIDEO,!0))),this._gateway.signal.on(Ax.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,zx.VIDEO,!1))),this._gateway.signal.on(Ax.RECEIVE_METADATA,(e=>{const t=OD(e.metadata);this.safeEmit(sD.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(Ax.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let i=OD(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Un(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<KP)throw new qL(PN.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(KP));const t=await async function(e,t,i){const n=i.subarray(0,KP),r=n.slice(8,KP),o=(r[0]<<8)+r[1],s=(n[6]<<8)+n[7],a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:GP,additionalData:new Uint8Array(GD(o,2))},t,i.subarray(KP));return new Uint8Array(a).subarray(0,s)}(this._encryptDataStreamIv,this._encryptDataStreamKey,i);i=t}let n=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),i=this.remoteUsers.find((t=>t.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==i?void 0:i._audioSSRC)));n=null==r?void 0:r.jitterBufferMs}(null==n||Number.isNaN(n))&&(n=0),iW(zW(zW({},e),{},{payload:i}),n,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(Ax.ON_CRYPT_ERROR,(()=>{bD((()=>{gL.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(sD.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(Ax.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(Ax.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{gL.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,tD.TOKEN_EXPIRE),this.safeEmit(sD.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(Ax.ON_STREAM_FALLBACK_UPDATE,(e=>{gL.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(sD.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(Ax.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===rD.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{gL.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(Ax.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),gL.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(Ax.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(Ax.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(Cx.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case Ix.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some((e=>e.stream_type===Vx.Audio)),o=e.some((e=>e.stream_type!==Vx.Audio)),s=e.some((e=>{let t=e.stream_type;return t===Vx.Screen||t===Vx.ScreenLow}));"offer"===t.state&&YL.publish(this._joinInfo.sid,{eventElapse:Aj.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:PN.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(i=e.find((e=>e.stream_type===Vx.Audio)))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:o?null===(n=e.find((e=>e.stream_type!==Vx.Audio)))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case Ix.SUBSCRIBE:t&&YL.subscribe(this._joinInfo.sid,{succ:!1,ec:PN.TIMEOUT,audio:t.stream_type===zx.AUDIO,video:t.stream_type===zx.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:Aj.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(Ax.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(Ax.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;let t=e.users;VP("BLOCK_LOCAL_CLIENT")&&(t=t.filter((e=>!$V(e.string_id||e.stream_id,this.channelName)))),this._handleUserList(t)})),this._gateway.signal.on(Ax.ON_USER_LIST,(e=>{if(!e||!Array.isArray(e.users)||0===e.users.length)return;let t=e.users;t=VP("BLOCK_LOCAL_CLIENT")?t.filter((e=>!$V(e.string_id||e.stream_id,this.channelName))):t,this._handleUserList(t)})),this._gateway.signal.on(Ax.ON_RTP_CAPABILITY_CHANGE,(e=>{const t=e.video_codec;if(this._p2pChannel instanceof YG){if("audience"===this.role&&VP("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void gL.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 Un(t=Object.keys(jP)).call(t,e)})))}})),this._gateway.signal.on(Cx.VOS_FALLBACK_PROMISE,(async(e,t,i)=>{if("FALLBACKCN"===e&&VP("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return i(new qL(PN.UNEXPECTED_ERROR,"can not recover, no join info"));gL.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const n=await lj(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||XD,this.store);if(VP("QUALITY_FALLBACK_REHEARSAL"))return YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.VOS_FALLBACK_CN,options:{cur:n.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:$N.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void i();this._fallbackServerInfo=n,t()}catch(e){var n;const t=null==e||null===(n=e.data)||void 0===n?void 0:n.desc;VP("QUALITY_FALLBACK_REHEARSAL")?(YL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:QN.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:$N.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(t)&&Un(t).call(t,"request downgrade fallback")&&this.safeEmit(sD.FALLBACK_TO_HLS,aD.AP_ERROR),i(e)}}else i()}))}_handleUserList(e){var t=this;if(0===e.length)return;const i=[],n=[],r=[],o=[],s=[],a=[],c=this.getListeners(sD.USER_LIST).length>0,d=this.getListeners(sD.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 Pj(t.string_id||t.stream_id,t.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}));const d=Bx.Audio&t.stream_type,l=(Bx.Video|Bx.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)&&(n.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"}),i.push(e)}a.length>0&&(gL.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=>{gL.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})));const l=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];gL.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),e||s.forEach((e=>{gL.debug("[".concat(t._clientId,"] user online"),e._uintid),t.safeEmit(sD.USER_JOINED,e)})),n.length>0&&(r.forEach((e=>{gL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published audio")),t.safeEmit(sD.USER_PUBLISHED,e,"audio")})),o.forEach((e=>{gL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published video")),t.safeEmit(sD.USER_PUBLISHED,e,"video")})))};if(VP("ENABLE_USER_LIST"))c?(this.safeEmit(sD.USER_LIST,i),l(!0)):l();else if(d){if(n.length>0){const e=sr(n).call(n,((e,t)=>"".concat(e&&e+", ").concat(t.uid)),"");VP("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=n:(gL.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(e)),this.safeEmit(sD.PUBLISHED_USER_LIST,n))}}else l()}_handleP2PEvents(){this._gateway.signal.on(Ax.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(aF.PUBLISH,((e,t,i)=>{const n=e.uid;e.forEach((e=>{const r=e.kind,o=e.ssrcs,s=e.mid,a=e.isMuted;this._handleP2PAddAudioOrVideoStream(r,n,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===n));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,r,!!a)}))})),this._gateway.signal.on(aF.CALL,(async(e,t,i)=>{if(this.store.useP2P)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e))}catch(e){i(e)}})),this._gateway.signal.on(Cx.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(aF.UNPUBLISH,(async(e,t,i)=>{if(this.store.useP2P){const n=e.unpubMsg,r=e.uid,o=this._users.find((e=>e.uid===r));if(!o)return gL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{n.forEach((async e=>{const t=e.stream_type===Vx.Audio?zx.AUDIO:zx.VIDEO;await this._p2pChannel.unsubscribe(o,t),this._handleMuteStream(r,t,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(aF.CONTROL,(async(e,t)=>{switch(e.action){case cF.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,zx.VIDEO,!0);break;case cF.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,zx.AUDIO,!0);break;case cF.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,zx.VIDEO,!1);break;case cF.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,zx.AUDIO,!1)}})),this._gateway.signal.on(aF.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const i=e.direction,n=e.iceParameter;if(i!==bx.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(aF.CANDIDATE,(e=>{if(this.store.useP2P){const t=e.candidate,i=e.direction;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(tF.RequestP2PRestartICE,(async(e,t,i)=>{try{const i=e.direction;t(await this._gateway.sendExtensionMessage(aF.RESTART_ICE,e,i===bx.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(tF.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(aF.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(tF.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(aF.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(tF.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===PN.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(tF.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===PN.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(tF.StateChange,((e,t)=>{t===eF.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(tF.IceConnectionStateChange,(e=>{if("string"==typeof e||"connected"!==e.state&&"completed"!==e.state)return;const t=this._earlyJoinAttempt;t&&e.remoteUfrag&&t.acceptIceProof({remoteUfrag:e.remoteUfrag,state:"connected",at:Date.now()})})),this._p2pChannel.on(tF.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(sD.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(tF.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===PN.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(tF.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===PN.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(tF.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(tF.RequestRePublishDataChannel,((e,t,i)=>{cp.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!==PN.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(tF.RequestReSubscribe,(async(e,t,i)=>{try{for(const t of e){const e=t.user;t.kind===zx.VIDEO?await this.subscribe(e,"video"):await this.subscribe(e,"audio")}t()}catch(e){i(e)}})),this._p2pChannel.on(tF.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(tF.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(tF.MediaReconnectStart,(e=>{this.safeEmit(sD.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(tF.MediaReconnectEnd,(e=>{this.safeEmit(sD.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(tF.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(tF.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n})}catch(e){return void await t.throw(e)}const o=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r).iceParameters;await t.next({remoteIceParameters:o})})),this._p2pChannel.on(tF.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(tF.RequestReconnectPC,(async()=>{var e;const t=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),i=t.iceParameters,n=t.dtlsParameters,r=t.rtpCapabilities,o=await this._gateway.reconnectPC({iceParameters:i,dtlsParameters:n,rtpCapabilities:r}),s=rB(o.gatewayEstablishParams,o.gatewayAddress);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(tF.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(tF.P2PLost,(()=>{this.safeEmit(sD.P2P_LOST,this.store.uid)})),this._p2pChannel.on(tF.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig,e._optimizationMode).catch((e=>{gL.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))}))})),this._p2pChannel.on(tF.ConnectionTypeChange,(e=>{this.safeEmit(sD.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(tF.FirstVideoBufferReady,((e,t)=>{this.safeEmit(sD.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(tF.FirstVideoPreRender,((e,t)=>{this.safeEmit(sD.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(tF.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(tF.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(tF.AudioMetadata,(e=>{this.safeEmit(sD.AUDIO_METADATA,e)})),this._p2pChannel.on(tF.AudioPts,(e=>{this.safeEmit(sD.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new qL(PN.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},bB("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);const n=this._joinInfo,r=n.appId,o=n.cname,s=n.sid,a=n.token,c=n.uid,d=n.cid,l=n.vid;await i.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},XD)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(nF.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(sD.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===iF.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(sD.CONTENT_INSPECT_ERROR,new qL(PN.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(nF.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===PN.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return gL.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(sD.CONTENT_INSPECT_RESULT,e,t)})),e.on(nF.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new qL(PN.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(kN(e,"enabled"),e){if(!t)throw new qL(PN.INVALID_PARAMS,"config is required");if(function(e){if(UN(e.interval,"interval",1e3,1/0),e.extraInfo&&e.extraInfo.length>1024)throw new qL(PN.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e.vendor&&e.vendor.length>1024)throw new qL(PN.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}(t),!this._joinInfo)throw new qL(PN.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(i={config:t},bB("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);const n=this._joinInfo,r=n.appId,o=n.cname,s=n.sid,a=n.token,c=n.uid,d=n.cid,l=n.vid;await e.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},XD)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new qL(PN.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(sF.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(sD.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===oF.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new qL(PN.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(sF.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){MN(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new qL(PN.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,gL.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return gL.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){kN(e,"enabled"),UP("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}}},fx(qW.prototype,"leave",[oW],Object.getOwnPropertyDescriptor(qW.prototype,"leave"),qW.prototype),fx(qW.prototype,"publish",[sW],Object.getOwnPropertyDescriptor(qW.prototype,"publish"),qW.prototype),fx(qW.prototype,"unpublish",[aW],Object.getOwnPropertyDescriptor(qW.prototype,"unpublish"),qW.prototype),fx(qW.prototype,"subscribe",[cW],Object.getOwnPropertyDescriptor(qW.prototype,"subscribe"),qW.prototype),fx(qW.prototype,"presubscribe",[dW],Object.getOwnPropertyDescriptor(qW.prototype,"presubscribe"),qW.prototype),fx(qW.prototype,"massSubscribe",[lW],Object.getOwnPropertyDescriptor(qW.prototype,"massSubscribe"),qW.prototype),fx(qW.prototype,"unsubscribe",[uW],Object.getOwnPropertyDescriptor(qW.prototype,"unsubscribe"),qW.prototype),fx(qW.prototype,"massUnsubscribe",[hW],Object.getOwnPropertyDescriptor(qW.prototype,"massUnsubscribe"),qW.prototype),fx(qW.prototype,"setLowStreamParameter",[pW],Object.getOwnPropertyDescriptor(qW.prototype,"setLowStreamParameter"),qW.prototype),fx(qW.prototype,"setDualStreamMode",[_W],Object.getOwnPropertyDescriptor(qW.prototype,"setDualStreamMode"),qW.prototype),fx(qW.prototype,"enableDualStream",[EW],Object.getOwnPropertyDescriptor(qW.prototype,"enableDualStream"),qW.prototype),fx(qW.prototype,"disableDualStream",[fW],Object.getOwnPropertyDescriptor(qW.prototype,"disableDualStream"),qW.prototype),fx(qW.prototype,"setClientRole",[mW],Object.getOwnPropertyDescriptor(qW.prototype,"setClientRole"),qW.prototype),fx(qW.prototype,"_setClientRoleOptions",[SW],Object.getOwnPropertyDescriptor(qW.prototype,"_setClientRoleOptions"),qW.prototype),fx(qW.prototype,"setProxyServer",[gW],Object.getOwnPropertyDescriptor(qW.prototype,"setProxyServer"),qW.prototype),fx(qW.prototype,"setTurnServer",[TW],Object.getOwnPropertyDescriptor(qW.prototype,"setTurnServer"),qW.prototype),fx(qW.prototype,"setLicense",[RW],Object.getOwnPropertyDescriptor(qW.prototype,"setLicense"),qW.prototype),fx(qW.prototype,"startProxyServer",[vW],Object.getOwnPropertyDescriptor(qW.prototype,"startProxyServer"),qW.prototype),fx(qW.prototype,"stopProxyServer",[CW],Object.getOwnPropertyDescriptor(qW.prototype,"stopProxyServer"),qW.prototype),fx(qW.prototype,"setLocalAccessPointsV2",[IW],Object.getOwnPropertyDescriptor(qW.prototype,"setLocalAccessPointsV2"),qW.prototype),fx(qW.prototype,"setLocalAccessPoints",[yW],Object.getOwnPropertyDescriptor(qW.prototype,"setLocalAccessPoints"),qW.prototype),fx(qW.prototype,"setRemoteDefaultVideoStreamType",[AW],Object.getOwnPropertyDescriptor(qW.prototype,"setRemoteDefaultVideoStreamType"),qW.prototype),fx(qW.prototype,"setRemoteVideoStreamType",[bW],Object.getOwnPropertyDescriptor(qW.prototype,"setRemoteVideoStreamType"),qW.prototype),fx(qW.prototype,"setStreamFallbackOption",[OW],Object.getOwnPropertyDescriptor(qW.prototype,"setStreamFallbackOption"),qW.prototype),fx(qW.prototype,"setEncryptionConfig",[wW],Object.getOwnPropertyDescriptor(qW.prototype,"setEncryptionConfig"),qW.prototype),fx(qW.prototype,"renewToken",[NW],Object.getOwnPropertyDescriptor(qW.prototype,"renewToken"),qW.prototype),fx(qW.prototype,"enableAudioVolumeIndicator",[DW],Object.getOwnPropertyDescriptor(qW.prototype,"enableAudioVolumeIndicator"),qW.prototype),fx(qW.prototype,"startLiveStreaming",[PW],Object.getOwnPropertyDescriptor(qW.prototype,"startLiveStreaming"),qW.prototype),fx(qW.prototype,"setLiveTranscoding",[LW],Object.getOwnPropertyDescriptor(qW.prototype,"setLiveTranscoding"),qW.prototype),fx(qW.prototype,"stopLiveStreaming",[kW],Object.getOwnPropertyDescriptor(qW.prototype,"stopLiveStreaming"),qW.prototype),fx(qW.prototype,"startChannelMediaRelay",[MW],Object.getOwnPropertyDescriptor(qW.prototype,"startChannelMediaRelay"),qW.prototype),fx(qW.prototype,"updateChannelMediaRelay",[UW],Object.getOwnPropertyDescriptor(qW.prototype,"updateChannelMediaRelay"),qW.prototype),fx(qW.prototype,"stopChannelMediaRelay",[VW],Object.getOwnPropertyDescriptor(qW.prototype,"stopChannelMediaRelay"),qW.prototype),fx(qW.prototype,"sendCustomReportMessage",[xW],Object.getOwnPropertyDescriptor(qW.prototype,"sendCustomReportMessage"),qW.prototype),fx(qW.prototype,"pickSVCLayer",[FW],Object.getOwnPropertyDescriptor(qW.prototype,"pickSVCLayer"),qW.prototype),fx(qW.prototype,"setRTMConfig",[BW],Object.getOwnPropertyDescriptor(qW.prototype,"setRTMConfig"),qW.prototype),fx(qW.prototype,"enableContentInspect",[jW],Object.getOwnPropertyDescriptor(qW.prototype,"enableContentInspect"),qW.prototype),fx(qW.prototype,"disableContentInspect",[GW],Object.getOwnPropertyDescriptor(qW.prototype,"disableContentInspect"),qW.prototype),fx(qW.prototype,"setImageModeration",[WW],Object.getOwnPropertyDescriptor(qW.prototype,"setImageModeration"),qW.prototype),fx(qW.prototype,"setP2PTransport",[HW],Object.getOwnPropertyDescriptor(qW.prototype,"setP2PTransport"),qW.prototype),fx(qW.prototype,"getJoinChannelServiceRecords",[KW],Object.getOwnPropertyDescriptor(qW.prototype,"getJoinChannelServiceRecords"),qW.prototype),fx(qW.prototype,"setPublishAudioFilterEnabled",[YW],Object.getOwnPropertyDescriptor(qW.prototype,"setPublishAudioFilterEnabled"),qW.prototype),qW);function QW(){let e=!1;const t=Jw();return(t.name===Hw.CHROME&&Number(t.version)>=58&&(!Zw()||function(){const e=Jw();if($w()){if(e.os===Ww.MAC_OS)return!0;if(e.os===Ww.IOS){const e=Yw.os.version&&Yw.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===Hw.FIREFOX&&Number(t.version)>=56||t.name===Hw.OPERA&&Number(t.version)>=45||t.name===Hw.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(oN()||TN())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||RN()||Jw().name===Hw.QQ)&&(e=!0),e}class $W{constructor(e,t){Zb(this,"id",0),Zb(this,"element",void 0),Zb(this,"peerPair",void 0),Zb(this,"context",void 0),Zb(this,"audioPlayerElement",void 0),Zb(this,"audioTrack",void 0),$W.count+=1,this.id=$W.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new cp((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new qL(PN.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 qL(PN.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new qL(PN.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){gL.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 ZW,eH;Zb($W,"count",0);const tH=window.AudioContext||window.webkitAudioContext;const iH=new(ZW=KL({report:YL}),fx((eH=class{constructor(){Zb(this,"units",[]),Zb(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return gL.debug("the system does not need to process local aec"),-1;this.context||(this.context=new tH);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new $W(e,this.context),this.units.push(t)),t.startEchoCancellation(),gL.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Jw().name!==Hw.SAFARI}}).prototype,"processExternalMediaAEC",[ZW],Object.getOwnPropertyDescriptor(eH.prototype,"processExternalMediaAEC"),eH.prototype),eH);function nH(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function rH(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?nH(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):nH(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const oH=window||document;function sH(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!oH)return;const i=mH._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(mH.onSecurityPolicyViolation||mH.getListeners(rF.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;VP("CSP_DETECTED_HOSTNAME_LIST").some((e=>Un(t).call(t,e)))&&(mH.onSecurityPolicyViolation&&"function"==typeof mH.onSecurityPolicyViolation&&mH.onSecurityPolicyViolation(e),mH.getListeners(rF.SECURITY_POLICY_VIOLATION).length>0&&mH.safeEmit(rF.SECURITY_POLICY_VIOLATION,e))};i&&oH.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||mH.getListeners(rF.SECURITY_POLICY_VIOLATION).length>0)&&oH.addEventListener("securitypolicyviolation",n),mH._cspEventHandlerPointer=n}function aH(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cH(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aH(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aH(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class dH{constructor(e){Zb(this,"sessionDesc",void 0),Zb(this,"localCapabilities",void 0),Zb(this,"rtpCapabilities",void 0),Zb(this,"candidates",void 0),Zb(this,"_originCandidates",void 0),Zb(this,"iceParameters",void 0),Zb(this,"dtlsParameters",void 0),Zb(this,"setup",void 0),Zb(this,"currentMidIndex",void 0),Zb(this,"cname",void 0);const t=e=ID(e),i=t.iceParameters,n=t.dtlsParameters,r=t.candidates,o=t.rtpCapabilities,s=t.setup,a=t.localCapabilities,c=t.sdkCodec,d=t.cname,l=JP("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=o,this.candidates=r,this._originCandidates=ID(r),this.iceParameters=i,this.dtlsParameters=n,this.setup=s,this.localCapabilities=a,this.cname=d;for(let e=0;e<l.mediaDescriptions.length;e++){const t=l.mediaDescriptions[e];if(t.attributes.iceUfrag=i.iceUfrag,t.attributes.icePwd=i.icePwd,t.attributes.fingerprints=n.fingerprints,t.attributes.candidates=r,t.attributes.setup=s,"video"===t.media.mediaType){t.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10)));const e=o.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Un(i=t.encodingName.toLowerCase()).call(i,c)})),i=o.videoCodecs.filter((t=>!Un(e).call(e,t)));t.attributes.payloads=[...e,...i],t.attributes.extmaps=o.videoExtensions}"audio"===t.media.mediaType&&(t.media.fmts=o.audioCodecs.map((e=>e.payloadType.toString(10))),t.attributes.payloads=o.audioCodecs,t.attributes.extmaps=o.audioExtensions),l.mediaDescriptions[e]=this.mungMediaDesc(t)}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return zP(this.sessionDesc)}send(e,t,i){const n=aB(t,this.cname),r=n.ssrcs,o=n.ssrcGroups,s=this.sessionDesc.mediaDescriptions.find((t=>e===zx.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),a=r[0].attributes.label,c=r[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(r),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(o),{id:a,mslabel:c}}batchSend(e){return e.map((e=>{let t=e.kind,i=e.ssrcMsg;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{Un(e).call(e,t.attributes.label||"")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Un(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(cH(cH({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case Xx.TCP_RELAY:this.candidates=i;break;case Xx.UDP_TCP_RELAY:case Xx.RELAY:this.candidates=[...t,...i];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=ID(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}mungRecvMediaDsec(e,t){const i=ID(e);return cB(i,t),lB(i,t),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===zx.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;if(e)e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i)}}mungMediaDesc(e){const t=ID(e);return dB(t),function(e){const t=e.attributes.extmaps.find((e=>ZF(e.extensionName)));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}var lH;function uH(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hH(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?uH(Object(i),!0).forEach((function(t){Zb(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):uH(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let pH=(lH=class e extends Jx{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 Un(t=Object.keys(jP)).call(t,e)})))]}constructor(t,i){super(t,i),Zb(this,"store",void 0),Zb(this,"peerConnection",void 0),Zb(this,"remoteSDP",void 0),Zb(this,"initialOffer",void 0),Zb(this,"statsFilter",void 0),Zb(this,"useRTX",!1),Zb(this,"localCapabilities",void 0),Zb(this,"localCandidateCount",0),Zb(this,"allCandidatesReceived",!1),Zb(this,"establishPromise",void 0),Zb(this,"mutex",void 0),this.store=i,this.mutex=new JD("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=IP(this.peerConnection,VP("STATS_UPDATE_INTERVAL"),void 0,rN()?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=nB(e.sdp),i=iB(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:VP("FILTER_VIDEO_FEC"),filterAudioFec:VP("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,hH(hH({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new LN(PN.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 dH(hH(hH({},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 LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new LN(PN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var i=this;return XO((function*(){const n=yield QO(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map((e=>i.peerConnection.addTrack(e._mediaStreamTrack))),o=yield QO(i.peerConnection.createOffer()),s=JP(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{tN()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)})),e}const d=i.mungSendOfferSDP(o.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield QO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield QO(i.applySendEncodings(r,e)),yield QO(i.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:a[t],id:i}}))}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{tN()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const i=this.remoteSDP.send(e,t,n),r=i.id,o=i.mslabel,s=new cp(((t,i)=>{const n=setTimeout((()=>{i(new Error("Cannot receive track, id: ".concat(r)))}),1e4),s=i=>{const a=Jw();if(("Safari"===a.name&&11===Number(a.version)||oN())&&i.track.id!==r&&i.streams[0].id===o){var c;const o=i.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,r,i.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(n),void t(o)}if(i.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(n),void t(i.track)};this.peerConnection.addEventListener("track",s)})),a=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:a});const c=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(c);return{track:await s,id:r}}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(tN()&&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 LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(tN()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return XO((function*(){const i=yield QO(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=zL().supportPCSetConfiguration;if(e===Xx.RELAY&&!n)return;if(n){const i=t.peerConnection.getConfiguration(),n=e===Xx.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(gL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}e!==Xx.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield QO(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=nB(r.sdp),s=(yield o.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield QO(t.peerConnection.setLocalDescription(r)),yield QO(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){gL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new LN(PN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e}));1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find((e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t}));i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new LN(PN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new LN(PN.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,gL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,gL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),VP("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(iD(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),VP("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id}))}if(!t)return gL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!zL().supportSetRtpSenderParameters)return gL.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof yV)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(VP("DSCP_TYPE")&&IN()){var o;const e=VP("DSCP_TYPE");Un(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(s,n),gL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!zL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];n&&r&&await this.updateRtpSenderEncodings(r,n)}}catch(e){gL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const i=JP(e);return t.forEach(((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&cB(r,e)})),zP(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let n=t.id,r=t.mslabel;const o=e[i].kind;return new cp(((e,t)=>{const i=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=Jw();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await cp.all(t)}catch(e){throw new LN(PN.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(zL().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},fx(lH.prototype,"connect",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"connect"),lH.prototype),fx(lH.prototype,"stopSending",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"stopSending"),lH.prototype),fx(lH.prototype,"receive",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"receive"),lH.prototype),fx(lH.prototype,"stopReceiving",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"stopReceiving"),lH.prototype),fx(lH.prototype,"muteRemote",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"muteRemote"),lH.prototype),fx(lH.prototype,"unmuteRemote",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"unmuteRemote"),lH.prototype),fx(lH.prototype,"muteLocal",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"muteLocal"),lH.prototype),fx(lH.prototype,"unmuteLocal",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"unmuteLocal"),lH.prototype),fx(lH.prototype,"close",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"close"),lH.prototype),fx(lH.prototype,"updateEncoderConfig",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"updateEncoderConfig"),lH.prototype),fx(lH.prototype,"updateSendParameters",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"updateSendParameters"),lH.prototype),fx(lH.prototype,"replaceTrack",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"replaceTrack"),lH.prototype),fx(lH.prototype,"getRemoteSSRC",[_H],Object.getOwnPropertyDescriptor(lH.prototype,"getRemoteSSRC"),lH.prototype),lH);function _H(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}const EH={name:"PlanBConnection",create:function(e){let t=e.store,i=e.spec;return new pH(i,t)}};AP(),UP("PROCESS_ID","process-".concat(MD(8,""),"-").concat(MD(4,""),"-").concat(MD(4,""),"-").concat(MD(4,""),"-").concat(MD(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void gL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();gL.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(MP,e)){const n=t[e],r=n.value,o=n.expires;if(o&&o<=i)return;FP[e]=r,MP[e]=r}}))}catch(t){gL.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(FP.AREAS)&&FP.AREAS.length>0&&zB(FP.AREAS,!0);const fH=(e,t,i)=>{gL.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),UP(e,t,i)};!function(e){e(EH,!1)}(AB);const mH=function(e){const t=new JN,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===rF.SECURITY_POLICY_VIOLATION&&sH(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return rH(rH({},i),n)}({__TRACK_LIST__:fk,VERSION:bP,BUILD:LP,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:fH,getParameter:VP,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return zL().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new qL(PN.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=YL.reportApiInvoke(null,{name:QN.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:$N.TRACER}),i=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const i=window.RTCPeerConnection,n=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,r=window.WebSocket;t=!(!i||!r),e&&!n&&(t=!1),t&&yN()&&aN(75)&&(new i).close()}catch(e){gL.error("check system requirement failed: ",e),t=!1}return t}(e),n=QW();gL.debug("checkSystemRequirements, api:",i,"browser",n);const r=i&&n;return t.onSuccess(r),VP("IGNORE_RTC_DEVICE_CHECK")?i:r},getDevices:function(e){return EM.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return EM.getRecordingDevices(e)},getCameras:function(e){return EM.getCamerasDevices(e)},getElectronScreenSources:aM,getPlaybackDevices:function(e){return EM.getSpeakers(e)},createClient:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=MD(5,"client-"),i=YL.reportApiInvoke(null,{id:t,clientId:t,name:QN.CREATE_CLIENT,options:[e],tag:$N.TRACER});try{var n;!function(e){MN(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),MN(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&MN(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.aiClientMode&&kN(e.aiClientMode,"config.aiClientMode"),void 0!==e.proxyServer&&xN(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&nD(e.turnServer),void 0!==e.httpRetryConfig&&ZN(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&ZN(e.websocketRetryConfig)}(e),(pN(16,0,!0)||_N(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",gL.debug("browser not support vp9, force use vp8")),UP("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus");const r=new XW(zW(zW({forceWaitGatewayResponse:!0},e),{},{role:Un(n=["rtc","p2p"]).call(n,e.mode)?"host":e.role||"audience"}),t);return i.onSuccess(),Sj(),r}catch(e){throw i.onError(e),e}},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=VP("CAMERA_CAPTURE_CONFIG"),i=MD(8,"track-cam-"),n=YL.reportApiInvoke(null,{id:i,tag:$N.TRACER,name:QN.CREATE_CAM_VIDEO_TRACK,options:[Hk({},e),t]});t&&(e.encoderConfig=t);const r=FM(e);let o=null;gL.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await uM({video:r},i)).getVideoTracks()[0]||null}catch(e){throw n.onError(e),e}if(!o){const e=new LN(PN.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(gL)}if(e.optimizationMode&&OV(i,o,e,uk(e.encoderConfig)),VP("USE_STANDARD_BITRATE_DEFAULT")){const t=uk(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const s=new AV(o,e,r,e.scalabiltyMode?pk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return n.onSuccess(s.getTrackId()),gL.info("create camera video success, trackId:",i),s},createCustomVideoTrack:function(e){const t=MD(8,"track-cus-"),i=YL.reportApiInvoke(null,{id:t,tag:$N.TRACER,name:QN.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});VP("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const n=new yV(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin,minDownscaleWidth:e.minDownscaleWidth,minDownscaleHeight:e.minDownscaleHeight},e.scalabiltyMode?pk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[gk.CUSTOM_TRACK]);return i.onSuccess(n.getTrackId()),gL.info("create custom video track success with config",e,"trackId",n.getTrackId()),n},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i="object"==typeof t?function(e){const t=BM(e);return tk()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),ik()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;i&&(t="auto");const n=MD(8,"track-scr-v-"),r=YL.reportApiInvoke(null,{id:n,tag:$N.TRACER,name:QN.CREATE_SCREEN_VIDEO_TRACK,options:[Hk({},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="string"==typeof e.encoderConfig&&bV.has(e.encoderConfig),s=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&eN()&&(t.extensionId=e.extensionId);const i=e.displaySurface,n=e.selfBrowserSurface,r=e.surfaceSwitching,o=e.systemAudio,s=e.preferCurrentTab,a=e.windowAudio,c=e.monitorTypeSurfaces;(sN(107)||dN(107)||EN(93))&&(i&&(MN(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(MN(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(MN(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(sN(105)||dN(105)||EN(91))&&o&&(MN(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(sN(94)||dN(94)||EN(80))&&s&&(t.preferCurrentTab=!0),(sN(141)||dN(141)||EN(125))&&a&&(MN(a,"windowAudio",["exclude","system"]),t.windowAudio=a),(sN(119)||dN(119)||EN(105))&&c&&(MN(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const d=e.encoderConfig?hk(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 a=null,c=null;const d=zL();if(!d.supportShareAudio&&"enable"===t){const e=new LN(PN.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(gL)}gL.info("start create screen video track with config",e,"withAudio",t,"trackId",n);const l=d.supportShareAudio&&"disable"!==t;try{const e=await uM({screen:s,screenAudio:l?i||!0:void 0},n);a=e.getVideoTracks()[0]||null,c=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!a){const e=new LN(PN.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(gL)}if(!c&&"enable"===t){a&&a.stop();const e=new LN(PN.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(gL)}if("auto"===e.encoderConfig){const t=a.getSettings(),i=t.width,r=t.height,o=t.frameRate;i&&r?e.encoderConfig={width:i,height:r,frameRate:o||15}:(gL.warning("[".concat(n,"] can not read captured screen resolution for auto profile, fallback to 1080p_3")),e.encoderConfig=hk("1080p_3"))}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(OV(n,a,e,e.encoderConfig&&hk(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig)){const t=e.encoderConfig,i=t.bitrateMin,n=t.bitrateMax;e.encoderConfig.bitrateMin="number"==typeof i&&Number.isInteger(i)&&i>0?i:n}const u=new yV(a,e.encoderConfig?hk(e.encoderConfig):{},e.scalabiltyMode?pk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n,[gk.SCREEN_TRACK]);if(o&&u.updateBitrateFromProfile(),!c)return r.onSuccess(u.getTrackId()),gL.info("create screen video track success","video:",u.getTrackId()),u;const h=new DU(c,void 0,MD(8,"track-scr-a-"),!1);return r.onSuccess([u.getTrackId(),h.getTrackId()]),gL.info("create screen video track success","video:",u.getTrackId(),"audio:",h.getTrackId()),[u,h]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=VP("CAMERA_CAPTURE_CONFIG"),n=MD(8,"track-mic-"),r=MD(8,"track-cam-"),o=YL.reportApiInvoke(null,{id:"".concat(n,"-").concat(r),tag:$N.TRACER,name:QN.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const s=FM(t),a=jM(e);let c=null,d=null;gL.info("start create camera video track(".concat(r,") and microphone audio track(").concat(n,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await uM({audio:a,video:s},"".concat(n,"-").concat(r));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new LN(PN.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(gL)}if(t.optimizationMode&&OV(r,d,t,uk(t.encoderConfig)),VP("USE_STANDARD_BITRATE_DEFAULT")){const e=uk(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const l=new PU(c,e,a,n),u=new AV(d,t,s,t.scalabiltyMode?pk(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),gL.info("create camera video track(".concat(r,") and microphone audio track(").concat(n,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=MD(8,"track-mic-"),i=YL.reportApiInvoke(null,{id:t,tag:$N.TRACER,name:QN.CREATE_MIC_AUDIO_TRACK,options:[e]}),n=jM(e);let r=null;gL.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await uM({audio:n},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!r){const e=new LN(PN.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(gL)}const o=new PU(r,e,n,t);return i.onSuccess(o.getTrackId()),gL.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:function(e){const t=MD(8,"track-cus-"),i=YL.reportApiInvoke(null,{id:t,tag:$N.TRACER,name:QN.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),n=new DU(e.mediaStreamTrack,e.encoderConfig?Ek(e.encoderConfig):{},t,!1);return gL.info("create custom audio track success with config",e,"trackId",n.getTrackId()),i.onSuccess(n.getTrackId()),n},createBufferSourceAudioTrack:async function(e){var t;const i=e.cacheOnlineFile,n=e.encoderConfig;let r=e.source;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},s=MD(8,"track-buf-"),a=YL.reportApiInvoke(null,{id:s,tag:$N.TRACER,name:QN.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(VP("DISABLE_WEBAUDIO"))throw new LN(PN.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");gL.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(e,t){let i=null;if("string"==typeof e){const t=UU.get(e);if(t)return gL.debug("use cached audio resource: ",e),t;try{i=(await $D((()=>Vw.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new LN(PN.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new cp(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new LN(PN.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new LN(PN.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=$k();return new cp(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new LN(PN.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&UU.set(e,n),n}(r,i)}catch(e){return a.onError(e),e.throw(gL)}const d=new MU(r),l=new LU(c,d,n?Ek(n):{},s);return gL.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(gL.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw gL.debug("Invalid appType"),new qL(PN.INVALID_PARAMS,"invalid app type",e);UP("APP_TYPE",Math.floor(e))},setLogLevel:function(e){gL.setLogLevel(e)},enableLogUpload:function(){VP("USE_NEW_LOG")?UP("UPLOAD_LOG",!0):gL.enableLogUpload()},disableLogUpload:function(){VP("USE_NEW_LOG")?UP("UPLOAD_LOG",!1):gL.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new Nj},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=YL.reportApiInvoke(null,{tag:$N.TRACER,name:QN.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof DU||e instanceof HV)){const e=new qL(PN.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof DU?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new cp((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d<s?d:s;const l=o-s>1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:n,maxVolumeLevel:o,result:t};gL.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),i.onSuccess(s),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=YL.reportApiInvoke(null,{tag:$N.TRACER,name:QN.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof yV||e instanceof WV)){const e=new qL(PN.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof yV?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,(tN()||$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,i,n){let r,o=0,s=null;return new cp(((a,c)=>{function d(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new qL(PN.UNEXPECTED_ERROR,"can not get canvas 2d context.");return gL.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e<l;e+=3)if(d.data[e]!==s[e])return o+=1,void(s=d.data);s=d.data}else s=d.data}setTimeout((()=>{r&&(r(),a(o))}),t),r=tM((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw i.onError(e),e}nW===Hw.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return gL.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:zB,audioElementPlayCenter:NM,resumeAudioContext:function(){return NM.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){iH.processExternalMediaAEC(e)},registerExtensions:function(e){const t=VP("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Un(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=gL.extLog,i.reporter.hookApiInvoke=YL.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach((e=>{i.parameters[e]=VP(e)}))})),fH("PLUGIN_INFO",t)},ChannelMediaRelayError:Ux,ChannelMediaRelayEvent:kx,ChannelMediaRelayState:Mx,RemoteStreamFallbackType:vk,RemoteStreamType:Rk,ConnectionDisconnectedReason:tD,AudienceLatencyLevelType:eD,AREAS:jx,preload:async()=>{},startLastmileProbeTest:async()=>({state:"unavailable"}),use:e=>(AB(e),mH)});return Object.defineProperties(mH,{onAudioAutoplayFailed:{get:()=>mM.onAudioAutoplayFailed,set:e=>{mM.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>mM.onAutoplayFailed,set:e=>{mM.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>mH._onSecurityPolicyViolation,set(e){mH._onSecurityPolicyViolation=e,sH(e)}},__CLIENT_LIST__:{get:()=>VP("SHOW_GLOBAL_CLIENT_LIST")?XV:[]}}),EM.on(Uk.CAMERA_DEVICE_CHANGED,(e=>{gL.info("camera device changed",JSON.stringify(e)),mH.onCameraChanged&&mH.onCameraChanged(e),mH.safeEmit(rF.CAMERA_CHANGED,e)})),EM.on(Uk.RECORDING_DEVICE_CHANGED,(e=>{gL.info("microphone device changed",JSON.stringify(e)),mH.onMicrophoneChanged&&mH.onMicrophoneChanged(e),mH.safeEmit(rF.MICROPHONE_CHANGED,e)})),EM.on(Uk.PLAYOUT_DEVICE_CHANGED,(e=>{gL.debug("playout device changed",JSON.stringify(e)),mH.onPlaybackDeviceChanged&&mH.onPlaybackDeviceChanged(e),mH.safeEmit(rF.PLAYBACK_DEVICE_CHANGED,e)})),NM.onAutoplayFailed=()=>{gL.info("detect audio element autoplay failed"),mM.onAudioAutoplayFailed&&mM.onAudioAutoplayFailed()},Qk.on("autoplay-failed",(()=>{gL.info("detect webaudio autoplay failed"),mM.onAudioAutoplayFailed&&mM.onAudioAutoplayFailed(),mH.safeEmit(rF.AUTOPLAY_FAILED)})),Qk.on(nk.STATE_CHANGE,((e,t)=>{gL.info("audio context state changed: ".concat(t," => ").concat(e)),mH.onAudioContextStateChanged&&mH.onAudioContextStateChanged(e,t),mH.safeEmit(rF.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),ED.on(lD.NETWORK_STATE_CHANGE,((e,t)=>{gL.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=mH),mH}));