/** * AgoraWebSDK_N-v4.23.2-0-g1599fdac-dirty Copyright AgoraInc. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTC=t()}(this,(function(){"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n=function(e){try{return!!e()}catch(e){return!0}},r=!n((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),o=r,s=Function.prototype,a=s.call,c=o&&s.bind.bind(a,a),d=o?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math==Math&&e},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||function(){return this}()||t||Function("return this")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),T=d,S=T({}.toString),g=T("".slice),R=function(e){return g(S(e),8,-1)},v=R,C=d,I=function(e){if("Function"===v(e))return C(e)},y="object"==typeof document&&document.all,A={all:y,IS_HTMLDDA:void 0===y&&void 0!==y},b=A.all,w=A.IS_HTMLDDA?function(e){return"function"==typeof e||e===b}:function(e){return"function"==typeof e},O={},N=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),D=r,P=Function.prototype.call,L=D?P.bind(P):function(){return P.apply(P,arguments)},k={},M={}.propertyIsEnumerable,U=Object.getOwnPropertyDescriptor,x=U&&!M.call({1:2},1);k.f=x?function(e){var t=U(this,e);return!!t&&t.enumerable}:M;var V,F,B=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},j=n,G=R,W=Object,H=d("".split),K=j((function(){return!W("z").propertyIsEnumerable(0)}))?function(e){return"String"==G(e)?H(e,""):W(e)}:W,Y=function(e){return null==e},q=Y,z=TypeError,X=function(e){if(q(e))throw z("Can't call method on "+e);return e},J=K,Q=X,Z=function(e){return J(Q(e))},$=w,ee=A.all,te=A.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:$(e)||e===ee}:function(e){return"object"==typeof e?null!==e:$(e)},ie={},ne=ie,re=h,oe=w,se=function(e){return oe(e)?e:void 0},ae=function(e,t){return arguments.length<2?se(ne[e])||se(re[e]):ne[e]&&ne[e][t]||re[e]&&re[e][t]},ce="undefined"!=typeof navigator&&String(navigator.userAgent)||"",de=h,le=ce,ue=de.process,he=de.Deno,pe=ue&&ue.versions||he&&he.version,_e=pe&&pe.v8;_e&&(F=(V=_e.split("."))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&le&&(!(V=le.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=le.match(/Chrome\/(\d+)/))&&(F=+V[1]);var Ee=F,me=Ee,fe=n,Te=h.String,Se=!!Object.getOwnPropertySymbols&&!fe((function(){var e=Symbol();return!Te(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41})),ge=Se&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,ve=w,Ce=l,Ie=Object,ye=ge?function(e){return"symbol"==typeof e}:function(e){var t=Re("Symbol");return ve(t)&&Ce(t.prototype,Ie(e))},Ae=String,be=function(e){try{return Ae(e)}catch(e){return"Object"}},we=w,Oe=be,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+" is not a function")},Pe=De,Le=Y,ke=function(e,t){var i=e[t];return Le(i)?void 0:Pe(i)},Me=L,Ue=w,xe=te,Ve=TypeError,Fe={exports:{}},Be=h,je=Object.defineProperty,Ge=function(e,t){try{je(Be,e,{value:t,configurable:!0,writable:!0})}catch(i){Be[e]=t}return t},We="__core-js_shared__",He=h[We]||Ge(We,{}),Ke=He;(Fe.exports=function(e,t){return Ke[e]||(Ke[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ye=Fe.exports,qe=X,ze=Object,Xe=function(e){return ze(qe(e))},Je=Xe,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Je(e),t)},$e=d,et=0,tt=Math.random(),it=$e(1..toString),nt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+it(++et+tt,36)},rt=Ye,ot=Ze,st=nt,at=Se,ct=ge,dt=h.Symbol,lt=rt("wks"),ut=ct?dt.for||dt:dt&&dt.withoutSetter||st,ht=function(e){return ot(lt,e)||(lt[e]=at&&ot(dt,e)?dt[e]:ut("Symbol."+e)),lt[e]},pt=L,_t=te,Et=ye,mt=ke,ft=function(e,t){var i,n;if("string"===t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!xe(n=Me(i,e)))return n;if("string"!==t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;throw Ve("Can't convert object to primitive value")},Tt=TypeError,St=ht("toPrimitive"),gt=function(e,t){if(!_t(e)||Et(e))return e;var i,n=mt(e,St);if(n){if(void 0===t&&(t="default"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw Tt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ft(e,t)},Rt=ye,vt=function(e){var t=gt(e,"string");return Rt(t)?t:t+""},Ct=te,It=h.document,yt=Ct(It)&&Ct(It.createElement),At=function(e){return yt?It.createElement(e):{}},bt=At,wt=!N&&!n((function(){return 7!=Object.defineProperty(bt("div"),"a",{get:function(){return 7}}).a})),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=vt,Mt=Ze,Ut=wt,xt=Object.getOwnPropertyDescriptor;O.f=Ot?xt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return xt(e,t)}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t])};var Vt=n,Ft=w,Bt=/#|\.prototype\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?Vt(t):!!t)},Gt=jt.normalize=function(e){return String(e).replace(Bt,".").toLowerCase()},Wt=jt.data={},Ht=jt.NATIVE="N",Kt=jt.POLYFILL="P",Yt=jt,qt=De,zt=r,Xt=I(I.bind),Jt=function(e,t){return qt(e),void 0===t?e:zt?Xt(e,t):function(){return e.apply(t,arguments)}},Qt={},Zt=N&&n((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),$t=te,ei=String,ti=TypeError,ii=function(e){if($t(e))return e;throw ti(ei(e)+" is not an object")},ni=N,ri=wt,oi=Zt,si=ii,ai=vt,ci=TypeError,di=Object.defineProperty,li=Object.getOwnPropertyDescriptor,ui="enumerable",hi="configurable",pi="writable";Qt.f=ni?oi?function(e,t,i){if(si(e),t=ai(t),si(i),"function"==typeof e&&"prototype"===t&&"value"in i&&pi in i&&!i[pi]){var n=li(e,t);n&&n[pi]&&(e[t]=i.value,i={configurable:hi in i?i[hi]:n[hi],enumerable:ui in i?i[ui]:n[ui],writable:!1})}return di(e,t,i)}:di:function(e,t,i){if(si(e),t=ai(t),si(i),ri)try{return di(e,t,i)}catch(e){}if("get"in i||"set"in i)throw ci("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var _i=Qt,Ei=B,mi=N?function(e,t,i){return _i.f(e,t,Ei(1,i))}:function(e,t,i){return e[t]=i,e},fi=h,Ti=f,Si=I,gi=w,Ri=O.f,vi=Yt,Ci=ie,Ii=Jt,yi=mi,Ai=Ze,bi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return Ti(e,this,arguments)};return t.prototype=e.prototype,t},wi=function(e,t){var i,n,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?fi:p?fi[u]:(fi[u]||{}).prototype,m=h?Ci:Ci[u]||yi(Ci,u,{})[u],f=m.prototype;for(o in t)n=!(i=vi(h?o:u+(p?".":"#")+o,e.forced))&&E&&Ai(E,o),a=m[o],n&&(c=e.dontCallGetSet?(l=Ri(E,o))&&l.value:E[o]),s=n&&c?c:t[o],n&&typeof a==typeof s||(d=e.bind&&n?Ii(s,fi):e.wrap&&n?bi(s):_&&gi(s)?Si(s):s,(e.sham||s&&s.sham||a&&a.sham)&&yi(d,"sham",!0),yi(m,o,d),_&&(Ai(Ci,r=u+"Prototype")||yi(Ci,r,{}),yi(Ci[r],o,s),e.real&&f&&(i||!f[o])&&yi(f,o,s)))},Oi=Math.ceil,Ni=Math.floor,Di=Math.trunc||function(e){var t=+e;return(t>0?Ni:Oi)(t)},Pi=Di,Li=function(e){var t=+e;return t!=t||0===t?0:Pi(t)},ki=Li,Mi=Math.max,Ui=Math.min,xi=function(e,t){var i=ki(e);return i<0?Mi(i+t,0):Ui(i,t)},Vi=Li,Fi=Math.min,Bi=function(e){return e>0?Fi(Vi(e),9007199254740991):0},ji=Bi,Gi=function(e){return ji(e.length)},Wi=Z,Hi=xi,Ki=Gi,Yi=function(e){return function(t,i,n){var r,o=Wi(t),s=Ki(o),a=Hi(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},qi={includes:Yi(!0),indexOf:Yi(!1)},zi=qi.includes;wi({target:"Array",proto:!0,forced:n((function(){return!Array(1).includes()}))},{includes:function(e){return zi(this,e,arguments.length>1?arguments[1]:void 0)}});var Xi=ie,Ji=function(e){return Xi[e+"Prototype"]},Qi=Ji("Array").includes,Zi=te,$i=R,en=ht("match"),tn=function(e){var t;return Zi(e)&&(void 0!==(t=e[en])?!!t:"RegExp"==$i(e))},nn=tn,rn=TypeError,on={};on[ht("toStringTag")]="z";var sn="[object z]"===String(on),an=sn,cn=w,dn=R,ln=ht("toStringTag"),un=Object,hn="Arguments"==dn(function(){return arguments}()),pn=an?dn:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=un(e),ln))?i:hn?dn(t):"Object"==(n=dn(t))&&cn(t.callee)?"Arguments":n},_n=pn,En=String,mn=function(e){if("Symbol"===_n(e))throw TypeError("Cannot convert a Symbol value to a string");return En(e)},fn=ht("match"),Tn=wi,Sn=function(e){if(nn(e))throw rn("The method doesn't accept regular expressions");return e},gn=X,Rn=mn,vn=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[fn]=!1,"/./"[e](t)}catch(e){}}return!1},Cn=d("".indexOf);Tn({target:"String",proto:!0,forced:!vn("includes")},{includes:function(e){return!!~Cn(Rn(gn(this)),Rn(Sn(e)),arguments.length>1?arguments[1]:void 0)}});var In=Ji("String").includes,yn=l,An=Qi,bn=In,wn=Array.prototype,On=String.prototype,Nn=function(e){var t=e.includes;return e===wn||yn(wn,e)&&t===wn.includes?An:"string"==typeof e||e===On||yn(On,e)&&t===On.includes?bn:t},Dn=i(Nn),Pn=De,Ln=Xe,kn=K,Mn=Gi,Un=TypeError,xn=function(e){return function(t,i,n,r){Pn(i);var o=Ln(t),s=kn(o),a=Mn(o),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw Un("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=i(r,s[c],c,o));return r}},Vn={left:xn(!1),right:xn(!0)},Fn=n,Bn=function(e,t){var i=[][e];return!!i&&Fn((function(){i.call(null,t||function(){return 1},1)}))},jn="undefined"!=typeof process&&"process"==R(process),Gn=Vn.left;wi({target:"Array",proto:!0,forced:!jn&&Ee>79&&Ee<83||!Bn("reduce")},{reduce:function(e){var t=arguments.length;return Gn(this,e,t,t>1?arguments[1]:void 0)}});var Wn=Ji("Array").reduce,Hn=l,Kn=Wn,Yn=Array.prototype,qn=function(e){var t=e.reduce;return e===Yn||Hn(Yn,e)&&t===Yn.reduce?Kn:t},zn=qn,Xn=i(zn),Jn=R,Qn=Array.isArray||function(e){return"Array"==Jn(e)},Zn=wi,$n=Qn,er=d([].reverse),tr=[1,2];Zn({target:"Array",proto:!0,forced:String(tr)===String(tr.reverse())},{reverse:function(){return $n(this)&&(this.length=this.length),er(this)}});var ir=Ji("Array").reverse,nr=l,rr=ir,or=Array.prototype,sr=function(e){var t=e.reverse;return e===or||nr(or,e)&&t===or.reverse?rr:t},ar=sr,cr=i(ar),dr=nt,lr=Ye("keys"),ur=function(e){return lr[e]||(lr[e]=dr(e))},hr=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),pr=Ze,_r=w,Er=Xe,mr=hr,fr=ur("IE_PROTO"),Tr=Object,Sr=Tr.prototype,gr=mr?Tr.getPrototypeOf:function(e){var t=Er(e);if(pr(t,fr))return t[fr];var i=t.constructor;return _r(i)&&t instanceof i?i.prototype:t instanceof Tr?Sr:null},Rr=d,vr=De,Cr=w,Ir=String,yr=TypeError,Ar=function(e,t,i){try{return Rr(vr(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},br=ii,wr=function(e){if("object"==typeof e||Cr(e))return e;throw yr("Can't set "+Ir(e)+" as a prototype")},Or=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Ar(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return br(i),wr(n),t?e(i,n):i.__proto__=n,i}}():void 0),Nr={},Dr={},Pr=Ze,Lr=Z,kr=qi.indexOf,Mr=Dr,Ur=d([].push),xr=function(e,t){var i,n=Lr(e),r=0,o=[];for(i in n)!Pr(Mr,i)&&Pr(n,i)&&Ur(o,i);for(;t.length>r;)Pr(n,i=t[r++])&&(~kr(o,i)||Ur(o,i));return o},Vr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Fr=xr,Br=Vr.concat("length","prototype");Nr.f=Object.getOwnPropertyNames||function(e){return Fr(e,Br)};var jr={};jr.f=Object.getOwnPropertySymbols;var Gr=ae,Wr=Nr,Hr=jr,Kr=ii,Yr=d([].concat),qr=Gr("Reflect","ownKeys")||function(e){var t=Wr.f(Kr(e)),i=Hr.f;return i?Yr(t,i(e)):t},zr=Ze,Xr=qr,Jr=O,Qr=Qt,Zr={},$r=xr,eo=Vr,to=Object.keys||function(e){return $r(e,eo)},io=N,no=Zt,ro=Qt,oo=ii,so=Z,ao=to;Zr.f=io&&!no?Object.defineProperties:function(e,t){oo(e);for(var i,n=so(t),r=ao(t),o=r.length,s=0;o>s;)ro.f(e,i=r[s++],n[i]);return e};var co,lo=ae("document","documentElement"),uo=ii,ho=Zr,po=Vr,_o=Dr,Eo=lo,mo=At,fo="prototype",To="script",So=ur("IE_PROTO"),go=function(){},Ro=function(e){return"<"+To+">"+e+""},vo=function(e){e.write(Ro("")),e.close();var t=e.parentWindow.Object;return e=null,t},Co=function(){try{co=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;Co="undefined"!=typeof document?document.domain&&co?vo(co):(t=mo("iframe"),i="java"+To+":",t.style.display="none",Eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Ro("document.F=Object")),e.close(),e.F):vo(co);for(var n=po.length;n--;)delete Co[fo][po[n]];return Co()};_o[So]=!0;var Io=Object.create||function(e,t){var i;return null!==e?(go[fo]=uo(e),i=new go,go[fo]=null,i[So]=e):i=Co(),void 0===t?i:ho.f(i,t)},yo=te,Ao=mi,bo=Error,wo=d("".replace),Oo=String(bo("zxcasd").stack),No=/\n\s*at [^:]*:[^\n]*/,Do=No.test(Oo),Po=B,Lo=!n((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Po(1,7)),7!==e.stack)})),ko=mi,Mo=function(e,t){if(Do&&"string"==typeof e&&!bo.prepareStackTrace)for(;t--;)e=wo(e,No,"");return e},Uo=Lo,xo=Error.captureStackTrace,Vo={},Fo=Vo,Bo=ht("iterator"),jo=Array.prototype,Go=function(e){return void 0!==e&&(Fo.Array===e||jo[Bo]===e)},Wo=pn,Ho=ke,Ko=Y,Yo=Vo,qo=ht("iterator"),zo=function(e){if(!Ko(e))return Ho(e,qo)||Ho(e,"@@iterator")||Yo[Wo(e)]},Xo=L,Jo=De,Qo=ii,Zo=be,$o=zo,es=TypeError,ts=function(e,t){var i=arguments.length<2?$o(e):t;if(Jo(i))return Qo(Xo(i,e));throw es(Zo(e)+" is not iterable")},is=L,ns=ii,rs=ke,os=function(e,t,i){var n,r;ns(e);try{if(!(n=rs(e,"return"))){if("throw"===t)throw i;return i}n=is(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return ns(n),i},ss=Jt,as=L,cs=ii,ds=be,ls=Go,us=Gi,hs=l,ps=ts,_s=zo,Es=os,ms=TypeError,fs=function(e,t){this.stopped=e,this.result=t},Ts=fs.prototype,Ss=function(e,t,i){var n,r,o,s,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=ss(t,l),m=function(e){return n&&Es(n,"normal",e),new fs(!0,e)},f=function(e){return u?(cs(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=_s(e)))throw ms(ds(e)+" is not iterable");if(ls(r)){for(o=0,s=us(e);s>o;o++)if((a=f(e[o]))&&hs(Ts,a))return a;return new fs(!1)}n=ps(e,r)}for(c=h?e.next:n.next;!(d=as(c,n)).done;){try{a=f(d.value)}catch(e){Es(n,"throw",e)}if("object"==typeof a&&a&&hs(Ts,a))return a}return new fs(!1)},gs=mn,Rs=wi,vs=l,Cs=gr,Is=Or,ys=function(e,t,i){for(var n=Xr(t),r=Qr.f,o=Jr.f,s=0;s2&&Os(i,arguments[2]);var r=[];return Ds(e,Ms,{that:r}),bs(i,"errors",r),i};Is?Is(Us,ks):ys(Us,ks,{name:!0});var xs=Us.prototype=As(ks.prototype,{constructor:ws(1,Us),message:ws(1,""),name:ws(1,"AggregateError")});Rs({global:!0,constructor:!0,arity:2},{AggregateError:Us});var Vs,Fs,Bs,js=w,Gs=h.WeakMap,Ws=js(Gs)&&/native code/.test(String(Gs)),Hs=h,Ks=te,Ys=mi,qs=Ze,zs=He,Xs=ur,Js=Dr,Qs="Object already initialized",Zs=Hs.TypeError,$s=Hs.WeakMap;if(Ws||zs.state){var ea=zs.state||(zs.state=new $s);ea.get=ea.get,ea.has=ea.has,ea.set=ea.set,Vs=function(e,t){if(ea.has(e))throw Zs(Qs);return t.facade=e,ea.set(e,t),t},Fs=function(e){return ea.get(e)||{}},Bs=function(e){return ea.has(e)}}else{var ta=Xs("state");Js[ta]=!0,Vs=function(e,t){if(qs(e,ta))throw Zs(Qs);return t.facade=e,Ys(e,ta,t),t},Fs=function(e){return qs(e,ta)?e[ta]:{}},Bs=function(e){return qs(e,ta)}}var ia,na,ra,oa={set:Vs,get:Fs,has:Bs,enforce:function(e){return Bs(e)?Fs(e):Vs(e,{})},getterFor:function(e){return function(t){var i;if(!Ks(t)||(i=Fs(t)).type!==e)throw Zs("Incompatible receiver, "+e+" required");return i}}},sa=N,aa=Ze,ca=Function.prototype,da=sa&&Object.getOwnPropertyDescriptor,la=aa(ca,"name"),ua={EXISTS:la,PROPER:la&&"something"===function(){}.name,CONFIGURABLE:la&&(!sa||sa&&da(ca,"name").configurable)},ha=mi,pa=function(e,t,i,n){return n&&n.enumerable?e[t]=i:ha(e,t,i),e},_a=n,Ea=w,ma=te,fa=Io,Ta=gr,Sa=pa,ga=ht("iterator"),Ra=!1;[].keys&&("next"in(ra=[].keys())?(na=Ta(Ta(ra)))!==Object.prototype&&(ia=na):Ra=!0);var va=!ma(ia)||_a((function(){var e={};return ia[ga].call(e)!==e}));Ea((ia=va?{}:fa(ia))[ga])||Sa(ia,ga,(function(){return this}));var Ca={IteratorPrototype:ia,BUGGY_SAFARI_ITERATORS:Ra},Ia=pn,ya=sn?{}.toString:function(){return"[object "+Ia(this)+"]"},Aa=sn,ba=Qt.f,wa=mi,Oa=Ze,Na=ya,Da=ht("toStringTag"),Pa=function(e,t,i,n){if(e){var r=i?e:e.prototype;Oa(r,Da)||ba(r,Da,{configurable:!0,value:t}),n&&!Aa&&wa(r,"toString",Na)}},La=Ca.IteratorPrototype,ka=Io,Ma=B,Ua=Pa,xa=Vo,Va=function(){return this},Fa=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ka(La,{next:Ma(+!n,i)}),Ua(e,r,!1,!0),xa[r]=Va,e},Ba=wi,ja=L,Ga=ua,Wa=Fa,Ha=gr,Ka=Pa,Ya=pa,qa=Vo,za=Ca,Xa=Ga.PROPER,Ja=za.BUGGY_SAFARI_ITERATORS,Qa=ht("iterator"),Za="keys",$a="values",ec="entries",tc=function(){return this},ic=function(e,t,i,n,r,o,s){Wa(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Ja&&e in p)return p[e];switch(e){case Za:case $a:case ec:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[Qa]||p["@@iterator"]||r&&p[r],E=!Ja&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=Ha(m.call(new e)))!==Object.prototype&&a.next&&(Ka(a,u,!0,!0),qa[u]=tc),Xa&&r==$a&&_&&_.name!==$a&&(h=!0,E=function(){return ja(_,this)}),r)if(c={values:l($a),keys:o?E:l(Za),entries:l(ec)},s)for(d in c)(Ja||h||!(d in p))&&Ya(p,d,c[d]);else Ba({target:t,proto:!0,forced:Ja||h},c);return s&&p[Qa]!==E&&Ya(p,Qa,E,{name:r}),qa[t]=E,c},nc=function(e,t){return{value:e,done:t}},rc=Z,oc=Vo,sc=oa;Qt.f;var ac=ic,cc=nc,dc="Array Iterator",lc=sc.set,uc=sc.getterFor(dc);ac(Array,"Array",(function(e,t){lc(this,{type:dc,target:rc(e),index:0,kind:t})}),(function(){var e=uc(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,cc(void 0,!0)):cc("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),oc.Arguments=oc.Array;var hc=Qt,pc=function(e,t,i){return hc.f(e,t,i)},_c=ae,Ec=pc,mc=N,fc=ht("species"),Tc=l,Sc=TypeError,gc=function(e,t){if(Tc(t,e))return e;throw Sc("Incorrect invocation")},Rc=w,vc=He,Cc=d(Function.toString);Rc(vc.inspectSource)||(vc.inspectSource=function(e){return Cc(e)});var Ic=vc.inspectSource,yc=d,Ac=n,bc=w,wc=pn,Oc=Ic,Nc=function(){},Dc=[],Pc=ae("Reflect","construct"),Lc=/^\s*(?:class|function)\b/,kc=yc(Lc.exec),Mc=!Lc.exec(Nc),Uc=function(e){if(!bc(e))return!1;try{return Pc(Nc,Dc,e),!0}catch(e){return!1}},xc=function(e){if(!bc(e))return!1;switch(wc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Mc||!!kc(Lc,Oc(e))}catch(e){return!0}};xc.sham=!0;var Vc,Fc,Bc,jc,Gc=!Pc||Ac((function(){var e;return Uc(Uc.call)||!Uc(Object)||!Uc((function(){e=!0}))||e}))?xc:Uc,Wc=Gc,Hc=be,Kc=TypeError,Yc=ii,qc=function(e){if(Wc(e))return e;throw Kc(Hc(e)+" is not a constructor")},zc=Y,Xc=ht("species"),Jc=function(e,t){var i,n=Yc(e).constructor;return void 0===n||zc(i=Yc(n)[Xc])?t:qc(i)},Qc=d([].slice),Zc=TypeError,$c=function(e,t){if(e=a?e?"":void 0:(n=gh(o,s))<55296||n>56319||s+1===a||(r=gh(o,s+1))<56320||r>57343?e?Sh(o,s):n:e?Rh(o,s,s+2):r-56320+(n-55296<<10)+65536}},Ch={codeAt:vh(!1),charAt:vh(!0)},Ih=Ch.charAt,yh=mn,Ah=oa,bh=ic,wh=nc,Oh="String Iterator",Nh=Ah.set,Dh=Ah.getterFor(Oh);bh(String,"String",(function(e){Nh(this,{type:Oh,string:yh(e),index:0})}),(function(){var e,t=Dh(this),i=t.string,n=t.index;return n>=i.length?wh(void 0,!0):(e=Ih(i,n),t.index+=e.length,wh(e,!1))}));var Ph=ie.Promise,Lh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},kh=h,Mh=pn,Uh=mi,xh=Vo,Vh=ht("toStringTag");for(var Fh in Lh){var Bh=kh[Fh],jh=Bh&&Bh.prototype;jh&&Mh(jh)!==Vh&&Uh(jh,Vh,Fh),xh[Fh]=xh.Array}var Gh=Ph,Wh=i(Gh),Hh=Ji("Array").values,Kh=pn,Yh=Ze,qh=l,zh=Hh,Xh=Array.prototype,Jh={DOMTokenList:!0,NodeList:!0},Qh=function(e){var t=e.values;return e===Xh||qh(Xh,e)&&t===Xh.values||Yh(Jh,Kh(e))?zh:t},Zh=i(Qh),$h=n,ep=ht("iterator"),tp=!$h((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2"),n="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),n+=i+e})),i.delete("a",2),!e.toJSON||!i.has("a",1)||i.has("a",2)||!t.size&&true||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[ep]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host})),ip=pa,np=vt,rp=Qt,op=B,sp=function(e,t,i){var n=np(t);n in e?rp.f(e,n,op(0,i)):e[n]=i},ap=xi,cp=Gi,dp=sp,lp=Array,up=Math.max,hp=function(e,t,i){for(var n=cp(e),r=ap(t,n),o=ap(void 0===i?n:i,n),s=lp(up(o-r,0)),a=0;r0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},fp=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s0?arguments[0]:void 0));Cp||(this.size=e.entries.length)},w_=b_.prototype;if(bp(w_,{append:function(e,t){var i=Xp(this);Wp(arguments.length,2),l_(i.entries,{key:Vp(e),value:Vp(t)}),Cp||this.length++,i.updateURL()},delete:function(e){for(var t=Xp(this),i=Wp(arguments.length,1),n=t.entries,r=Vp(e),o=i<2?void 0:arguments[1],s=void 0===o?o:Vp(o),a=0;at.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Xp(this).entries,n=kp(e,arguments.length>1?arguments[1]:void 0),r=0;r1?D_(arguments[1]):{})}}),Pp(e_)){var P_=function(e){return Dp(this,i_),new e_(e,arguments.length>1?D_(arguments[1]):{})};i_.constructor=P_,P_.prototype=i_,Sp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:P_})}}var L_,k_={URLSearchParams:b_,getState:Xp},M_=ie.URLSearchParams,U_=N,x_=d,V_=L,F_=n,B_=to,j_=jr,G_=k,W_=Xe,H_=K,K_=Object.assign,Y_=Object.defineProperty,q_=x_([].concat),z_=!K_||F_((function(){if(U_&&1!==K_({b:1},K_(Y_({},"a",{enumerable:!0,get:function(){Y_(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach((function(e){t[e]=e})),7!=K_({},e)[i]||B_(K_({},t)).join("")!=n}))?function(e,t){for(var i=W_(e),n=arguments.length,r=1,o=j_.f,s=G_.f;n>r;)for(var a,c=H_(arguments[r++]),d=o?q_(B_(c),o(c)):B_(c),l=d.length,u=0;l>u;)a=d[u++],U_&&!V_(s,c,a)||(i[a]=c[a]);return i}:K_,X_=ii,J_=os,Q_=Jt,Z_=L,$_=Xe,eE=function(e,t,i,n){try{return n?t(X_(i)[0],i[1]):t(i)}catch(t){J_(e,"throw",t)}},tE=Go,iE=Gc,nE=Gi,rE=sp,oE=ts,sE=zo,aE=Array,cE=d,dE=2147483647,lE=/[^\0-\u007E]/,uE=/[.\u3002\uFF0E\uFF61]/g,hE="Overflow: input needs wider integers to process",pE=RangeError,_E=cE(uE.exec),EE=Math.floor,mE=String.fromCharCode,fE=cE("".charCodeAt),TE=cE([].join),SE=cE([].push),gE=cE("".replace),RE=cE("".split),vE=cE("".toLowerCase),CE=function(e){return e+22+75*(e<26)},IE=function(e,t,i){var n=0;for(e=i?EE(e/700):e>>1,e+=EE(e/t);e>455;)e=EE(e/35),n+=36;return EE(n+36*e/(e+38))},yE=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=o&&nEE((dE-s)/u))throw pE(hE);for(s+=(l-o)*u,o=l,i=0;idE)throw pE(hE);if(n==o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;SE(t,mE(CE(_+E%m))),h=EE(E/m),p+=36}SE(t,mE(CE(h))),a=IE(s,u,d==c),s=0,d++}}s++,o++}return TE(t,"")},AE=wi,bE=N,wE=tp,OE=h,NE=Jt,DE=d,PE=pa,LE=pc,kE=gc,ME=Ze,UE=z_,xE=function(e){var t=$_(e),i=iE(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=Q_(r,n>2?arguments[2]:void 0));var s,a,c,d,l,u,h=sE(t),p=0;if(!h||this===aE&&tE(h))for(s=nE(t),a=i?new this(s):aE(s);s>p;p++)u=o?r(t[p],p):t[p],rE(a,p,u);else for(l=(d=oE(t,h)).next,a=i?new this:[];!(c=Z_(l,d)).done;p++)u=o?eE(d,r,[c.value,p],!0):c.value,rE(a,p,u);return a.length=p,a},VE=hp,FE=Ch.codeAt,BE=function(e){var t,i,n=[],r=RE(gE(vE(e),uE,"."),".");for(t=0;t?@[\\\]^|]/,Im=/[\0\t\n\r #/:<>?@[\\\]^|]/,ym=/^[\u0000-\u0020]+/,Am=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,bm=/[\t\n\r]/g,wm=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)hm(t,e%256),e=$E(e/256);return nm(t,".")}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=rm(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},Om={},Nm=UE({},Om,{" ":1,'"':1,"<":1,">":1,"`":1}),Dm=UE({},Nm,{"#":1,"?":1,"{":1,"}":1}),Pm=UE({},Dm,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Lm=function(e,t){var i=FE(e,0);return i>32&&i<127&&!ME(t,e)?e:encodeURIComponent(e)},km={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Mm=function(e,t){var i;return 2==e.length&&im(mm,tm(e,0))&&(":"==(i=tm(e,1))||!t&&"|"==i)},Um=function(e){var t;return e.length>1&&Mm(lm(e,0,2))&&(2==e.length||"/"===(t=tm(e,2))||"\\"===t||"?"===t||"#"===t)},xm=function(e){return"."===e||"%2e"===um(e)},Vm={},Fm={},Bm={},jm={},Gm={},Wm={},Hm={},Km={},Ym={},qm={},zm={},Xm={},Jm={},Qm={},Zm={},$m={},ef={},tf={},nf={},rf={},of={},sf=function(e,t,i){var n,r,o,s=jE(e);if(t){if(r=this.parse(s))throw QE(r);this.searchParams=null}else{if(void 0!==i&&(n=new sf(i,!0)),r=this.parse(s,null,n))throw QE(r);(o=XE(new zE)).bindURL(this),this.searchParams=o}};sf.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,d=t||Vm,l=0,u="",h=!1,p=!1,_=!1;for(e=jE(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=am(e,ym,""),e=am(e,Am,"$1")),e=am(e,bm,""),n=xE(e);l<=n.length;){switch(r=n[l],d){case Vm:if(!r||!im(mm,r)){if(t)return pm;d=Bm;continue}u+=um(r),d=Fm;break;case Fm:if(r&&(im(fm,r)||"+"==r||"-"==r||"."==r))u+=um(r);else{if(":"!=r){if(t)return pm;u="",d=Bm,l=0;continue}if(t&&(c.isSpecial()!=ME(km,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&km[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=Qm:c.isSpecial()&&i&&i.scheme==c.scheme?d=jm:c.isSpecial()?d=Km:"/"==n[l+1]?(d=Gm,l++):(c.cannotBeABaseURL=!0,sm(c.path,""),d=nf)}break;case Bm:if(!i||i.cannotBeABaseURL&&"#"!=r)return pm;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=VE(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=of;break}d="file"==i.scheme?Qm:Wm;continue;case jm:if("/"!=r||"/"!=n[l+1]){d=Wm;continue}d=Ym,l++;break;case Gm:if("/"==r){d=qm;break}d=tf;continue;case Wm:if(c.scheme=i.scheme,r==L_)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=VE(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=Hm;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=VE(i.path),c.query="",d=rf;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=VE(i.path),c.path.length--,d=tf;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=VE(i.path),c.query=i.query,c.fragment="",d=of}break;case Hm:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=tf;continue}d=qm}else d=Ym;break;case Km:if(d=Ym,"/"!=r||"/"!=tm(u,l+1))continue;l++;break;case Ym:if("/"!=r&&"\\"!=r){d=qm;continue}break;case qm:if("@"==r){h&&(u="%40"+u),h=!0,o=xE(u);for(var E=0;E65535)return Em;c.port=c.isSpecial()&&T===km[c.scheme]?null:T,u=""}if(t)return;d=ef;continue}return Em}u+=r;break;case Qm:if(c.scheme="file","/"==r||"\\"==r)d=Zm;else{if(!i||"file"!=i.scheme){d=tf;continue}if(r==L_)c.host=i.host,c.path=VE(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=VE(i.path),c.query="",d=rf;else{if("#"!=r){Um(nm(VE(n,l),""))||(c.host=i.host,c.path=VE(i.path),c.shortenPath()),d=tf;continue}c.host=i.host,c.path=VE(i.path),c.query=i.query,c.fragment="",d=of}}break;case Zm:if("/"==r||"\\"==r){d=$m;break}i&&"file"==i.scheme&&!Um(nm(VE(n,l),""))&&(Mm(i.path[0],!0)?sm(c.path,i.path[0]):c.host=i.host),d=tf;continue;case $m:if(r==L_||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&Mm(u))d=tf;else if(""==u){if(c.host="",t)return;d=ef}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",d=ef}continue}u+=r;break;case ef:if(c.isSpecial()){if(d=tf,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=L_&&(d=tf,"/"!=r))continue}else c.fragment="",d=of;else c.query="",d=rf;break;case tf:if(r==L_||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=um(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||sm(c.path,"")):xm(u)?"/"==r||"\\"==r&&c.isSpecial()||sm(c.path,""):("file"==c.scheme&&!c.path.length&&Mm(u)&&(c.host&&(c.host=""),u=tm(u,0)+":"),sm(c.path,u)),u="","file"==c.scheme&&(r==L_||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)cm(c.path);"?"==r?(c.query="",d=rf):"#"==r&&(c.fragment="",d=of)}else u+=Lm(r,Dm);break;case nf:"?"==r?(c.query="",d=rf):"#"==r?(c.fragment="",d=of):r!=L_&&(c.path[0]+=Lm(r,Om));break;case rf:t||"#"!=r?r!=L_&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":Lm(r,Om)):(c.fragment="",d=of);break;case of:r!=L_&&(c.fragment+=Lm(r,Nm))}l++}},parseHost:function(e){var t,i,n;if("["==tm(e,0)){if("]"!=tm(e,e.length-1))return _m;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 tm(e,u)};if(":"==h()){if(":"!=tm(e,1))return;u+=2,l=++d}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&im(vm,h());)t=16*t+ZE(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(!im(Tm,h()))return;for(;im(Tm,h());){if(o=ZE(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}(lm(e,1,-1)),!t)return _m;this.host=t}else if(this.isSpecial()){if(e=BE(e),im(Cm,e))return _m;if(t=function(e){var t,i,n,r,o,s,a,c=dm(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&"0"==tm(r,0)&&(o=im(Sm,r)?16:8,r=lm(r,8==o?1:2)),""===r)s=0;else{if(!im(10==o?Rm:8==o?gm:vm,r))return e;s=ZE(r,o)}sm(i,s)}for(n=0;n=em(256,5-t))return null}else if(s>255)return null;for(a=om(i),n=0;n1?arguments[1]:void 0,n=YE(t,new sf(e,!1,i));bE||(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())},cf=af.prototype,df=function(e,t){return{get:function(){return qE(this)[e]()},set:t&&function(e){return qE(this)[t](e)},configurable:!0,enumerable:!0}};if(bE&&(LE(cf,"href",df("serialize","setHref")),LE(cf,"origin",df("getOrigin")),LE(cf,"protocol",df("getProtocol","setProtocol")),LE(cf,"username",df("getUsername","setUsername")),LE(cf,"password",df("getPassword","setPassword")),LE(cf,"host",df("getHost","setHost")),LE(cf,"hostname",df("getHostname","setHostname")),LE(cf,"port",df("getPort","setPort")),LE(cf,"pathname",df("getPathname","setPathname")),LE(cf,"search",df("getSearch","setSearch")),LE(cf,"searchParams",df("getSearchParams")),LE(cf,"hash",df("getHash","setHash"))),PE(cf,"toJSON",(function(){return qE(this).serialize()}),{enumerable:!0}),PE(cf,"toString",(function(){return qE(this).serialize()}),{enumerable:!0}),JE){var lf=JE.createObjectURL,uf=JE.revokeObjectURL;lf&&PE(af,"createObjectURL",NE(lf,JE)),uf&&PE(af,"revokeObjectURL",NE(uf,JE))}GE(af,"URL"),AE({global:!0,constructor:!0,forced:!wE,sham:!bE},{URL:af});var hf=wi,pf=n,_f=$c,Ef=mn,mf=tp,ff=ae("URL");hf({target:"URL",stat:!0,forced:!(mf&&pf((function(){ff.canParse()})))},{canParse:function(e){var t=_f(arguments.length,1),i=Ef(e),n=t<2||void 0===arguments[1]?void 0:Ef(arguments[1]);try{return!!new ff(i,n)}catch(e){return!1}}});var Tf=i(ie.URL);let Sf=!0,gf=!0;function Rf(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function vf(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 Cf(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Sf=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function If(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(gf=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function yf(){if("object"==typeof window){if(Sf)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Af(e,t){gf&&console.warn(e+" is deprecated, please use "+t+" instead.")}function bf(e){return"[object Object]"===Object.prototype.toString.call(e)}function wf(e){var t;return bf(e)?Xn(t=Object.keys(e)).call(t,(function(t,i){const n=bf(e[i]),r=n?wf(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function Of(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Of(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Of(e,e.get(t),i)}))})))}function Nf(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&&Of(e,i,r)}))})),r}const Df=yf;function Pf(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>{var i;return Dn(i=e.label.toLowerCase()).call(i,t)}))));return!s&&i.length&&Dn(t).call(t,"back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),Df("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Df("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Wh.reject(o(e))))))}}}function Lf(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function kf(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 vf(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Mf(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 Uf(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Wh(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function xf(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=>Nf(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}),vf(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Nf(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Wh.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Wh.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Vf(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 Ff(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Vf(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find((e=>e.track===t));if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Wh.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Bf(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 jf(e,t){vf(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Gf=Object.freeze({__proto__:null,fixNegotiationNeeded:jf,shimAddTrackRemoveTrack:Ff,shimAddTrackRemoveTrackWithNative:Vf,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:Mf,shimGetStats:Uf,shimGetUserMedia:Pf,shimMediaStream:Lf,shimOnTrack:kf,shimPeerConnection:Bf,shimSenderReceiverGetStats:xf});function Wf(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Af("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 Hf(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 Kf(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function Yf(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Wh.resolve(new Map)}}function qf(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}),vf(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function zf(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Af("removeStream","removeTrack"),this.getSenders().forEach((t=>{var i;t.track&&Dn(i=e.getTracks()).call(i,t.track)&&this.removeTrack(t)}))})}function Xf(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Jf(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Qf(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 Zf(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Wh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function $f(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Wh.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var eT=Object.freeze({__proto__:null,shimAddTransceiver:Jf,shimCreateAnswer:$f,shimCreateOffer:Zf,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Wh.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Qf,shimGetUserMedia:Wf,shimOnTrack:Hf,shimPeerConnection:Kf,shimRTCDataChannel:Xf,shimReceiverGetStats:qf,shimRemoveStream:zf,shimSenderGetStats:Yf});function tT(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var i;this._localStreams||(this._localStreams=[]),Dn(i=this._localStreams).call(i,e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r{var t;this._localStreams?Dn(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{Dn(i).call(i,e.track)&&this.removeTrack(e)}))})}}function iT(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{var t;if(this._remoteStreams||(this._remoteStreams=[]),Dn(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const i=new Event("addstream");i.stream=e,this.dispatchEvent(i)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function nT(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Wh.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Wh.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Wh.resolve()):n},t.addIceCandidate=a}function rT(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(oT(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function oT(e){return e&&void 0!==e.video?Object.assign({},e,{video:wf(e.video)}):e}function sT(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate})}function aT(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 cT(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 dT(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var lT=Object.freeze({__proto__:null,shimAudioContext:dT,shimCallbacksAPI:nT,shimConstraints:oT,shimCreateOfferLegacy:cT,shimGetUserMedia:rT,shimLocalStreamsAPI:tT,shimRTCIceServerUrls:sT,shimRemoteStreamsAPI:iT,shimTrackEventTransceiver:aT}),uT="\t\n\v\f\r                 \u2028\u2029\ufeff",hT=X,pT=mn,_T=uT,ET=d("".replace),mT=RegExp("^["+_T+"]+"),fT=RegExp("(^|[^"+_T+"])["+_T+"]+$"),TT=function(e){return function(t){var i=pT(hT(t));return 1&e&&(i=ET(i,mT,"")),2&e&&(i=ET(i,fT,"$1")),i}},ST={start:TT(1),end:TT(2),trim:TT(3)},gT=ua.PROPER,RT=n,vT=uT,CT=ST.trim;wi({target:"String",proto:!0,forced:function(e){return RT((function(){return!!vT[e]()||"​…᠎"!=="​…᠎"[e]()||gT&&vT[e].name!==e}))}("trim")},{trim:function(){return CT(this)}});var IT=Ji("String").trim,yT=l,AT=IT,bT=String.prototype,wT=function(e){var t=e.trim;return"string"==typeof e||e===bT||yT(bT,e)&&t===bT.trim?AT:t},OT=i(wT),NT={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function MT(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||vf(e,"icecandidate",(e=>{if(e.candidate){const t=PT.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function UT(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=PT.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=PT.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=PT.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=o(arguments[0],e);let s;s=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function xT(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},vf(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function VT(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 FT(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"!==OT(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 BT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Wh.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Wh.resolve())})}function jT(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 GT=Object.freeze({__proto__:null,removeExtmapAllowMixed:FT,shimAddIceCandidateNullOrEmpty:BT,shimConnectionState:VT,shimMaxMessageSize:UT,shimParameterlessSetLocalDescription:jT,shimRTCIceCandidate:kT,shimRTCIceCandidateRelayProtocol:MT,shimSendThrowTypeError:xT});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=yf,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Rf(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Rf(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=Rf(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:GT,extractVersion:Rf,disableLog:Cf,disableWarnings:If,sdp:LT};switch(n.browser){case"chrome":if(!Gf||!Bf||!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=Gf,BT(e,n),jT(e),Pf(e,n),Lf(e),Bf(e,n),kf(e),Ff(e,n),Mf(e),Uf(e),xf(e),jf(e,n),kT(e),MT(e),VT(e),UT(e,n),xT(e),FT(e,n);break;case"firefox":if(!eT||!Kf||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=eT,BT(e,n),jT(e),Wf(e,n),Kf(e,n),Hf(e),zf(e),Yf(e),qf(e),Xf(e),Jf(e),Qf(e),Zf(e),$f(e),kT(e),VT(e),UT(e,n),xT(e);break;case"safari":if(!lT||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=lT,BT(e,n),jT(e),sT(e),cT(e),nT(e),tT(e),iT(e),aT(e),rT(e),dT(e),kT(e),MT(e),UT(e,n),xT(e),FT(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var WT=be,HT=TypeError,KT=ce.match(/firefox\/(\d+)/i),YT=!!KT&&+KT[1],qT=/MSIE|Trident/.test(ce),zT=ce.match(/AppleWebKit\/(\d+)\./),XT=!!zT&&+zT[1],JT=wi,QT=d,ZT=De,$T=Xe,eS=Gi,tS=function(e,t){if(!delete e[t])throw HT("Cannot delete property "+WT(t)+" of "+WT(e))},iS=mn,nS=n,rS=Tp,oS=Bn,sS=YT,aS=qT,cS=Ee,dS=XT,lS=[],uS=QT(lS.sort),hS=QT(lS.push),pS=nS((function(){lS.sort(void 0)})),_S=nS((function(){lS.sort(null)})),ES=oS("sort"),mS=!nS((function(){if(cS)return cS<70;if(!(sS&&sS>3)){if(aS)return!0;if(dS)return dS<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++)lS.push({k:t+n,v:i})}for(lS.sort((function(e,t){return t.v-e.v})),n=0;niS(i)?1:-1}}(e)),i=eS(r),n=0;n0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r2&&(e[d]="iPad",e[u]=f),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,T,g.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,T,g.os),!e[l]&&S&&"Unknown"!=S.platform&&(e[l]=S.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return T},this.setUA=function(e){return T=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(T),this};J.VERSION="0.7.34",J.BROWSER=G([l,p,c]),J.CPU=G([_]),J.DEVICE=G([d,h,u,E,m,T,f,S,g]),J.ENGINE=J.OS=G([l,p]),e.exports&&(i=e.exports=J),i.UAParser=J;var Q=typeof t!==o&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new J;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:t)}(yS,yS.exports);var AS=i(yS.exports),bS=pn,wS=Ze,OS=Y,NS=Vo,DS=ht("iterator"),PS=Object,LS=function(e){if(OS(e))return!1;var t=PS(e);return void 0!==t[DS]||"@@iterator"in t||wS(NS,bS(t))},kS=i(LS),MS=bd.clear;wi({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==MS},{clearImmediate:MS});var US="function"==typeof Bun&&Bun&&"string"==typeof Bun.version,xS=h,VS=f,FS=w,BS=US,jS=ce,GS=Qc,WS=$c,HS=xS.Function,KS=/MSIE .\./.test(jS)||BS&&function(){var e=xS.Bun.version.split(".");return e.length<3||0==e[0]&&(e[1]<3||3==e[1]&&0==e[2])}(),YS=wi,qS=h,zS=bd.set,XS=function(e,t){var i=t?2:1;return KS?function(n,r){var o=WS(arguments.length,1)>i,s=FS(n)?n:HS(n),a=o?GS(arguments,i):[],c=o?function(){VS(s,this,a)}:s;return t?e(c,r):e(c)}:e},JS=qS.setImmediate?XS(zS,!1):zS;YS({global:!0,bind:!0,enumerable:!0,forced:qS.setImmediate!==JS},{setImmediate:JS});var QS=i(ie.setImmediate),ZS=wi,$S=el,eg=De,tg=$c,ig=jn,ng=h.process;ZS({global:!0,enumerable:!0,dontCallGetSet:!0},{queueMicrotask:function(e){tg(arguments.length,1),eg(e);var t=ig&&ng.domain;$S(t?t.bind(e):e)}});var rg=i(ie.queueMicrotask);function og(e,t){return function(){return e.apply(t,arguments)}}const{toString:sg}=Object.prototype,{getPrototypeOf:ag}=Object,cg=(dg=Object.create(null),e=>{const t=sg.call(e);return dg[t]||(dg[t]=t.slice(8,-1).toLowerCase())});var dg;const lg=e=>(e=e.toLowerCase(),t=>cg(t)===e),ug=e=>t=>typeof t===e,{isArray:hg}=Array,pg=ug("undefined");const _g=lg("ArrayBuffer");const Eg=ug("string"),mg=ug("function"),fg=ug("number"),Tg=e=>null!==e&&"object"==typeof e,Sg=e=>{if("object"!==cg(e))return!1;const t=ag(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||kS(e))},gg=lg("Date"),Rg=lg("File"),vg=lg("Blob"),Cg=lg("FileList"),Ig=lg("URLSearchParams"),[yg,Ag,bg,wg]=["ReadableStream","Request","Response","Headers"].map(lg);function Og(e,t){let i,n,{allOwnKeys:r=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null!=e)if("object"!=typeof e&&(e=[e]),hg(e))for(i=0,n=e.length;i0;)if(n=i[r],t===n.toLowerCase())return n;return null}const Dg=void 0!==IS?IS:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Pg=e=>!pg(e)&&e!==Dg;const Lg=(kg="undefined"!=typeof Uint8Array&&ag(Uint8Array),e=>kg&&e instanceof kg);var kg;const Mg=lg("HTMLFormElement"),Ug=(e=>{let{hasOwnProperty:t}=e;return(e,i)=>t.call(e,i)})(Object.prototype),xg=lg("RegExp"),Vg=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};Og(i,((i,r)=>{let o;!1!==(o=t(i,r,e))&&(n[r]=o||i)})),Object.defineProperties(e,n)},Fg="abcdefghijklmnopqrstuvwxyz",Bg="0123456789",jg={DIGIT:Bg,ALPHA:Fg,ALPHA_DIGIT:Fg+Fg.toUpperCase()+Bg};const Gg=lg("AsyncFunction"),Wg=(Hg="function"==typeof QS,Kg=mg(Dg.postMessage),Hg?QS:Kg?(Yg="axios@".concat(Math.random()),qg=[],Dg.addEventListener("message",(e=>{let{source:t,data:i}=e;t===Dg&&i===Yg&&qg.length&&qg.shift()()}),!1),e=>{qg.push(e),Dg.postMessage(Yg,"*")}):e=>setTimeout(e));var Hg,Kg,Yg,qg;const zg=void 0!==rg?rg.bind(Dg):"undefined"!=typeof process&&process.nextTick||Wg;var Xg={isArray:hg,isArrayBuffer:_g,isBuffer:function(e){return null!==e&&!pg(e)&&null!==e.constructor&&!pg(e.constructor)&&mg(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||mg(e.append)&&("formdata"===(t=cg(e))||"object"===t&&mg(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&_g(e.buffer),t},isString:Eg,isNumber:fg,isBoolean:e=>!0===e||!1===e,isObject:Tg,isPlainObject:Sg,isReadableStream:yg,isRequest:Ag,isResponse:bg,isHeaders:wg,isUndefined:pg,isDate:gg,isFile:Rg,isBlob:vg,isRegExp:xg,isFunction:mg,isStream:e=>Tg(e)&&mg(e.pipe),isURLSearchParams:Ig,isTypedArray:Lg,isFileList:Cg,forEach:Og,merge:function e(){const{caseless:t}=Pg(this)&&this||{},i={},n=(n,r)=>{const o=t&&Ng(i,r)||r;Sg(i[o])&&Sg(n)?i[o]=e(i[o],n):Sg(n)?i[o]=e({},n):hg(n)?i[o]=n.slice():i[o]=n};for(let e=0,t=arguments.length;e3&&void 0!==arguments[3]?arguments[3]:{};return Og(t,((t,n)=>{i&&mg(t)?e[n]=og(t,i):e[n]=t}),{allOwnKeys:n}),e},trim:e=>OT(e)?OT(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,n)=>{let r,o,s;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==i&&ag(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:cg,kindOfTest:lg,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(hg(e))return e;let t=e.length;if(!fg(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:Mg,hasOwnProperty:Ug,hasOwnProp:Ug,reduceDescriptors:Vg,freezeMethods:e=>{Vg(e,((t,i)=>{if(mg(e)&&-1!==["arguments","caller","callee"].indexOf(i))return!1;const n=e[i];mg(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))}))},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach((e=>{i[e]=!0}))};return hg(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:Ng,global:Dg,isContextDefined:Pg,ALPHABET:jg,generateString:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:jg.ALPHA_DIGIT,i="";const{length:n}=t;for(;e--;)i+=t[Math.random()*n|0];return i},isSpecCompliantForm:function(e){return!!(e&&mg(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(Tg(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const r=hg(e)?[]:{};return Og(e,((e,t)=>{const o=i(e,n+1);!pg(o)&&(r[t]=o)})),t[n]=void 0,r}}return e};return i(e,0)},isAsyncFn:Gg,isThenable:e=>e&&(Tg(e)||mg(e))&&mg(e.then)&&mg(e.catch),setImmediate:Wg,asap:zg};function Jg(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status?r.status:null)}Xg.inherits(Jg,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Xg.toJSONObject(this.config),code:this.code,status:this.status}}});const Qg=Jg.prototype,Zg={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Zg[e]={value:e}})),Object.defineProperties(Jg,Zg),Object.defineProperty(Qg,"isAxiosError",{value:!0}),Jg.from=(e,t,i,n,r,o)=>{const s=Object.create(Qg);return Xg.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Jg.call(s,e.message,t,i,n,r),s.cause=e,s.name=e.name,o&&Object.assign(s,o),s};function $g(e){return Xg.isPlainObject(e)||Xg.isArray(e)}function eR(e){return Xg.endsWith(e,"[]")?e.slice(0,-2):e}function tR(e,t,i){return e?e.concat(t).map((function(e,t){return e=eR(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}const iR=Xg.toFlatObject(Xg,{},null,(function(e){return/^is[A-Z]/.test(e)}));function nR(e,t,i){if(!Xg.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(i=Xg.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Xg.isUndefined(t[e])}))).metaTokens,r=i.visitor||d,o=i.dots,s=i.indexes,a=(i.Blob||"undefined"!=typeof Blob&&Blob)&&Xg.isSpecCompliantForm(t);if(!Xg.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Xg.isDate(e))return e.toISOString();if(!a&&Xg.isBlob(e))throw new Jg("Blob is not supported. Use a Buffer instead.");return Xg.isArrayBuffer(e)||Xg.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,i,r){let a=e;if(e&&!r&&"object"==typeof e)if(Xg.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(Xg.isArray(e)&&function(e){return Xg.isArray(e)&&!e.some($g)}(e)||(Xg.isFileList(e)||Xg.endsWith(i,"[]"))&&(a=Xg.toArray(e)))return i=eR(i),a.forEach((function(e,n){!Xg.isUndefined(e)&&null!==e&&t.append(!0===s?tR([i],n,o):null===s?i:i+"[]",c(e))})),!1;return!!$g(e)||(t.append(tR(r,i,o),c(e)),!1)}const l=[],u=Object.assign(iR,{defaultVisitor:d,convertValue:c,isVisitable:$g});if(!Xg.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!Xg.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),Xg.forEach(i,(function(i,o){!0===(!(Xg.isUndefined(i)||null===i)&&r.call(t,i,Xg.isString(o)?OT(o).call(o):o,n,u))&&e(i,n?n.concat(o):[o])})),l.pop()}}(e),t}function rR(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function oR(e,t){this._pairs=[],e&&nR(e,this,t)}const sR=oR.prototype;function aR(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function cR(e,t,i){if(!t)return e;const n=i&&i.encode||aR;Xg.isFunction(i)&&(i={serialize:i});const r=i&&i.serialize;let o;if(o=r?r(t,i):Xg.isURLSearchParams(t)?t.toString():new oR(t,i).toString(n),o){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}sR.append=function(e,t){this._pairs.push([e,t])},sR.toString=function(e){const t=e?function(t){return e.call(this,t,rR)}:rR;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var dR=class{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Xg.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},lR={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},uR={exports:{}},hR=wi,pR=N,_R=Qt.f;hR({target:"Object",stat:!0,forced:Object.defineProperty!==_R,sham:!pR},{defineProperty:_R});var ER=ie.Object,mR=uR.exports=function(e,t,i){return ER.defineProperty(e,t,i)};ER.defineProperty.sham&&(mR.sham=!0);var fR=i(uR.exports),TR=TypeError,SR=Qn,gR=Gc,RR=te,vR=ht("species"),CR=Array,IR=function(e){var t;return SR(e)&&(t=e.constructor,(gR(t)&&(t===CR||SR(t.prototype))||RR(t)&&null===(t=t[vR]))&&(t=void 0)),void 0===t?CR:t},yR=function(e,t){return new(IR(e))(0===t?0:t)},AR=n,bR=Ee,wR=ht("species"),OR=function(e){return bR>=51||!AR((function(){var t=[];return(t.constructor={})[wR]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},NR=wi,DR=n,PR=Qn,LR=te,kR=Xe,MR=Gi,UR=function(e){if(e>9007199254740991)throw TR("Maximum allowed index exceeded");return e},xR=sp,VR=yR,FR=OR,BR=Ee,jR=ht("isConcatSpreadable"),GR=BR>=51||!DR((function(){var e=[];return e[jR]=!1,e.concat()[0]!==e})),WR=function(e){if(!LR(e))return!1;var t=e[jR];return void 0!==t?!!t:PR(e)};NR({target:"Array",proto:!0,arity:1,forced:!GR||!FR("concat")},{concat:function(e){var t,i,n,r,o,s=kR(this),a=VR(s,0),c=0;for(t=-1,n=arguments.length;tT;T++)if((a||T in E)&&(p=m(h=E[T],T,_),e))if(t)g[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:pv(g,h)}else switch(e){case 4:return!1;case 7:pv(g,h)}return o?-1:n||r?r:g}},Ev={forEach:_v(0),map:_v(1),filter:_v(2),some:_v(3),every:_v(4),find:_v(5),findIndex:_v(6),filterReject:_v(7)},mv=wi,fv=h,Tv=L,Sv=d,gv=N,Rv=Se,vv=n,Cv=Ze,Iv=l,yv=ii,Av=Z,bv=vt,wv=mn,Ov=B,Nv=Io,Dv=to,Pv=Nr,Lv=HR,kv=jr,Mv=O,Uv=Qt,xv=Zr,Vv=k,Fv=pa,Bv=pc,jv=Ye,Gv=Dr,Wv=nt,Hv=ht,Kv=JR,Yv=iv,qv=av,zv=Pa,Xv=oa,Jv=Ev.forEach,Qv=ur("hidden"),Zv="Symbol",$v="prototype",eC=Xv.set,tC=Xv.getterFor(Zv),iC=Object[$v],nC=fv.Symbol,rC=nC&&nC[$v],oC=fv.TypeError,sC=fv.QObject,aC=Mv.f,cC=Uv.f,dC=Lv.f,lC=Vv.f,uC=Sv([].push),hC=jv("symbols"),pC=jv("op-symbols"),_C=jv("wks"),EC=!sC||!sC[$v]||!sC[$v].findChild,mC=gv&&vv((function(){return 7!=Nv(cC({},"a",{get:function(){return cC(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=aC(iC,t);n&&delete iC[t],cC(e,t,i),n&&e!==iC&&cC(iC,t,n)}:cC,fC=function(e,t){var i=hC[e]=Nv(rC);return eC(i,{type:Zv,tag:e,description:t}),gv||(i.description=t),i},TC=function(e,t,i){e===iC&&TC(pC,t,i),yv(e);var n=bv(t);return yv(i),Cv(hC,n)?(i.enumerable?(Cv(e,Qv)&&e[Qv][n]&&(e[Qv][n]=!1),i=Nv(i,{enumerable:Ov(0,!1)})):(Cv(e,Qv)||cC(e,Qv,Ov(1,{})),e[Qv][n]=!0),mC(e,n,i)):cC(e,n,i)},SC=function(e,t){yv(e);var i=Av(t),n=Dv(i).concat(CC(i));return Jv(n,(function(t){gv&&!Tv(gC,i,t)||TC(e,t,i[t])})),e},gC=function(e){var t=bv(e),i=Tv(lC,this,t);return!(this===iC&&Cv(hC,t)&&!Cv(pC,t))&&(!(i||!Cv(this,t)||!Cv(hC,t)||Cv(this,Qv)&&this[Qv][t])||i)},RC=function(e,t){var i=Av(e),n=bv(t);if(i!==iC||!Cv(hC,n)||Cv(pC,n)){var r=aC(i,n);return!r||!Cv(hC,n)||Cv(i,Qv)&&i[Qv][n]||(r.enumerable=!0),r}},vC=function(e){var t=dC(Av(e)),i=[];return Jv(t,(function(e){Cv(hC,e)||Cv(Gv,e)||uC(i,e)})),i},CC=function(e){var t=e===iC,i=dC(t?pC:Av(e)),n=[];return Jv(i,(function(e){!Cv(hC,e)||t&&!Cv(iC,e)||uC(n,hC[e])})),n};Rv||(nC=function(){if(Iv(rC,this))throw oC("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?wv(arguments[0]):void 0,t=Wv(e),i=function(e){this===iC&&Tv(i,pC,e),Cv(this,Qv)&&Cv(this[Qv],t)&&(this[Qv][t]=!1),mC(this,t,Ov(1,e))};return gv&&EC&&mC(iC,t,{configurable:!0,set:i}),fC(t,e)},Fv(rC=nC[$v],"toString",(function(){return tC(this).tag})),Fv(nC,"withoutSetter",(function(e){return fC(Wv(e),e)})),Vv.f=gC,Uv.f=TC,xv.f=SC,Mv.f=RC,Pv.f=Lv.f=vC,kv.f=CC,Kv.f=function(e){return fC(Hv(e),e)},gv&&Bv(rC,"description",{configurable:!0,get:function(){return tC(this).description}})),mv({global:!0,constructor:!0,wrap:!0,forced:!Rv,sham:!Rv},{Symbol:nC}),Jv(Dv(_C),(function(e){Yv(e)})),mv({target:Zv,stat:!0,forced:!Rv},{useSetter:function(){EC=!0},useSimple:function(){EC=!1}}),mv({target:"Object",stat:!0,forced:!Rv,sham:!gv},{create:function(e,t){return void 0===t?Nv(e):SC(Nv(e),t)},defineProperty:TC,defineProperties:SC,getOwnPropertyDescriptor:RC}),mv({target:"Object",stat:!0,forced:!Rv},{getOwnPropertyNames:vC}),qv(),zv(nC,Zv),Gv[Qv]=!0;var IC=Se&&!!Symbol.for&&!!Symbol.keyFor,yC=wi,AC=ae,bC=Ze,wC=mn,OC=Ye,NC=IC,DC=OC("string-to-symbol-registry"),PC=OC("symbol-to-string-registry");yC({target:"Symbol",stat:!0,forced:!NC},{for:function(e){var t=wC(e);if(bC(DC,t))return DC[t];var i=AC("Symbol")(t);return DC[t]=i,PC[i]=t,i}});var LC=wi,kC=Ze,MC=ye,UC=be,xC=IC,VC=Ye("symbol-to-string-registry");LC({target:"Symbol",stat:!0,forced:!xC},{keyFor:function(e){if(!MC(e))throw TypeError(UC(e)+" is not a symbol");if(kC(VC,e))return VC[e]}});var FC=Qn,BC=w,jC=R,GC=mn,WC=d([].push),HC=wi,KC=ae,YC=f,qC=L,zC=d,XC=n,JC=w,QC=ye,ZC=Qc,$C=function(e){if(BC(e))return e;if(FC(e)){for(var t=e.length,i=[],n=0;n=e.length;if(o=!o&&Xg.isArray(n)?n.length:o,a)return Xg.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!s;n[o]&&Xg.isObject(n[o])||(n[o]=[]);return t(e,i,n[o],r)&&Xg.isArray(n[o])&&(n[o]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let o;for(n=0;n{t(function(e){return nA(Xg).call(Xg,/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const oA={transitional:lR,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=Xg.isObject(e);r&&Xg.isHTMLForm(e)&&(e=new FormData(e));if(Xg.isFormData(e))return n?JSON.stringify(rA(e)):e;if(Xg.isArrayBuffer(e)||Xg.isBuffer(e)||Xg.isStream(e)||Xg.isFile(e)||Xg.isBlob(e)||Xg.isReadableStream(e))return e;if(Xg.isArrayBufferView(e))return e.buffer;if(Xg.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return nR(e,new ay.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return ay.isNode&&Xg.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((o=Xg.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return nR(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if(Xg.isString(e))try{return(t||JSON.parse)(e),OT(Xg).call(Xg,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||oA.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(Xg.isResponse(e)||Xg.isReadableStream(e))return e;if(e&&Xg.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw Jg.from(e,Jg.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ay.classes.FormData,Blob:ay.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Xg.forEach(["delete","get","head","post","put","patch"],(e=>{oA.headers[e]={}}));var sA=oA;const aA=Xg.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 cA=Symbol("internals");function dA(e){var t;return e&&OT(t=String(e)).call(t).toLowerCase()}function lA(e){return!1===e||null==e?e:Xg.isArray(e)?e.map(lA):String(e)}function uA(e,t,i,n,r){return Xg.isFunction(n)?n.call(this,t,i):(r&&(t=i),Xg.isString(t)?Xg.isString(n)?-1!==t.indexOf(n):Xg.isRegExp(n)?n.test(t):void 0:void 0)}class hA{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=dA(t);if(!r)throw new Error("header name must be a non-empty string");const o=Xg.findKey(n,r);(!o||void 0===n[o]||!0===i||void 0===i&&!1!==n[o])&&(n[o||t]=lA(e))}const o=(e,t)=>Xg.forEach(e,((e,i)=>r(e,i,t)));if(Xg.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(Xg.isString(e)&&(e=OT(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(OT(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=OT(o=e.substring(0,r)).call(o).toLowerCase(),n=OT(s=e.substring(r+1)).call(s),!i||t[i]&&aA[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t);else if(Xg.isHeaders(e))for(const[t,n]of e.entries())r(n,t,i);else null!=e&&r(t,e,i);var s;return this}get(e,t){if(e=dA(e)){const i=Xg.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(Xg.isFunction(t))return t.call(this,e,i);if(Xg.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=dA(e)){const i=Xg.findKey(this,e);return!(!i||void 0===this[i]||t&&!uA(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=dA(e)){const r=Xg.findKey(i,e);!r||t&&!uA(0,i[r],r,t)||(delete i[r],n=!0)}}return Xg.isArray(e)?e.forEach(r):r(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!uA(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return Xg.forEach(this,((n,r)=>{var o;const s=Xg.findKey(i,r);if(s)return t[s]=lA(n),void delete t[r];const a=e?function(e){return OT(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):OT(o=String(r)).call(o);a!==r&&delete t[r],t[a]=lA(n),i[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),i=0;i{null!=i&&!1!==i&&(t[n]=e&&Xg.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let[t,i]=e;return t+": "+i})).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e){const t=new this(e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;rt.set(e))),t}static accessor(e){const t=(this[cA]=this[cA]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=dA(e);t[n]||(!function(e,t){const i=Xg.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{value:function(e,i,r){return this[n].call(this,t,e,i,r)},configurable:!0})}))}(i,e),t[n]=!0)}return Xg.isArray(e)?e.forEach(n):n(e),this}}hA.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Xg.reduceDescriptors(hA.prototype,((e,t)=>{let{value:i}=e,n=t[0].toUpperCase()+t.slice(1);return{get:()=>i,set(e){this[n]=e}}})),Xg.freezeMethods(hA);var pA=hA;function _A(e,t){const i=this||sA,n=t||i,r=pA.from(n.headers);let o=n.data;return Xg.forEach(e,(function(e){o=e.call(i,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function EA(e){return!(!e||!e.__CANCEL__)}function mA(e,t,i){Jg.call(this,null==e?"canceled":e,Jg.ERR_CANCELED,t,i),this.name="CanceledError"}function fA(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Jg("Request failed with status code "+i.status,[Jg.ERR_BAD_REQUEST,Jg.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}Xg.inherits(mA,Jg,{__CANCEL__:!0});const TA=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-r1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,i=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[function(){const e=Date.now(),t=e-r;for(var a=arguments.length,c=new Array(a),d=0;d=o?s(c,e):(i=c,n||(n=setTimeout((()=>{n=null,s(i)}),o-t)))},()=>i&&s(i)]}((i=>{const o=i.loaded,s=i.lengthComputable?i.total:void 0,a=o-n,c=r(a);n=o;e({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:i,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),i)},SA=(e,t)=>{const i=null!=e;return[n=>t[0]({lengthComputable:i,total:e,loaded:n}),t[1]]},gA=e=>function(){for(var t=arguments.length,i=new Array(t),n=0;ne(...i)))};var RA=ay.hasStandardBrowserEnv?((e,t)=>i=>(i=new Tf(i,ay.origin),e.protocol===i.protocol&&e.host===i.host&&(t||e.port===i.port)))(new Tf(ay.origin),ay.navigator&&/(msie|trident)/i.test(ay.navigator.userAgent)):()=>!0,vA=ay.hasStandardBrowserEnv?{write(e,t,i,n,r,o){const s=[e+"="+encodeURIComponent(t)];Xg.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),Xg.isString(n)&&s.push("path="+n),Xg.isString(r)&&s.push("domain="+r),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function CA(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}function IA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const yA=e=>e instanceof pA?function(e){for(var t=1;tr(yA(e),yA(t),0,!0)};return Xg.forEach(Object.keys(Object.assign({},e,t)),(function(n){const o=c[n]||r,s=o(e[n],t[n],n);Xg.isUndefined(s)&&o!==a||(i[n]=s)})),i}var bA=e=>{const t=AA({},e);let i,{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=pA.from(a),t.url=cR(CA(t.baseURL,t.url),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Xg.isFormData(n))if(ay.hasStandardBrowserEnv||ay.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(i=a.getContentType())){const[e,...t]=i?i.split(";").map((e=>OT(e).call(e))).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ay.hasStandardBrowserEnv&&(r&&Xg.isFunction(r)&&(r=r(t)),r||!1!==r&&RA(t.url))){const e=o&&s&&vA.read(s);e&&a.set(o,e)}return t};var wA="undefined"!=typeof XMLHttpRequest&&function(e){return new Wh((function(t,i){const n=bA(e);let r=n.data;const o=pA.from(n.headers).normalize();let s,a,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=n;function _(){d&&d(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let E=new XMLHttpRequest;function m(){if(!E)return;const n=pA.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders());fA((function(e){t(e),_()}),(function(e){i(e),_()}),{data:u&&"text"!==u&&"json"!==u?E.response:E.responseText,status:E.status,statusText:E.statusText,headers:n,config:e,request:E}),E=null}E.open(n.method.toUpperCase(),n.url,!0),E.timeout=n.timeout,"onloadend"in E?E.onloadend=m:E.onreadystatechange=function(){E&&4===E.readyState&&(0!==E.status||E.responseURL&&0===E.responseURL.indexOf("file:"))&&setTimeout(m)},E.onabort=function(){E&&(i(new Jg("Request aborted",Jg.ECONNABORTED,e,E)),E=null)},E.onerror=function(){i(new Jg("Network Error",Jg.ERR_NETWORK,e,E)),E=null},E.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const r=n.transitional||lR;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),i(new Jg(t,r.clarifyTimeoutError?Jg.ETIMEDOUT:Jg.ECONNABORTED,e,E)),E=null},void 0===r&&o.setContentType(null),"setRequestHeader"in E&&Xg.forEach(o.toJSON(),(function(e,t){E.setRequestHeader(t,e)})),Xg.isUndefined(n.withCredentials)||(E.withCredentials=!!n.withCredentials),u&&"json"!==u&&(E.responseType=n.responseType),p&&([c,l]=TA(p,!0),E.addEventListener("progress",c)),h&&E.upload&&([a,d]=TA(h),E.upload.addEventListener("progress",a),E.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(s=t=>{E&&(i(!t||t.type?new mA(null,e,E):t),E.abort(),E=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const f=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);f&&-1===ay.protocols.indexOf(f)?i(new Jg("Unsupported protocol "+f+":",Jg.ERR_BAD_REQUEST,e)):E.send(r||null)}))};var OA=(e,t)=>{const{length:i}=e=e?e.filter(Boolean):[];if(t||i){let i,n=new AbortController;const r=function(e){if(!i){i=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof Jg?t:new mA(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>{o=null,r(new Jg("timeout ".concat(t," of ms exceeded"),Jg.ETIMEDOUT))}),t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)})),e=null)};e.forEach((e=>e.addEventListener("abort",r)));const{signal:a}=n;return a.unsubscribe=()=>Xg.asap(s),a}},NA=Gh,DA=gl;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=DA.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var PA=gl,LA=tl;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=PA.f(this),i=LA(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var kA=i(NA),MA=JR.f("asyncIterator"),UA=i(MA);function xA(e,t){this.v=e,this.k=t}function VA(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof xA;kA.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 kA((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 FA(e){return function(){return new VA(e.apply(this,arguments))}}function BA(e){return new xA(e,0)}function jA(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new xA(n=new kA((function(i){i(e[t](n))})),1)}}return t[void 0!==YI&&qI||"@@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}VA.prototype["function"==typeof YI&&UA||"@@asyncIterator"]=function(){return this},VA.prototype.next=function(e){return this._invoke("next",e)},VA.prototype.throw=function(e){return this._invoke("throw",e)},VA.prototype.return=function(e){return this._invoke("return",e)};var GA=i(MA);function WA(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=GA,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new HA(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function HA(e){function t(e){if(Object(e)!==e)return Wh.reject(new TypeError(e+" is not an object."));var t=e.done;return Wh.resolve(e.value).then((function(e){return{value:e,done:t}}))}return HA=function(e){this.s=e,this.n=e.next},HA.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Wh.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Wh.reject(e):t(i.apply(this.s,arguments))}},new HA(e)}const KA=function*(e,t){let i=e.byteLength;if(!t||i{const r=YA(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await r.next();if(t)return a(),void e.close();let o=n.byteLength;if(i){let e=s+=o;i(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})};function XA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function JA(e){for(var t=1;teb.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var eb;const tb=function(e){try{for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{let e=!1;const t=new Request(ay.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),nb=ZA&&tb((()=>Xg.isReadableStream(new Response("").body))),rb={stream:nb&&(e=>e.body)};var ob;QA&&(ob=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!rb[e]&&(rb[e]=Xg.isFunction(ob[e])?t=>t[e]():(t,i)=>{throw new Jg("Response type '".concat(e,"' is not supported"),Jg.ERR_NOT_SUPPORT,i)})})));const sb=async(e,t)=>{const i=Xg.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(Xg.isBlob(e))return e.size;if(Xg.isSpecCompliantForm(e)){const t=new Request(ay.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Xg.isArrayBufferView(e)||Xg.isArrayBuffer(e)?e.byteLength:(Xg.isURLSearchParams(e)&&(e+=""),Xg.isString(e)?(await $A(e)).byteLength:void 0)})(t):i};var ab=QA&&(async e=>{let{url:t,method:i,data:n,signal:r,cancelToken:o,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:h}=bA(e);d=d?(d+"").toLowerCase():"text";let p,_=OA([r,o&&o.toAbortSignal()],s);const E=_&&_.unsubscribe&&(()=>{_.unsubscribe()});let m;try{if(c&&ib&&"get"!==i&&"head"!==i&&0!==(m=await sb(l,n))){let e,i=new Request(t,{method:"POST",body:n,duplex:"half"});if(Xg.isFormData(n)&&(e=i.headers.get("content-type"))&&l.setContentType(e),i.body){const[e,t]=SA(m,TA(gA(c)));n=zA(i.body,65536,e,t)}}Xg.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;p=new Request(t,JA(JA({},h),{},{signal:_,method:i.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:r?u:void 0}));let o=await fetch(p);const s=nb&&("stream"===d||"response"===d);if(nb&&(a||s&&E)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=o[t]}));const t=Xg.toFiniteNumber(o.headers.get("content-length")),[i,n]=a&&SA(t,TA(gA(a),!0))||[];o=new Response(zA(o.body,65536,i,(()=>{n&&n(),E&&E()})),e)}d=d||"text";let f=await rb[Xg.findKey(rb,d)||"text"](o,e);return!s&&E&&E(),await new Wh(((t,i)=>{fA(t,i,{data:f,headers:pA.from(o.headers),status:o.status,statusText:o.statusText,config:e,request:p})}))}catch(t){if(E&&E(),t&&"TypeError"===t.name&&/fetch/i.test(t.message))throw Object.assign(new Jg("Network Error",Jg.ERR_NETWORK,e,p),{cause:t.cause||t});throw Jg.from(t,t&&t.code,e,p)}});const cb={http:null,xhr:wA,fetch:ab};Xg.forEach(cb,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const db=e=>"- ".concat(e),lb=e=>Xg.isFunction(e)||null===e||!1===e;var ub={getAdapter:e=>{e=Xg.isArray(e)?e:[e];const{length:t}=e;let i,n;const r={};for(let o=0;o{let[t,i]=e;return"adapter ".concat(t," ")+(!1===i?"is not supported by the environment":"is not available in the build")}));throw new Jg("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(db).join("\n"):" "+db(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:cb};function hb(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new mA(null,e)}function pb(e){hb(e),e.headers=pA.from(e.headers),e.data=_A.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ub.getAdapter(e.adapter||sA.adapter)(e).then((function(t){return hb(e),t.data=_A.call(e,e.transformResponse,t),t.headers=pA.from(t.headers),t}),(function(t){return EA(t)||(hb(e),t&&t.response&&(t.response.data=_A.call(e,e.transformResponse,t.response),t.response.headers=pA.from(t.response.headers))),Wh.reject(t)}))}const _b="1.7.9",Eb={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Eb[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const mb={};Eb.transitional=function(e,t,i){function n(e,t){return"[Axios v"+_b+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,r,o)=>{if(!1===e)throw new Jg(n(r," has been removed"+(t?" in "+t:"")),Jg.ERR_DEPRECATED);return t&&!mb[r]&&(mb[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)}},Eb.spelling=function(e){return(t,i)=>(console.warn("".concat(i," is likely a misspelling of ").concat(e)),!0)};var fb={assertOptions:function(e,t,i){if("object"!=typeof e)throw new Jg("options must be an object",Jg.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-- >0;){const o=n[r],s=t[o];if(s){const t=e[o],i=void 0===t||s(t,o,e);if(!0!==i)throw new Jg("option "+o+" must be "+i,Jg.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new Jg("Unknown option "+o,Jg.ERR_BAD_OPTION)}},validators:Eb};const Tb=fb.validators;let Sb=class{constructor(e){this.defaults=e,this.interceptors={request:new dR,response:new dR}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const i=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=AA(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&fb.assertOptions(i,{silentJSONParsing:Tb.transitional(Tb.boolean),forcedJSONParsing:Tb.transitional(Tb.boolean),clarifyTimeoutError:Tb.transitional(Tb.boolean)},!1),null!=n&&(Xg.isFunction(n)?t.paramsSerializer={serialize:n}:fb.assertOptions(n,{encode:Tb.function,serialize:Tb.function},!0)),fb.assertOptions(t,{baseUrl:Tb.spelling("baseURL"),withXsrfToken:Tb.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&Xg.merge(r.common,r[t.method]);r&&Xg.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete r[e]})),t.headers=pA.concat(o,r);const s=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,u=0;if(!a){const e=[pb.bind(this),void 0];for(e.unshift.apply(e,s),e.push.apply(e,c),l=e.length,d=Wh.resolve(t);u{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Wh((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new mA(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 Rb((function(t){e=t}));return{token:t,cancel:e}}}var vb=Rb;const Cb={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Cb).forEach((e=>{let[t,i]=e;Cb[i]=t}));var Ib=Cb;const yb=function e(t){const i=new gb(t),n=og(gb.prototype.request,i);return Xg.extend(n,gb.prototype,i,{allOwnKeys:!0}),Xg.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(AA(t,i))},n}(sA);yb.Axios=gb,yb.CanceledError=mA,yb.CancelToken=vb,yb.isCancel=EA,yb.VERSION=_b,yb.toFormData=nR,yb.AxiosError=Jg,yb.Cancel=yb.CanceledError,yb.all=function(e){return Wh.all(e)},yb.spread=function(e){return function(t){return e.apply(null,t)}},yb.isAxiosError=function(e){return Xg.isObject(e)&&!0===e.isAxiosError},yb.mergeConfig=AA,yb.AxiosHeaders=pA,yb.formToJSON=e=>rA(Xg.isHTMLForm(e)?new FormData(e):e),yb.getAdapter=ub.getAdapter,yb.HttpStatusCode=Ib,yb.default=yb;var Ab=yb;const bb=()=>{};function wb(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:bb};return e.promise=new Wh(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const Ob=new Map,Nb=new Map,Db=new Map;let Pb=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}({}),Lb=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 kb=new AS;let Mb=kb.getResult(),Ub=null;function xb(e){if(!Ub){e&&kb.setUA(e),Mb=kb.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return Lb.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return Lb.CHROME;case"Safari":case"Mobile Safari":return Lb.SAFARI;case"Edge":return Lb.EDGE;case"Firefox":return Lb.FIREFOX;case"QQ":case"QQBrowser":return Lb.QQ;case"Opera":return Lb.OPERA;case"WeChat":return Lb.WECHAT;default:return e.browser.name||""}}(Mb),i=Vb(Mb),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(Mb),r=Mb.os.version,o=Vb(Mb,!1),s=Mb.device.type;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s};Ub={name:t,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s}}return Ub}function Vb(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 Fb(){return xb().os}function Bb(){const e=xb();return"".concat(e.os," ").concat(e.osVersion)}function jb(){const e=xb();return!!("WebKit"===Mb.engine.name&&e.os===Pb.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Lb.SAFARI||Yb()&&e.name!==Lb.SAFARI)}function Gb(){return xb().name===Lb.CHROME}function Wb(){return xb().name===Lb.SAFARI}function Hb(){return xb().name===Lb.EDGE}function Kb(){return xb().name===Lb.FIREFOX}function Yb(){return xb().os===Pb.IOS}function qb(e){const t=xb();return!(t.name!==Lb.CHROME||!t.osVersion)&&Number(t.version)>=e}function zb(e){const t=xb();return!(t.name!==Lb.CHROME||!t.osVersion)&&Number(t.version)=t&&Number(n.version)<=i:Number(n.version)===t)}function Jb(e){const t=xb();return!(t.name!==Lb.EDGE||!t.osVersion)&&Number(t.version)>=e}function Qb(e){const t=xb();return!(t.name!==Lb.SAFARI||!t.osVersion)&&Number(t.version)>=e}function Zb(e,t,i){const n=xb();if(n.os!==Pb.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])=e}function tw(){const e=xb();if(e.os!==Pb.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function iw(){const e=xb();if(e.os!==Pb.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function nw(){const e=xb();if(e.os!==Pb.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function rw(){const e=xb();if(e.os!==Pb.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function ow(){return Wb()&&navigator.maxTouchPoints>0}function sw(){return xb().name===Lb.WECHAT}function aw(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function cw(){const e=Fb();return function(){const{deviceType:e}=xb();return"mobile"===e||"tablet"===e}()||e===Pb.ANDROID||e===Pb.IOS||e===Pb.HARMONY_OS}function dw(){const e=xb();return e.name!==Lb.EDGE&&e.name!==Lb.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function lw(){return Fb()===Pb.ANDROID}function uw(){const e=xb();return lw()&&(e.name===Lb.CHROME||e.name===Lb.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function hw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function pw(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),_w(this,"code",void 0),_w(this,"message",void 0),_w(this,"data",void 0),_w(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 fw(e,t){if("boolean"!=typeof e)throw new mw(Ew.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Tw(e,t,i){if(!Dn(i).call(i,e))throw new mw(Ew.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function Sw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(en||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new mw(Ew.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function gw(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new mw(Ew.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&Sw(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&Sw(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&Sw(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&Sw(e.ideal,"".concat(t,".ideal"),1,1/0)}else Sw(e,t,1,1/0)}function Rw(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 mw(Ew.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!Iw(e,i,n,r))throw new mw(Ew.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function vw(e,t){if(!Array.isArray(e))throw new mw(Ew.INVALID_PARAMS,"".concat(t," should be an array"))}function Cw(e){return null==e}function Iw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return!1;for(let t=0;t255)return!1}return!0}(e))}var yw=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(yw||{}),Aw=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(Aw||{});const bw=new class{constructor(){_w(this,"_clientSize",null),_w(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),_w(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),_w(this,"getStyle",(e=>window.getComputedStyle(e,null))),_w(this,"checkCssVisibleProperty",(e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:o,opacity:s,filter:a}=n;return("none"===r||Dn(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter((e=>{var t;const i=e.split("(")[0];return Dn(t=["brightness","blur","opacity"]).call(t,i)})).map((e=>{const[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1)}})),i)})),_w(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})),_w(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),_w(this,"getSizeAboutClient",(e=>{const{width:t,height:i,left:n,right:r,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),_w(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),_w(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),_w(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),_w(this,"getPointPositionList",(()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,o=t/6,s=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(o*t*a-1e5)/a:o*t)*a)/a;s.push({x:c,y:d})}return[...s]})),_w(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),_w(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),_w(this,"checkSizeOfPartInClient",(()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:o,clientMin:s}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e(this._clientSize=null,{visible:!1,reason:e}))),_w(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(yw.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(yw.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(yw.SIZE)}}return this.returnHiddenResult(yw.STYLE)}return this.returnHiddenResult(Aw.UNMOUNTED)}return this.returnHiddenResult(Aw.INVALID_HTML_ELEMENT)})),_w(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function ww(e){return(new TextEncoder).encode(e)}const Ow=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 Nw=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",ww(e)),16);let Dw=class{constructor(){_w(this,"_events",{}),_w(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r1?t-1:0),n=1;n{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}};let Pw=null;function Lw(){if(Pw)return Pw;if(window.electron)return Pw=window.electron;if(!window.require)return null;try{return Pw=window.require("electron"),Pw}catch(e){return null}}let kw=function(e){return e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.PRELOAD="PRELOAD",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload",e.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",e}({}),Mw=function(e){return e.TRACER="tracer",e}({});function Uw(e){return Sw(e.timeout,"config.timeout",0,1e5),Sw(e.timeoutFactor,"config.timeoutFactor",0,100,!1),Sw(e.maxRetryCount,"config.maxRetryConfig",0,1/0),Sw(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let xw=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}({}),Vw=function(e){return e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.FALLBACK="FALLBACK",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e}({});function Fw(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 Bw(e){return Rw(e.turnServerURL,"turnServerURL"),Rw(e.username,"username"),Rw(e.password,"password"),e.udpport&&Sw(e.udpport,"udpport",1,99999,!0),e.forceturn&&fw(e.forceturn,"forceturn"),e.security&&fw(e.security,"security"),e.tcpport&&Sw(e.tcpport,"tcpport",1,99999,!0),!0}function jw(e){return void 0!==e.level&&Tw(e.level,"level",[1,2,3]),void 0!==e.delay&&Sw(e.delay,"delay",0,3e3,!0),!0}let Gw=function(e){return e.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",e.AUDIO_METADATA="audio-metadata",e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",e}({}),Ww=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}({}),Hw=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),Kw=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function Yw(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r{e.emit(t,...n,i,r)}))}function qw(e,t){if(0===e.getListeners(t).length)return Wh.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r2?i-2:0),r=2;r2?r-2:0),s=2;s{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new mw(Ew.UNEXPECTED_ERROR,"handler is not sync");return i}const Jw=new class extends Dw{set networkState(e){this.emit(Kw.NETWORK_STATE_CHANGE,e,this._networkState),e===Hw.ONLINE?this.emit(Kw.ONLINE):e===Hw.OFFLINE&&(this.onlineWaiter=new Wh((e=>{this.once(Kw.ONLINE,(()=>{this.onlineWaiter=void 0,e(Hw.ONLINE)}))})),this.emit(Kw.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===Hw.ONLINE}constructor(){super(),_w(this,"_moduleName","network-indicator"),_w(this,"_networkState",Hw.ONLINE),_w(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=Hw.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=Hw.OFFLINE}))}};function Qw(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function Zw(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function $w(e){void 0!==Wh?Wh.resolve().then(e):setTimeout(e,0)}function eO(e){return JSON.parse(JSON.stringify(e))}function tO(e){try{return eO(e)}catch(t){return e}}const iO={};function nO(e,t){iO[t]||(iO[t]=!0,e())}function rO(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:16,i=(new TextEncoder).encode(e);if(i.length>t)i=i.slice(0,t);else if(i.lengthe+t.length),0),r=new Uint8Array(new ArrayBuffer(n));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function cO(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function dO(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?cO(e):e.size})),t+138}function lO(e){const t=new mw(Ew.TIMEOUT,"timeout");return new Wh(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function uO(e){return new Wh((t=>{window.setTimeout(t,e)}))}function hO(){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)+hO(e-i.length,"")}function pO(){return hO(32,"").toUpperCase()}const _O=()=>{},EO=new class{constructor(){_w(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:s,args:o,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,pw(pw({},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})}}},mO=EO.throttleByKey.bind(EO);function fO(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function TO(e,t){if(!fO(e)||!fO(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i}function gO(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function RO(e){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,o,s){return n(function(e,t){return e<>>32-t}(n(n(t,e),n(r,s)),o),i)}function o(e,t,i,n,o,s,a){return r(t&i|~t&n,e,t,o,s,a)}function s(e,t,i,n,o,s,a){return r(t&n|i&~n,e,t,o,s,a)}function a(e,t,i,n,o,s,a){return r(t^i^n,e,t,o,s,a)}function c(e,t,i,n,o,s,a){return r(i^(t|~n),e,t,o,s,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t>2]|=e.charCodeAt(t)<>2]|=128<0}lock(e){let t;this.locks+=1,this.logger("locked",e);const i=new Wh((i=>{t=()=>{this.locks-=1,this.logger("unlocked",e),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}};function yO(e,t){return function(i,n,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var s=arguments.length,a=new Array(s),c=0;c{await function(e){return new Wh((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new Wh((async(n,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;ca=!0,c}let OO,NO=class{constructor(e){_w(this,"input",[]),_w(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:Xn(e=this.input).call(e,((e,t)=>e+t))/this.input.length}},DO=0,PO=0;function LO(e,t,i,n){return new Wh(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),DO+=cO(t.data)):i&&(t.data.size?DO+=t.data.size:t.data instanceof FormData?DO+=dO(t.data):DO+=cO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Ab.request(t).then((e=>{"string"==typeof e.data?PO+=cO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?PO+=e.data.byteLength:PO+=cO(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Ab.isCancel(e)?o(new mw(Ew.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new mw(Ew.NETWORK_TIMEOUT,e.message)):e.response?o(new mw(Ew.NETWORK_RESPONSE_ERROR,e.response.status)):o(new mw(Ew.NETWORK_ERROR,e.message))}))}))}async function kO(e,t){const i=new Blob([t.data],{type:"buffer"});return await LO(e,pw(pw({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const MO=()=>void 0!==window.isSecureContext;function UO(e){if(Array.isArray(e))return e.map((e=>e));if(!xO(e))return e;const t={};for(const i in e){const n=e[i];xO(n)||Array.isArray(n)?t[i]=UO(n):t[i]=n}return t}function xO(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let VO=class{constructor(e){_w(this,"input",[]),_w(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 FO={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},BO={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:FO,remoteCandidate:FO},updateInterval:0},jO={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},GO={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},WO={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},HO={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0};let KO=class{constructor(e,t){_w(this,"onFirstVideoReceived",void 0),_w(this,"onFirstVideoDecoded",void 0),_w(this,"onFirstAudioReceived",void 0),_w(this,"onFirstVideoDecodedTimeout",void 0),_w(this,"onFirstAudioDecoded",void 0),_w(this,"onSelectedLocalCandidateChanged",void 0),_w(this,"onSelectedRemoteCandidateChanged",void 0),_w(this,"videoIsReady",!1),_w(this,"videoIsReady2",{}),_w(this,"pc",void 0),_w(this,"options",void 0),_w(this,"intervalTimer",void 0),_w(this,"stats",UO(BO)),_w(this,"isFirstVideoReceived",{}),_w(this,"isFirstVideoDecoded",{}),_w(this,"isFirstAudioReceived",{}),_w(this,"isFirstAudioDecoded",{}),_w(this,"isFirstVideoDecodedTimeout",{}),_w(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval((async()=>{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new Wh((e=>{e({local:pw({},FO),remote:pw({},FO)})}))}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)}},YO=class extends KO{constructor(){super(...arguments),_w(this,"_stats",BO),_w(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=UO(BO);const i=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(i);const n=t.find((e=>"VideoBwe"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=Dn(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=UO(GO);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=UO(jO),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case"audio_send":{const t=UO(WO);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new Wh(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}},qO=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),zO=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}({}),XO=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}({}),JO=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 QO=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(QO||{});function ZO(e,t,i,n){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:QO.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 $O=class extends KO{constructor(){super(...arguments),_w(this,"_stats",BO),_w(this,"report",void 0),_w(this,"lastDecodeVideoReceiverStats",new Map),_w(this,"lastVideoFramesRecv",new Map),_w(this,"lastVideoFramesSent",new Map),_w(this,"lastVideoFramesDecode",new Map),_w(this,"lastVideoFramesOutput",new Map),_w(this,"lastVideoJBDelay",new Map),_w(this,"lastAudioJBDelay",new Map),_w(this,"mediaBytesSent",new Map),_w(this,"mediaBytesRetransmit",new Map),_w(this,"mediaBytesTargetEncode",new Map),_w(this,"lastDecodeAudioReceiverStats",new Map),_w(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=UO(BO),this.report.forEach((e=>{switch(e.type){case JO.OUTBOUND:case JO.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===JO.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===JO.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case JO.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case JO.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:pw({},FO),remote:pw({},FO)};return e.forEach((i=>{let n;if(i.type===JO.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===JO.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===JO.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===JO.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===JO.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(pw({},t),pw({},this.stats.selectedCandidatePair.localCandidate)),e.type===JO.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(pw({},t),pw({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=UO(HO),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;const i=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=ZO(i,t,"totalProcessingDelay","jitterBufferEmittedCount",QO.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,pw({},t))}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=UO(jO),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;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,r=o-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCounte.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=ZO(null==i?void 0:i.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=ZO(null==i?void 0:i.stats,t,"totalProcessingDelay","framesDecodeCount",QO.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=ZO(null==i?void 0:i.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",QO.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=ZO(null==i?void 0:i.stats,t,"totalInterFrameDelay","framesDecodeCount",QO.kMillisecondsFromSeconds),n&&o-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:pw({},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=UO(GO),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new VO(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 VO(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 VO(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,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,JO.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=UO(WO),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,JO.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(Zh(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,i){var n,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,o,s,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(o=null==l?void 0:l.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,_=null!==(s=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if("number"==typeof h&&(i.totalSamplesReceived=h),u&&h&&(i.accelerateRate=u/h),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=E;let T=1920;m&&h&&(T=h/m/50,i.receivedFrames=Math.round(h/T)),f&&(i.droppedFrames=Math.round(f/T))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}},eN=class extends KO{updateStats(){return Wh.resolve()}};function tN(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 YO(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new $O(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof Wh||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new $O(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new eN(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}const iN="websdk_ng_install_id";function nN(){try{if(_N("INSTALL_ID"))return _N("INSTALL_ID");let e=window.localStorage.getItem(iN);return e||(e=pO(),window.localStorage.setItem(iN,e)),pN("INSTALL_ID",e),e}catch(e){return}}const rN=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.23.2"),oN=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let sN=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const aN=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=aN;const cN={ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,PRE_SUB_NUM:2,ENABLE_AUT_FEEDBACK:!1,SVC_EXTENDED:["VP9"]},dN={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},lN="v4.23.2-0-g1599fdac-dirty(3/4/2025, 5:13:36 PM)",uN={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,NEW_ICE_RESTART:!1,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",USE_TURN_IP:!1,NEW_TURN_MODE:void 0,NEW_FORCE_TURN:!1},hN=pw(pw(pw({},uN),{},{PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,SHOW_REPORT_USER_INVOKER_LOG:!0,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,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_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_METADATA:!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_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:dN,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},cN),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1},{INSTALL_ID:""});function pN(e,t,i){var n,r,o;Dn(n=Object.keys(hN)).call(n,e)&&(!i&&Dn(r=Object.keys(mN)).call(r,e)||(hN[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS_METADATA"!==e||!0!==t||(hN.ENABLE_ENCODED_TRANSFORM=!0,"ENABLE_AUDIO_PTS_METADATA"===e&&(hN.ENABLE_AUDIO_METADATA=!0)),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,hN.USE_NEW_NETWORK_CONFIG=o,o&&(hN.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],hN.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],hN.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],hN.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],hN.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",hN.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",hN.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(hN.ENABLE_INSTANT_VIDEO=!0,hN.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(hN.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(hN.NEW_TURN_MODE||(hN.NEW_TURN_MODE=4))))}function _N(e){return hN[e]}oN||(hN.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],hN.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],hN.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],hN.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],hN.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],hN.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],hN.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",hN.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",hN.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",hN.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",hN.AREAS=["NORTH_AMERICA","OVERSEA"]);let EN=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const mN={};var fN=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}(fN||{});let TN=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 SN=128,gN=96,RN=1e3,vN=10;let CN=0;var IN=(()=>{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 m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return h(e)||a(e)||"+"===e||"/"===e}function T(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function S(e){for(var t=1;t=0&&n<=255)return i;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i)}return"/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n!!OT(e).call(e))).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:n,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t=.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new I;for(;this.currentLinel(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLinel(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine2?i-2:0),r=2;rs)throw new Error("error in length, should be less or equal than ".concat(s," characters."));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error("Nothing to extract from attValue.");for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;ie!==o&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,o);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends C{constructor(e){super(),g(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach((e=>{let[t,i]=e.split("=");t=OT(t).call(t);const r="string"==typeof i?OT(i).call(i):null;"string"==typeof t&&t.length>0&&(n[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),n=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,"eol",r)}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){A(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map((e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map((e=>"".concat(o).concat(e))).join("")).concat(this.eol))).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map((e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map((e=>"".concat(o).concat(e.name).concat(e.value?"=".concat(e.value):"")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(o,"*"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>"".concat(o).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(o).concat(t).concat(o).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return i}printFmtp(e,t){if(!t)return"";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(o).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(o).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(o),n=t;return"trr-int"===n.type?i+="ttr-int".concat(o).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(o).concat(n.parameter),n.additional&&(i+="".concat(o).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(o).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new 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 yN(e){return IN.parse(e)}function AN(e,t){return IN.print(e,t)}var bN=Ji("Array").keys,wN=pn,ON=Ze,NN=l,DN=bN,PN=Array.prototype,LN={DOMTokenList:!0,NodeList:!0},kN=function(e){var t=e.keys;return e===PN||NN(PN,e)&&t===PN.keys||ON(LN,wN(e))?DN:t},MN=i(kN);function UN(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 xN(e){for(var t=1;tthis.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};class BN{constructor(e){VN(this,"logger",void 0),VN(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{for(const t in WN)if(Object.prototype.hasOwnProperty.call(WN,t)&&WN[t]===e)return t;return"DEFAULT"};const YN=new class{constructor(){VN(this,"proxyServerURL",void 0),VN(this,"logLevel",WN.DEBUG),VN(this,"uploadState","collecting"),VN(this,"uploadLogWaitingList",[]),VN(this,"uploadLogUploadingList",[]),VN(this,"uploadErrorCount",0),VN(this,"currentLogID",0),VN(this,"url",void 0),VN(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{this.log(...t)}),Date.now()-HN);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=jN()+" Agora-SDK [".concat(KN(n),"]:"),this.appendLogToWaitingList(n,...t),n{this.uploadLog(...t)}),Date.now()-HN);const n=Math.max(0,Math.min(4,t[0]));t[0]=jN()+" Agora-SDK [".concat(KN(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!_N("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:rN,process_id:_N("PROCESS_ID"),payload:JSON.stringify(e)};return wO((async()=>{const e=await Ab.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(_N("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(_N("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),FN.reportLogUploadError(i),!0}),{timeout:_N("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:_N("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,_N("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),_N("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),_N("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),_N("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var qN;function zN(e){return Rw(e.reportId,"params.reportId",0,100,!1),Rw(e.category,"params.category",0,100,!1),Rw(e.event,"params.event",0,100,!1),Rw(e.label,"params.label",0,100,!1),Sw(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(qN={}).FREE="free",qN.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}({});const XN={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let JN=function(e){return e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",e.AB_TEST="ab_test",e}({}),QN=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",e.AB_TEST="io.agora.pb.Wrtc.ABTest",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let ZN=function(e){return e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",e}({});function $N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t,n=arguments.length,s=new Array(n),a=0;a(d.onSuccess(e.reportResult&&t),t))).catch((e=>{throw d.onError(e),e})):(d.onSuccess(e.reportResult&&t),t)}catch(e){throw d.onError(e),e}}}return n}}const eD=new class{constructor(){VN(this,"baseInfoMap",new Map),VN(this,"proxyServer",void 0),VN(this,"eventUploadTimer",void 0),VN(this,"setSessionIdTimer",void 0),VN(this,"url",void 0),VN(this,"sids",new Set),VN(this,"backupUrl",void 0),VN(this,"_appId",void 0),VN(this,"_aid",0),VN(this,"keyEventUploadPendingItems",[]),VN(this,"normalEventUploadPendingItems",[]),VN(this,"apiInvokeUploadPendingItems",[]),VN(this,"apiInvokeCount",0),VN(this,"apiInvokeLoggedCount",0),VN(this,"ltsList",[]),VN(this,"lastSendNormalEventTime",Date.now()),VN(this,"customReportCounterTimer",void 0),VN(this,"customReportCount",0),VN(this,"extApiInvoke",(async e=>{for(const t of e){const e=xN(xN({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:Mw.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),_N("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),_N("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,(e=>{let[t,i]=e;return t+i})),16)||0}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!_N("SHOW_REPORT_INVOKER_LOG"),s=!!_N("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,"]");t.id&&(n+="[".concat(t.id,"]")),t.name&&(n+="[".concat(t.name,"]")),YN.info("".concat(n," ").concat(e),"start"===e?t.options:i||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null});d("start");let u=!1;uO(t.timeout).then((()=>{u||(this.sendApiInvoke(xN(xN({},l()),{},{error:Ew.API_INVOKE_TIMEOUT,success:!1})),d("timeout"))}));const h=new mw(Ew.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(xN(xN({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return i?mO(n,t.name+"Success",i,(()=>u=!0)):n()},onError:e=>{const n=()=>{if(u)throw e;u=!0,this.sendApiInvoke(xN(xN({},l()),{},{success:!1,error:e})),d("onFailure",e.toString())};return i?mO(n,t.name+"Error",i,(()=>u=!0)):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:_N("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:oN?"global":"oversea",areas:_N("AREAS")&&_N("AREAS").join(",")},t.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=xN(xN({},n),{},{eventType:JN.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:lN,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:_N("PROCESS_ID"),appType:_N("APP_TYPE"),success:!0,version:rN,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:Dn(p=window.navigator.userAgent).call(p,"AgoraWebView")?42:20,clientRole:l,serviceId:_N("PROCESS_ID"),extensionID:_N("PLUGIN_INFO").join(",")||""});var p;this.send({type:QN.SESSION,data:h},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=xN(xN({},n),{},{role:t.role,eventType:JN.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});this.send({type:QN.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=xN(xN({},n),{},{eventType:JN.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:QN.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:o,avoidJoinStartTime:s,addr:a,isProxy:c}=t,d=r-(o&&s?s:i.startTime),l=xN(xN({},n),{},{eventType:JN.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:d,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:nN(),isABTestSuccess:t.isABTestSuccess?1:0}),u=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),o)this.send({type:QN.JOIN_GATEWAY,data:l},!0);else{let e;if(a)if(c){const t=a.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=a.match(/p=[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:c?1:0}}else{const t=a.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=a.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(/:|p=/g)[1]:"",isProxy:c?1:0}}else e={isSuccess:u,gatewayIp:"",port:"",isProxy:c?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:JN.REJOIN_GATEWAY});this.send({type:QN.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=xN(xN({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:QN.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=xN(xN({},n),{},{eventType:JN.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:QN.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=xN(xN({},r),{},{eventType:JN.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:QN.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...MN(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=xN(xN({},o),{},{eventType:JN.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:QN.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=xN(xN(xN({},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=xN(xN(xN({},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=xN(xN(xN({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:JN.AB_TEST,lts:r});this.send({type:QN.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=xN(xN(xN({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:JN.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:QN.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=xN(xN(xN({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:JN.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:QN.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=xN(xN(xN({},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=xN(xN({},n),{},{eventType:JN.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:QN.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=xN(xN({},n),{},{eventType:JN.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:QN.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=xN(xN({},n),{},{eventType:JN.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:QN.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?YN.debug("reportProxyServerurl: ".concat(e)):YN.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=xN(xN({},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:QN.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=cO(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;cthis.send({type:QN.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=xN(xN(xN({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:QN.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=xN(xN(xN({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:QN.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=xN(xN(xN({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:QN.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>_N("CUSTOM_REPORT_LIMIT"))throw new mw(Ew.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:QN.USER_ANALYTICS,data:xN(xN({sid:e},t),{},{lts:i})})));try{_N("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw YN.error("send custom report message failed",e.toString()),new mw(Ew.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=_N("NOT_REPORT_EVENT");if(e.tag&&Dn(t)&&Dn(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:o}=i.info;let s;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof mw){const{code:t,message:i}=e.error;s=t||i||e.error.toString()}else s=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:o,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?s:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:QN.API_INVOKE,data:a},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){const e=this.apiInvokeUploadPendingItems;if(0===e.length)return;const t=Array.from(this.sids).find((e=>null!==e));t&&e.forEach((e=>{e&&(e.sid=t,this.sendApiInvoke(Object.assign({},e)))})),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>_N("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),vS(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),_N("ENABLE_EVENT_REPORT")?(i.length&&(_N("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{_N("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>_N("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-_N("NORMAL_EVENT_QUEUE_CAPACITY")),YN.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){Jw.networkState===Hw.OFFLINE&&await Wh.race([Jw.onlineWaiter,uO(2*AO.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=ww(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(QN).forEach((i=>{let[n,r]=i;r===e.type&&(t=ZN[n])})),t})(e),o=new DataView(n);o.setUint16(0,i.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=Ow(t,new Uint8Array(n)),t=Ow(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(_N("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(_N("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(_N("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(_N("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await LO(n,{timeout:1e4,data:t(e),headers:xN(xN({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};Jw.networkState===Hw.OFFLINE&&await Wh.race([Jw.onlineWaiter,uO(2*AO.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(_N("EVENT_REPORT_DOMAIN"),"&p=").concat(_N("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(_N("EVENT_REPORT_DOMAIN"),":").concat(_N("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(_N("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(_N("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(_N("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(_N("STATS_COLLECTOR_PORT")).concat(o)));try{t?await kO(s,{timeout:1e4,data:r}):await LO(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},XN);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:Mw.TRACER}).onSuccess()}};FN.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=Jw.networkState,eD.reportApiInvoke(null,{name:"logUploadError",options:e,tag:Mw.TRACER}).onSuccess("logUploadError")}));class tD extends mw{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),VN(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,YN)}throw(){super.throw(YN)}}const iD={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function nD(){return iD}function rD(){return"setSinkId"in HTMLAudioElement.prototype&&(!_N("RESTRICTION_SET_PLAYBACK_DEVICE")||(Gb()||Hb())&&!cw())}function oD(){return!iD.supportUnifiedPlan||_N("CHROME_FORCE_PLAN_B")&&dw()}let sD=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 aD(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function cD(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function dD(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function lD(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const uD={"90p":cD(160,90),"90p_1":cD(160,90),"120p":cD(160,120,15,30,65),"120p_1":cD(160,120,15,30,65),"120p_3":cD(120,120,15,30,50),"120p_4":cD(212,120),"180p":cD(320,180,15,30,140),"180p_1":cD(320,180,15,30,140),"180p_3":cD(180,180,15,30,100),"180p_4":cD(240,180,15,30,120),"240p":cD(320,240,15,40,200),"240p_1":cD(320,240,15,40,200),"240p_3":cD(240,240,15,40,140),"240p_4":cD(424,240,15,40,220),"360p":cD(640,360,15,80,400),"360p_1":cD(640,360,15,80,400),"360p_3":cD(360,360,15,80,260),"360p_4":cD(640,360,30,80,600),"360p_6":cD(360,360,30,80,400),"360p_7":cD(480,360,15,80,320),"360p_8":cD(480,360,30,80,490),"360p_9":cD(640,360,15,80,800),"360p_10":cD(640,360,24,80,800),"360p_11":cD(640,360,24,80,1e3),"480p":cD(640,480,15,100,500),"480p_1":cD(640,480,15,100,500),"480p_2":cD(640,480,30,100,1e3),"480p_3":cD(480,480,15,100,400),"480p_4":cD(640,480,30,100,750),"480p_6":cD(480,480,30,100,600),"480p_8":cD(848,480,15,100,610),"480p_9":cD(848,480,30,100,930),"480p_10":cD(640,480,10,100,400),"720p":cD(1280,720,15,120,1130),"720p_auto":cD(1280,720,30,900,3e3),"720p_1":cD(1280,720,15,120,1130),"720p_2":cD(1280,720,30,120,2e3),"720p_3":cD(1280,720,30,120,1710),"720p_5":cD(960,720,15,120,910),"720p_6":cD(960,720,30,120,1380),"1080p":cD(1920,1080,15,120,2080),"1080p_1":cD(1920,1080,15,120,2080),"1080p_2":cD(1920,1080,30,120,3e3),"1080p_3":cD(1920,1080,30,120,3150),"1080p_5":cD(1920,1080,60,120,4780),"1440p":cD(2560,1440,30,120,4850),"1440p_1":cD(2560,1440,30,120,4850),"1440p_2":cD(2560,1440,60,120,7350),"4k":cD(3840,2160,30,120,8910),"4k_1":cD(3840,2160,30,120,8910),"4k_3":cD(3840,2160,60,120,13500)},hD={"480p":dD(640,480,5),"480p_1":dD(640,480,5),"480p_2":dD(640,480,30),"480p_3":dD(640,480,15),"720p":dD(1280,720,5),"720p_auto":cD(1280,720,30,900,3e3),"720p_1":dD(1280,720,5),"720p_2":dD(1280,720,30),"720p_3":dD(1280,720,15),"1080p":dD(1920,1080,5),"1080p_1":dD(1920,1080,5),"1080p_2":dD(1920,1080,30),"1080p_3":dD(1920,1080,15)},pD={"1SL1TL":lD(1,1),"3SL3TL":lD(3,3),"2SL3TL":lD(2,3)};function _D(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},uD[e]):e}function ED(e){return"string"==typeof e?Object.assign({},hD[e]):e}function mD(e){return"string"==typeof e?Object.assign({},pD[e]):e}const fD={speech_low_quality:aD(16e3,!1),speech_standard:aD(32e3,!1,18),music_standard:aD(48e3,!1),standard_stereo:aD(48e3,!0,56),high_quality:aD(48e3,!1,128),high_quality_stereo:aD(48e3,!0,192)};function TD(e){return"string"==typeof e?Object.assign({},fD[e]):e}const SD=[];function gD(e){return Tw(e,"mediaSource",["screen","window","application"]),!0}let RD=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),vD=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 CD=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),ID=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}({}),yD=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}({}),AD=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}({}),bD=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}({}),wD=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}({}),OD=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),ND=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 DD={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},PD={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},LD={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},kD={uplinkNetworkQuality:0,downlinkNetworkQuality:0},MD={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 UD=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),xD=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),VD=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),FD=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),BD=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}({}),jD=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 GD={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let WD=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function HD(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 KD(e){for(var t=1;t{var e;eD.reportApiInvoke(null,{name:kw.GET_MEDIA_STREAM_TRACK,options:[],tag:Mw.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===CD.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=SD.indexOf(e);-1!==t&&SD.splice(t,1)}(this),this.emit(bD.CLOSED),this.removeAllListeners(AD.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===CD.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(AD.TRANSCEIVER_UPDATED,e,t)}}class XD extends zD{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),YD(this,"_enabled",!0),YD(this,"_muted",!1),YD(this,"_isExternalTrack",!1),YD(this,"_isClosed",!1),YD(this,"_enabledMutex",void 0),YD(this,"processor",void 0),YD(this,"_processorContext",void 0),YD(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new IO("".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,YN.debug("[".concat(this.getTrackId(),"] close")),this.emit(RD.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 qw(this,RD.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){YN.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(bD.TRACK_ENDED)}stateCheck(e,t){if(YN.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),fw(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new mw(Ew.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",YN);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new mw(Ew.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",YN)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Wh.resolve([])}}const JD=window.AudioContext||window.webkitAudioContext;let QD=null;const ZD=new class extends Dw{constructor(){super(...arguments),YD(this,"prevState",void 0),YD(this,"curState",void 0),YD(this,"currentTime",void 0),YD(this,"currentTimeStuckAt",void 0),YD(this,"interruptDetectorTrack",void 0),YD(this,"onLocalAudioTrackMute",(()=>{YN.info("ios15-interruption-start"),this.emit(sD.IOS_15_16_INTERRUPTION_START)})),YD(this,"onLocalAudioTrackUnmute",(async()=>{YN.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?YN.info("ios15-interruption-end-canceled"):(QD&&await QD.suspend(),this.emit(sD.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){YN.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){YN.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 $D(){if(!QD){if(function(){if(!JD)return void YN.error("your browser is not support web audio");YN.info("create audio context");const e=KD({},_N("WEBAUDIO_INIT_OPTIONS"));YN.debug("audio context init option:",JSON.stringify(e)),QD=new JD(e),ZD.curState=QD.state,QD.onstatechange=()=>{ZD.prevState=ZD.curState,ZD.curState=QD?QD.state:void 0;const{prevState:e,curState:t}=ZD,i="running"===t,n="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=xb().osVersion;(Yb()||ow())&&r&&n&&(YN.info("ios".concat(a,"-interruption-start")),ZD.emit(sD.IOS_INTERRUPTION_START)),(Yb()||ow())&&(o||s)&&i&&(YN.info("ios".concat(a,"-interruption-end")),ZD.emit(sD.IOS_INTERRUPTION_END)),e!==t&&ZD.emit(sD.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=QD)||void 0===e?void 0:e.currentTime;ZD.currentTime!==t?(ZD.currentTimeStuckAt&&(YN.debug("AudioContext current time resume at ".concat(t)),ZD.currentTimeStuckAt=void 0),ZD.currentTime=t):(t!==ZD.currentTimeStuckAt&&(eD.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:Mw.TRACER}).onSuccess(),YN.warning("AudioContext current time stuck at ".concat(t))),ZD.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,o=!1;function s(t){"running"===e.state?a(!1):Yb()||ow()?"suspended"===e.state&&(a(!0),t&&e.resume().then(c,c)):"closed"!==e.state&&(a(!0),t&&e.resume().then(c,c))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,l(!0)}ZD.on(sD.STATE_CHANGE,(function(){s(!0)})),s(!1)}(QD)}(),!QD)throw new mw(Ew.NOT_SUPPORTED,"can not create audio context");return QD}return QD}function eP(e){if(function(){if(null!==tP)return tP;const e=$D(),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(),tP=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Dn(o=e._inputNodes).call(o,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,o)=>{i.call(e),n?Qw(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let tP=null;function iP(e,t){let i=!1;const n=1/t;if(_N("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=$D();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 nP{constructor(){YD(this,"context",void 0),YD(this,"analyserNode",void 0),YD(this,"sourceNode",void 0),this.context=$D(),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||Yb()||ow()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;ie+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){YN.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class rP extends Dw{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(),YD(this,"outputNode",void 0),YD(this,"outputTrack",void 0),YD(this,"isPlayed",!1),YD(this,"sourceNode",void 0),YD(this,"context",void 0),YD(this,"audioBufferNode",void 0),YD(this,"destNode",void 0),YD(this,"audioOutputLevel",0),YD(this,"volumeLevelAnalyser",void 0),YD(this,"_processedNode",void 0),YD(this,"playNode",void 0),YD(this,"isDestroyed",!1),YD(this,"onNoAudioInput",void 0),YD(this,"isNoAudioInput",!1),YD(this,"_noAudioInputCount",0),this.context=$D(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),eP(this.outputNode),this.volumeLevelAnalyser=new nP}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(ND.ON_AUDIO_BUFFER,function(e){for(let t=0;t{ZD.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;Yb()||ow()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e{if(YN.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 YN.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>YN.info("resume success"))),YN.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),eP(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),eP(this.outputNode),this.emit(ND.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new mw(Ew.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),eP(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,YN.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]));eP(t),this.originVolumeLevelAnalyser=new nP,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=xb();t&&o.os===Pb.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(ZD.on(sD.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),eP(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(ND.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),ZD.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),YN.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]));eP(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function sP(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 aP(e,t){const i=await cP(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Wh(((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e)};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(o),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='
'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await sP(n,e,r)}async function cP(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=Lw();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new mw(Ew.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new Wh(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new mw(Ew.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const dP=new IO("safari");let lP=!1,uP=!1;async function hP(e,t){let i=0,n=null;for(;i<2;)try{n=await pP(e,t,i>0);break}catch(e){if(e instanceof mw)throw YN.error("[".concat(t,"] ").concat(e.toString())),e;const n=_P(e.name||e.code||e,e.message);if(n.code===Ew.MEDIA_OPTION_INVALID){YN.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await uO(500);continue}throw YN.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new mw(Ew.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function pP(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new mw(Ew.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=nD(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return YN.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(Lw())e.screen.sourceId?EP(r,await sP(e.screen.sourceId,e.screen,!!e.screenAudio)):EP(r,await aP(e.screen,!!e.screenAudio));else if(Gb()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new mw(Ew.NOT_SUPPORTED,"This browser does not support screen sharing");YN.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(s=e.screen.extensionId,a=t,new Wh(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(i=>{if(!i||!i.streamId)return YN.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new mw(Ew.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){YN.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new mw(Ew.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,EP(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&gD(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c}=e.screen,d={selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c};!n&&delete d.selfBrowserSurface,!s&&delete d.surfaceSwitching,!a&&delete d.systemAudio,!c&&delete d.preferCurrentTab,YN.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:e.screenAudio,controls:d})),EP(r,await navigator.mediaDevices.getDisplayMedia(KD({video:i,audio:e.screenAudio},d)))}else{if(!Kb())throw YN.error("[".concat(t,"] This browser does not support screenSharing")),new mw(Ew.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&gD(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};YN.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),EP(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=_N("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=TO(c,d)}catch(e){}YN.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),xb();let l,u=null;(Wb()||Yb()||jb())&&(u=await dP.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(lP=!0),c.video&&(uP=!0),EP(r,l),u&&u(),r}function _P(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new mw(Ew.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new mw(Ew.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new mw(Ew.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new mw(Ew.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new mw(Ew.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new mw(Ew.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return YN.error("getUserMedia unexpected error",e),new mw(Ew.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function EP(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 mP=new class extends Dw{get state(){return this._state}set state(e){e!==this._state&&(this.emit(FD.STATE_CHANGE,e),this._state=e)}constructor(){super(),YD(this,"_state",VD.IDLE),YD(this,"isAccessMicrophonePermission",!1),YD(this,"isAccessCameraPermission",!1),YD(this,"lastAccessMicrophonePermission",!1),YD(this,"lastAccessCameraPermission",!1),YD(this,"checkdeviceMatched",!1),YD(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(_N("ENUMERATE_DEVICES_INTERVAL")||(lw()||Fb()===Pb.HARMONY_OS)&&dw())&&this.updateDevicesInfo()}),_N("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>YN.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new mw(Ew.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!i&&(o||s)){if(dP.isLocked&&(YN.debug("[device manager] wait GUM lock"),(await dP.lock())(),YN.debug("[device manager] GUM unlock")),lP&&(o=!1,this.isAccessMicrophonePermission=!0),uP&&(s=!1,this.isAccessCameraPermission=!0),YN.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=_P(e.name||e.code||e,e.message);if(t.code===Ew.PERMISSION_DENIED)throw t;YN.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=_P(e.name||e.code||e,e.message);if(t.code===Ew.PERMISSION_DENIED)throw t;YN.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=_P(e.name||e.code||e,e.message);if(t.code===Ew.PERMISSION_DENIED)throw t;YN.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}YN.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 mw(Ew.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 mw(Ew.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=VD.INITING;try{await this.updateDevicesInfo(),this.state=VD.INITEND}catch(e){throw YN.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=VD.IDLE,("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)||new mw(Ew.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?YN.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):YN.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):YN.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!==VD.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(FD.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(FD.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(FD.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 fP=!1;const TP=new class extends Dw{constructor(){super(...arguments),YD(this,"onAutoplayFailed",void 0),YD(this,"onAudioAutoplayFailed",void 0)}};function SP(){if(xb(),!fP){const e=t=>{t.preventDefault(),fP=!1,uw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};fP=!0,uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),YN.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),TP.onAutoplayFailed?TP.onAutoplayFailed():TP.onAudioAutoplayFailed?YN.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 ."):YN.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 ."),TP.emit("autoplay-failed")}}function gP(e,t,i,n){if(!e)return;const r=eD.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=KD(KD({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:TP.onAutoplayFailed||TP.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});eD.send({type:QN.AUTOPLAY_FAILED,data:a},!0)}const RP=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],vP=new class{constructor(){YD(this,"onAutoplayFailed",void 0),YD(this,"elementMap",new Map),YD(this,"elementStateMap",new Map),YD(this,"elementsNeedToResume",[]),YD(this,"sinkIdMap",new Map),YD(this,"autoResumeAfterInterruption",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,n]=t;const r=this.elementStateMap.get(i),o=n.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(YN.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(e)),"live"===s){if(e)return n.pause(),void n.play();if("running"===ZD.curState)return iw()?(n.pause(),void n.play()):void(r&&"paused"===r&&n.play())}}))})),YD(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(YN.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),ZD.on(sD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ZD.on(sD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),ZD.on(sD.STATE_CHANGE,(()=>{Yb()&&"suspended"===ZD.prevState&&"running"===ZD.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 mw(Ew.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,BD.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{YN.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){YN.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{n&&gP(n,"audio",e.message,t),YN.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(YN.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),$w((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),SP()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){RP.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(YN.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&YN.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{YN.debug("Auto resume audio element success")})).catch((e=>{YN.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new Wh((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function CP(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new mw(Ew.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",YN);for(var e=arguments.length,t=new Array(e),i=0;i{r.then(e).catch(t)})):r}),i}}class IP extends Dw{constructor(e){super(),YD(this,"name","VideoProcessorDestination"),YD(this,"ID","0"),YD(this,"_source",void 0),YD(this,"videoContext",void 0),YD(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new mw(Ew.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new mw(Ew.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(UD.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(UD.ON_TRACK,void 0)}}class yP extends Dw{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),YD(this,"constraintsMap",new Map),YD(this,"statsRegistry",[]),YD(this,"usageRegistry",[]),YD(this,"trackId",void 0),YD(this,"direction",void 0),YD(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await Yw(this,xD.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return YN.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),qw(this,xD.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return YN.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),qw(this,xD.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){YN.error(new mw(Ew.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Wh&&(i=await i),e.push(KD(KD({},i),{},{direction:this.direction}))}catch(e){YN.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class AP extends Dw{constructor(e){super(),YD(this,"name","AudioProcessorDestination"),YD(this,"ID","0"),YD(this,"inputTrack",void 0),YD(this,"inputNode",void 0),YD(this,"audioProcessorContext",void 0),YD(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new mw(Ew.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new mw(Ew.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(UD.ON_TRACK,void 0),this.emit(UD.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(UD.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(UD.ON_NODE,this.inputNode))}}class bP extends Dw{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),YD(this,"constraintsMap",new Map),YD(this,"statsRegistry",[]),YD(this,"audioContext",void 0),YD(this,"trackId",void 0),YD(this,"direction",void 0),YD(this,"usageRegistry",[]),YD(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return Yw(this,xD.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return YN.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),qw(this,xD.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),qw(this,xD.REQUEST_UPDATE_CONSTRAINTS,Array.from(Zh(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){YN.error(new mw(Ew.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Wh&&(i=await i),e.push(KD(KD({},i),{},{direction:this.direction}))}catch(e){YN.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class wP extends Dw{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),YD(this,"context",void 0),YD(this,"processSourceNode",void 0),YD(this,"outputTrack",void 0),YD(this,"processedNode",void 0),YD(this,"clonedTrack",void 0),YD(this,"outputNode",void 0),this.outputNode=new OP}setVolume(){}createOutputTrack(){throw new mw(Ew.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 OP{disconnect(){}connect(){}}function NP(e){return new Wh(((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=Yb()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&Kb()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(_O),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function DP(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=_D(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!aw()&&i.frameRate&&(t.frameRate=i.frameRate),Hb()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Kb()&&(t.frameRate={ideal:30,max:30}),t}function PP(e){const t={};return aw()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Gb()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function LP(e){const t=PP(e);if(e.encoderConfig){const i=TD(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),lw()&&(t.sampleRate=void 0),t}const kP=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:i,width:n,height:r}=e.getMediaStreamTrackSettings();let{frameRate:o=i,width:s=n,height:a=r}=t;if(!o||!s||!a)return;s=gO(s),a=gO(a),o=gO(o);const{max:c,min:d}=function(e,t,i){const n=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(n),max:Math.floor(4*n)}}(s,a,o),{bitrateMax:l,bitrateMin:u}=t||{};l||YN.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(u,"]"));const{maxFramerate:h}=_N("ENCODER_CONFIG_LIMIT");return h&&"number"==typeof h&&(o=Math.min(o,h)),{frameRate:o,bitrateMax:l||c,bitrateMin:u||d,scaleResolutionDownBy:1,scale:0}},MP=async(e,t,i)=>await(async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i{const t=document.createElement("canvas");return t.width=2,t.height=2,new Wh(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await xP(e);i({buffer:n,width:t.width,height:t.height})}else n(new mw(Ew.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},xP=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var VP,FP,BP,jP,GP,WP,HP,KP,YP,qP,zP,XP,JP,QP,ZP,$P,eL,tL,iL,nL,rL,oL,sL,aL,cL,dL,lL,uL,hL,pL,_L,EL,mL,fL,TL,SL,gL,RL,vL,CL;let IL=(VP=$N({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),FP=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),BP=CP(),jP=yO("LocalAudioTrack","_enabledMutex"),GP=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),WP=CP(),HP=yO("LocalAudioTrack","_enabledMutex"),KP=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),YP=CP(),qP=CP(),zP=CP(),XP=$N({argsMap:e=>[e.getTrackId()]}),JP=CP(),QP=$N({argsMap:e=>[e.getTrackId()]}),ZP=CP(),$P=$N({argsMap:e=>[e.getTrackId()]}),eL=$N({argsMap:(e,t)=>[e.getTrackId(),t.name]}),tL=$N({argsMap:e=>[e.getTrackId()]}),qD((iL=class extends XD{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?vP.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n){super(e,i),YD(this,"trackMediaType",OD.AUDIO),YD(this,"_encoderConfig",void 0),YD(this,"_trackSource",void 0),YD(this,"metadata",[]),YD(this,"_enabled",!0),YD(this,"_volume",100),YD(this,"_useAudioElement",!0),YD(this,"_bypassWebAudio",!1),YD(this,"processor",void 0),YD(this,"_processorContext",void 0),YD(this,"_processorDestination",void 0),YD(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new wP,_N("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),_N("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),Wb()&&!QD?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){Sw(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&vP.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void YN.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,qw(this,RD.NEED_REPLACE_TRACK,this).then((()=>{YN.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{YN.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||!rD())throw new mw(Ew.NOT_SUPPORTED,"your browser does not support setting the audio output device");await vP.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(YN.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await qw(this,RD.NEED_ENABLE_TRACK,this),YN.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),YN.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await qw(this,RD.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),YN.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,YN.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await qw(this,RD.NEED_MUTE_TRACK,this):await qw(this,RD.NEED_UNMUTE_TRACK,this))}getStats(){nO((()=>{YN.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return zw(this,RD.GET_STATS)||KD({},DD)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(ND.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(ND.ON_AUDIO_BUFFER),this._source.on(ND.ON_AUDIO_BUFFER,(t=>e(t)))}play(){YN.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(YN.debug("[".concat(this.getTrackId(),"] start audio playback in element")),vP.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){YN.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?vP.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];YN.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&vP.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 qw(this,RD.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Wh.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new mw(Ew.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new mw(Ew.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(UD.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await qw(this,RD.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await qw(this,RD.NEED_REPLACE_TRACK,this))})),e.on(UD.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(UD.ON_TRACK),e.removeAllListeners(UD.ON_NODE)}bindProcessorContextEvents(e){e.on(xD.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(xD.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof wP&&(this._trackSource=new oP(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new bP(this._source.context,this.getTrackId(),"local"),t=new AP(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(ND.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(vP.stop(this.getTrackId()),this._source.play()),qw(this,RD.NEED_REPLACE_MIXING_TRACK,this).then((()=>{YN.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{YN.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[VP],Object.getOwnPropertyDescriptor(iL.prototype,"setVolume"),iL.prototype),qD(iL.prototype,"setPlaybackDevice",[FP,BP],Object.getOwnPropertyDescriptor(iL.prototype,"setPlaybackDevice"),iL.prototype),qD(iL.prototype,"setEnabled",[jP,GP,WP],Object.getOwnPropertyDescriptor(iL.prototype,"setEnabled"),iL.prototype),qD(iL.prototype,"setMuted",[HP,KP,YP],Object.getOwnPropertyDescriptor(iL.prototype,"setMuted"),iL.prototype),qD(iL.prototype,"getStats",[qP],Object.getOwnPropertyDescriptor(iL.prototype,"getStats"),iL.prototype),qD(iL.prototype,"setAudioFrameCallback",[zP],Object.getOwnPropertyDescriptor(iL.prototype,"setAudioFrameCallback"),iL.prototype),qD(iL.prototype,"play",[XP,JP],Object.getOwnPropertyDescriptor(iL.prototype,"play"),iL.prototype),qD(iL.prototype,"stop",[QP,ZP],Object.getOwnPropertyDescriptor(iL.prototype,"stop"),iL.prototype),qD(iL.prototype,"close",[$P],Object.getOwnPropertyDescriptor(iL.prototype,"close"),iL.prototype),qD(iL.prototype,"pipe",[eL],Object.getOwnPropertyDescriptor(iL.prototype,"pipe"),iL.prototype),qD(iL.prototype,"unpipe",[tL],Object.getOwnPropertyDescriptor(iL.prototype,"unpipe"),iL.prototype),iL),yL=(nL=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),rL=CP(),oL=yO("MicrophoneAudioTrack","_enabledMutex"),sL=$N({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),aL=CP(),cL=$N({argsMap:e=>[e.getTrackId()]}),qD((dL=class extends IL{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?TD(t.encoderConfig):{},n,_N("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),YD(this,"_config",void 0),YD(this,"_deviceName","default"),YD(this,"_constraints",void 0),YD(this,"_originalConstraints",void 0),YD(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(iw()||nw())&&ZD.bindInterruptDetectorTrack(this)}async setDevice(e){if(YN.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await mP.getDeviceById(e),i={};i.audio=KD({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await hP(i,this.getTrackId())}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await hP({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 YN.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await mP.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}YN.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return YN.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(YN.info("[".concat(this.getTrackId(),"] start setEnabled"),e),_N("AUTO_RESET_AUDIO_ROUTE")&&(Yb()||ow())){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 qw(this,RD.NEED_DISABLE_TRACK,this)}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=KD({},this._constraints),o=mP.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await hP({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await qw(this,RD.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),YN.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}YN.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(iw()||nw())&&ZD.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Yb()||ow())&&this._enabled&&!this._isClosed&&ZD.duringInterruption){const e=async()=>{ZD.off(sD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(YN.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};ZD.on(sD.IOS_INTERRUPTION_END,e)}else YN.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(bD.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=mP.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await hP({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(xD.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(xD.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[nL,rL],Object.getOwnPropertyDescriptor(dL.prototype,"setDevice"),dL.prototype),qD(dL.prototype,"setEnabled",[oL,sL,aL],Object.getOwnPropertyDescriptor(dL.prototype,"setEnabled"),dL.prototype),qD(dL.prototype,"close",[cL],Object.getOwnPropertyDescriptor(dL.prototype,"close"),dL.prototype),dL),AL=(lL=$N({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),uL=CP(),hL=$N({argsMap:e=>[e.getTrackId()]}),pL=CP(),_L=$N({argsMap:e=>[e.getTrackId()]}),EL=CP(),mL=$N({argsMap:e=>[e.getTrackId()]}),fL=CP(),TL=$N({argsMap:e=>[e.getTrackId()]}),SL=CP(),gL=$N({argsMap:e=>[e.getTrackId()]}),RL=$N({argsMap:e=>[e.getTrackId()]}),vL=CP(),qD((CL=class extends IL{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),YD(this,"source",void 0),YD(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(ND.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(bD.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){Sw(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[lL,uL],Object.getOwnPropertyDescriptor(CL.prototype,"startProcessAudioBuffer"),CL.prototype),qD(CL.prototype,"pauseProcessAudioBuffer",[hL,pL],Object.getOwnPropertyDescriptor(CL.prototype,"pauseProcessAudioBuffer"),CL.prototype),qD(CL.prototype,"seekAudioBuffer",[_L,EL],Object.getOwnPropertyDescriptor(CL.prototype,"seekAudioBuffer"),CL.prototype),qD(CL.prototype,"resumeProcessAudioBuffer",[mL,fL],Object.getOwnPropertyDescriptor(CL.prototype,"resumeProcessAudioBuffer"),CL.prototype),qD(CL.prototype,"stopProcessAudioBuffer",[TL,SL],Object.getOwnPropertyDescriptor(CL.prototype,"stopProcessAudioBuffer"),CL.prototype),qD(CL.prototype,"close",[gL],Object.getOwnPropertyDescriptor(CL.prototype,"close"),CL.prototype),qD(CL.prototype,"setAudioBufferPlaybackSpeed",[RL,vL],Object.getOwnPropertyDescriptor(CL.prototype,"setAudioBufferPlaybackSpeed"),CL.prototype),CL);class bL extends IL{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=$D().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,hO(8,"track-mix-")),YD(this,"trackList",void 0),YD(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)?(YN.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):YN.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){YN.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}Qw(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 bL?t.emit(AD.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class wL extends rP{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(ND.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(),YD(this,"audioBuffer",void 0),YD(this,"sourceNode",void 0),YD(this,"startPlayTime",0),YD(this,"startPlayOffset",0),YD(this,"pausePlayTime",0),YD(this,"options",void 0),YD(this,"currentLoopCount",0),YD(this,"currentPlaybackSpeed",100),YD(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):YN.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 OL=new Map;class NL{get rendFrameRate(){if(this.renderStats&&this.renderStats.curTs!==this.renderStats.lastTs){const e=this.renderStats.curTs-this.renderStats.lastTs,t=(this.renderStats.renderNum-this.renderStats.lastRenderNum)/e;return this.renderStats.lastRenderNum=this.renderStats.renderNum,this.renderStats.lastTs=this.renderStats.curTs,t}return 0}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(YN.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){YD(this,"trackId",void 0),YD(this,"config",void 0),YD(this,"onFirstVideoFrameDecoded",void 0),YD(this,"onVideoStateChanged",void 0),YD(this,"freezeTimeCounterList",[]),YD(this,"renderFreezeAccTime",0),YD(this,"isKeepLastFrame",!1),YD(this,"timeUpdatedCount",0),YD(this,"freezeTime",0),YD(this,"playbackTime",0),YD(this,"lastTimeUpdatedTime",0),YD(this,"autoplayFailed",!1),YD(this,"videoTrack",void 0),YD(this,"videoElement",void 0),YD(this,"cacheVideoElement",void 0),YD(this,"renderStats",void 0),YD(this,"_videoState",jD.VideoStateStopped),YD(this,"videoElementCheckInterval",void 0),YD(this,"videoElementFreezeTimeout",void 0),YD(this,"_videoElementStatus",BD.NONE),YD(this,"isGettingVideoDimensions",!1),YD(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return YN.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),YD(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===ZD.curState&&(YN.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Bb())),rw()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),YD(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=BD.PLAYING;break;case"loadeddata":if(this.videoState=jD.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=BD.CANPLAY;break;case"stalled":this.videoElementStatus=BD.STALLED;break;case"suspend":this.videoElementStatus=BD.SUSPEND;break;case"pause":this.videoElementStatus=BD.PAUSED,Yb()||ow()||Wb()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(YN.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=BD.WAITING;break;case"abort":this.videoElementStatus=BD.ABORT;break;case"ended":this.videoElementStatus=BD.ENDED;break;case"emptied":this.videoElementStatus=BD.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=BD.ERROR,YN.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Dk.lastVisibleTime_N("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}}})),YD(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(YN.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Bb())),rw()?(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"),ZD.on(sD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ZD.on(sD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&gP(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(YN.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):YN.warning("[".concat(this.trackId,"] play warning: "),t)}));const i=xb();if(("Safari"===i.name&&15===Number(i.version)||iw())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return YN.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new Wh(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await xP(e);n({buffer:t,width:i.width,height:i.height})}else r(new mw(Ew.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await UP(e)}destroy(){this.renderStats=void 0,ZD.off(sD.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ZD.off(sD.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=jD.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=BD.INIT,!this.videoElementCheckInterval&&(DL.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=BD.DESTROYED)}),1e3),_N("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,_N("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===jD.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=jD.VideoStateFrozen:document.addEventListener("visibilitychange",n))},o=(e,t)=>{if(this.videoElementStatus===BD.PLAYING){if(this.renderStats?(this.renderStats.renderNum++,this.renderStats.curTs=t.mediaTime):this.renderStats={lastTs:t.mediaTime,curTs:t.mediaTime,lastRenderNum:0,renderNum:0},i){const e=t.presentationTime-i.presentationTime;this.videoState===jD.VideoStateStarting&&(this.videoState=jD.VideoStateDecoding),this.videoState===jD.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,_N("VIDEO_FREEZE_DURATION"))),e<_N("VIDEO_FREEZE_DURATION")&&this.videoState===jD.VideoStateFrozen&&(this.videoState=jD.VideoStateDecoding),e>_N("VIDEO_FREEZE_DURATION")&&Dk.lastVisibleTime>=Dk.lastHiddenTime&&i.timestamp>Dk.lastVisibleTime&&i.timestamp>Dk.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=KD(KD({},t),{},{timestamp:e})}var n,s;_N("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(n=(s=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(s,o))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),lw()&&!_N("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const i=xb();"Safari"===i.name&&15===Number(i.version)||iw()||!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,Kb()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Kb()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{YN.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){DL.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=BD.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{YN.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{YN.error(e)})),this.autoplayFailed=!1,uw()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};uw()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),SP()}}const DL=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class PL extends NL{constructor(e){super(e),YD(this,"container",void 0),YD(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await UP(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",_N("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}var LL,kL,ML,UL,xL,VL,FL,BL,jL,GL,WL,HL,KL,YL,qL,zL,XL,JL,QL,ZL,$L,ek,tk,ik,nk,rk,ok,sk,ak,ck,dk,lk,uk,hk;let pk=(LL=$N({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),kL=CP(),ML=$N({argsMap:e=>[e.getTrackId()]}),UL=yO("LocalVideoTrack","_enabledMutex"),xL=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),VL=CP(),FL=yO("LocalVideoTrack","_enabledMutex"),BL=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),jL=CP(),GL=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),WL=CP(),HL=CP(),KL=$N({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),YL=CP(),qL=CP(),zL=CP(),XL=CP(),JL=CP(),QL=CP(),ZL=CP(),$L=$N({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ek=$N({argsMap:e=>[e.getTrackId()]}),tk=$N({argsMap:e=>[e.getTrackId()]}),ik=$N({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),nk=class e extends XD{get videoHeight(){if(Wb()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(Wb()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==BD.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),YD(this,"trackMediaType",OD.VIDEO),YD(this,"_player",void 0),YD(this,"isUseScaleResolutionDownBy",!1),YD(this,"_videoVisibleTimer",null),YD(this,"_previousVideoVisibleStatus",void 0),YD(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),YD(this,"_encoderConfig",void 0),YD(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),YD(this,"_optimizationMode",void 0),YD(this,"_videoHeight",void 0),YD(this,"_videoWidth",void 0),YD(this,"_forceBitrateLimit",void 0),YD(this,"_enabled",!0),YD(this,"_processorDestination",void 0),YD(this,"_processorContext",void 0),Wb()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(vD.SCREEN_TRACK))this.updateBitrateFromProfile();else if(Xb(Lb.CHROME,115)&&-1!==Fb().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&nD().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&&(YN.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(vD.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new yP(this.getTrackId(),"local"),this._processorDestination=new IP(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:(YN.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}YN.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=KD(KD(KD({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new NL(i):this._player=new PL(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(bD.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),_N("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,YN.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(YN.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await qw(this,RD.NEED_DISABLE_TRACK,this)}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void YN.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await qw(this,RD.NEED_ENABLE_TRACK,this)}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}YN.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,YN.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await qw(this,RD.NEED_MUTE_TRACK,this):await qw(this,RD.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new mw(Ew.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=_D(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=DP({encoderConfig:e});(Wb()||Yb()||ow())&&(t.deviceId=void 0),YN.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 mw(Ew.UNEXPECTED_ERROR,e.toString());throw YN.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(vD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await qw(this,RD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(YN)}}getStats(){nO((()=>{YN.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return zw(this,RD.GET_STATS)||KD({},PD)}async setBeautyEffect(e){YN.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 UP(e)}async setBitrateLimit(e){YN.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(_O)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new mw(Ew.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");YN.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=_D(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(vD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await qw(this,RD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(YN)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:o,min:s}=function(e,t,i,n,r){const o=_N("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:n,max:r};if(void 0===r){var s;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*a:2*a,n=null!==(s=n)&&void 0!==s?s:a}else{var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10)}return{min:n,max:r}}(e,t,i,r,n);this._encoderConfig.bitrateMin=s,this._encoderConfig.bitrateMax=o,YN.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(s,"]"))}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=bw.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eD.reportApiInvoke(null,{tag:Mw.TRACER,name:kw.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 mw(Ew.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new mw(Ew.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=KD(KD({},n),_D(t))),n=tO(n);const r=hO(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,tO(this._scalabilityMode),this._optimizationMode,r,tO(this._hints));return t&&n&&o.setEncoderConfiguration(n),YN.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 mw(Ew.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new mw(Ew.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(nO((()=>{eD.reportApiInvoke(null,{name:kw.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:Mw.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!_N("ENABLE_VIDEO_SEI")||!_N("ENABLE_ENCODED_TRANSFORM"))return void YN.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new mw(Ew.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void YN.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===n?this.safeEmit("sei-to-send",e):YN.warning("SEI is not supported by ".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(UD.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await qw(this,RD.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await qw(this,RD.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(UD.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(xD.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(xD.REQUEST_CONSTRAINTS)}},qD(nk.prototype,"play",[LL,kL],Object.getOwnPropertyDescriptor(nk.prototype,"play"),nk.prototype),qD(nk.prototype,"stop",[ML],Object.getOwnPropertyDescriptor(nk.prototype,"stop"),nk.prototype),qD(nk.prototype,"setEnabled",[UL,xL,VL],Object.getOwnPropertyDescriptor(nk.prototype,"setEnabled"),nk.prototype),qD(nk.prototype,"setMuted",[FL,BL,jL],Object.getOwnPropertyDescriptor(nk.prototype,"setMuted"),nk.prototype),qD(nk.prototype,"setEncoderConfiguration",[GL,WL],Object.getOwnPropertyDescriptor(nk.prototype,"setEncoderConfiguration"),nk.prototype),qD(nk.prototype,"getStats",[HL],Object.getOwnPropertyDescriptor(nk.prototype,"getStats"),nk.prototype),qD(nk.prototype,"setBeautyEffect",[KL,YL],Object.getOwnPropertyDescriptor(nk.prototype,"setBeautyEffect"),nk.prototype),qD(nk.prototype,"getCurrentFrameData",[qL],Object.getOwnPropertyDescriptor(nk.prototype,"getCurrentFrameData"),nk.prototype),qD(nk.prototype,"getCurrentFrameImage",[zL],Object.getOwnPropertyDescriptor(nk.prototype,"getCurrentFrameImage"),nk.prototype),qD(nk.prototype,"setBitrateLimit",[XL],Object.getOwnPropertyDescriptor(nk.prototype,"setBitrateLimit"),nk.prototype),qD(nk.prototype,"setOptimizationMode",[JL],Object.getOwnPropertyDescriptor(nk.prototype,"setOptimizationMode"),nk.prototype),qD(nk.prototype,"setScalabiltyMode",[QL],Object.getOwnPropertyDescriptor(nk.prototype,"setScalabiltyMode"),nk.prototype),qD(nk.prototype,"updateMediaStreamTrackResolution",[ZL],Object.getOwnPropertyDescriptor(nk.prototype,"updateMediaStreamTrackResolution"),nk.prototype),qD(nk.prototype,"pipe",[$L],Object.getOwnPropertyDescriptor(nk.prototype,"pipe"),nk.prototype),qD(nk.prototype,"unpipe",[ek],Object.getOwnPropertyDescriptor(nk.prototype,"unpipe"),nk.prototype),qD(nk.prototype,"close",[tk],Object.getOwnPropertyDescriptor(nk.prototype,"close"),nk.prototype),qD(nk.prototype,"replaceTrack",[ik],Object.getOwnPropertyDescriptor(nk.prototype,"replaceTrack"),nk.prototype),nk),_k=(rk=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),ok=CP(),sk=yO("CameraVideoTrack","_enabledMutex"),ak=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),ck=CP(),dk=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),lk=CP(),uk=$N({argsMap:e=>[e.getTrackId()]}),hk=class e extends pk{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,_D(t.encoderConfig),n,r,o),YD(this,"_config",void 0),YD(this,"_originalConstraints",void 0),YD(this,"_constraints",void 0),YD(this,"_enabled",!0),YD(this,"_deviceName","default"),YD(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(iw()||nw())&&!function(){const e=xb();if(e.os!==Pb.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&sw()&&this._enabled&&!this._isClosed&&(YN.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=_D(this._config.encoderConfig),ZD.on(sD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),ZD.on(sD.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(YN.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await mP.getDeviceById(e),i={};i.video=KD({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await hP(i,this.getTrackId())}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await hP({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 YN.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await mP.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}YN.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){YN.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:KD(KD({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await hP(t,this.getTrackId())}catch(t){throw YN.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await hP({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=KD({},t.video),YN.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(YN.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await hP({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await qw(this,RD.NEED_ENABLE_TRACK,this)}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),YN.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 qw(this,RD.NEED_DISABLE_TRACK,this)}catch(e){throw YN.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}YN.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new mw(Ew.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=_D(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=eO(this._config);i.encoderConfig=e;const n=DP(i);(Wb()||Yb()||ow())&&(n.deviceId=void 0),YN.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 mw(Ew.UNEXPECTED_ERROR,e.toString());throw YN.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(vD.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await qw(this,RD.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(YN)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Yb()||ow())&&this._enabled&&!this._isClosed&&ZD.duringInterruption){const e=async()=>{ZD.off(sD.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(YN.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};ZD.on(sD.IOS_INTERRUPTION_END,e)}else YN.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(bD.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=mP.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await hP({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),ZD.off(sD.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),ZD.off(sD.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=KD(KD({},n),_D(t))),n=tO(n);const r=hO(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,tO(KD(KD({},this._config),{},{encoderConfig:n})),tO(this._constraints),tO(this._scalabilityMode),this._optimizationMode,r);return t&&n&&o.setEncoderConfiguration(n),YN.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(xD.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(xD.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},qD(hk.prototype,"setDevice",[rk,ok],Object.getOwnPropertyDescriptor(hk.prototype,"setDevice"),hk.prototype),qD(hk.prototype,"setEnabled",[sk,ak,ck],Object.getOwnPropertyDescriptor(hk.prototype,"setEnabled"),hk.prototype),qD(hk.prototype,"setEncoderConfiguration",[dk,lk],Object.getOwnPropertyDescriptor(hk.prototype,"setEncoderConfiguration"),hk.prototype),qD(hk.prototype,"close",[uk],Object.getOwnPropertyDescriptor(hk.prototype,"close"),hk.prototype),hk);function Ek(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=KD(KD({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?YN.debug("[".concat(e,"] set content hint to"),i.optimizationMode):YN.debug("[".concat(e,"] set content hint failed")))):YN.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var mk,fk,Tk,Sk,gk,Rk,vk,Ck,Ik,yk,Ak,bk;class wk extends zD{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(hO(5,""))),YD(this,"_userId",void 0),YD(this,"_uintId",void 0),YD(this,"_isDestroyed",!1),YD(this,"store",void 0),YD(this,"processor",void 0),YD(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,YN.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let Ok=(mk=$N({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),fk=$N({argsMap:e=>[e.getTrackId()]}),Tk=$N({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Sk=$N({argsMap:e=>[e.getTrackId()]}),qD((gk=class extends wk{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==BD.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),YD(this,"_videoVisibleTimer",null),YD(this,"_previousVideoVisibleStatus",void 0),YD(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),YD(this,"trackMediaType",OD.VIDEO),YD(this,"_videoWidth",void 0),YD(this,"_videoHeight",void 0),YD(this,"_player",void 0),YD(this,"processorDestination",void 0),YD(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new yP(this.getTrackId(),"remote"),this.processorDestination=new IP(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return nO((()=>{YN.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),zw(this,RD.GET_STATS)||KD({},MD)}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:(YN.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}YN.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=KD(KD({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new NL(i):this._player=new PL(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(wD.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(wD.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(wD.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),_N("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,YN.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){NP(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(_O)}_updatePlayerSource(){YN.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=bw.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eD.reportApiInvoke(null,{tag:Mw.TRACER,name:kw.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 mw(Ew.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new mw(Ew.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(UD.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(UD.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(AD.SEI_RECEIVED,e)}}).prototype,"play",[mk],Object.getOwnPropertyDescriptor(gk.prototype,"play"),gk.prototype),qD(gk.prototype,"stop",[fk],Object.getOwnPropertyDescriptor(gk.prototype,"stop"),gk.prototype),qD(gk.prototype,"pipe",[Tk],Object.getOwnPropertyDescriptor(gk.prototype,"pipe"),gk.prototype),qD(gk.prototype,"unpipe",[Sk],Object.getOwnPropertyDescriptor(gk.prototype,"unpipe"),gk.prototype),gk),Nk=(Rk=$N({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),vk=$N({argsMap:(e,t)=>[e.getTrackId(),t]}),Ck=$N({argsMap:e=>[e.getTrackId()]}),Ik=$N({argsMap:e=>[e.getTrackId()]}),yk=$N({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ak=$N({argsMap:e=>[e.getTrackId()]}),qD((bk=class extends wk{get isPlaying(){return this._useAudioElement?vP.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),YD(this,"trackMediaType",OD.AUDIO),YD(this,"_source",void 0),YD(this,"_useAudioElement",!0),YD(this,"_volume",100),YD(this,"processorContext",void 0),YD(this,"processorDestination",void 0),YD(this,"_played",!1),YD(this,"_bypassWebAudio",!1),_N("DISABLE_WEBAUDIO")?(this._source=new wP,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new oP(e,!0),_N("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(ND.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(wD.FIRST_FRAME_DECODED)})),this.processorContext=new bP(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new AP(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(ND.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(ND.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(ND.ON_AUDIO_BUFFER),this._source.on(ND.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?vP.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!rD())throw new mw(Ew.NOT_SUPPORTED,"your browser does not support setting the audio output device");await vP.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return nO((()=>{YN.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),zw(this,RD.GET_STATS)||KD({},LD)}play(){YN.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(YN.debug("[".concat(this.getTrackId(),"] use audio element to play")),vP.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){YN.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?vP.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];YN.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&vP.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new mw(Ew.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new mw(Ew.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new mw(Ew.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(UD.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(UD.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(UD.ON_TRACK),this.processorDestination.removeAllListeners(UD.ON_NODE)}}).prototype,"setVolume",[Rk],Object.getOwnPropertyDescriptor(bk.prototype,"setVolume"),bk.prototype),qD(bk.prototype,"setPlaybackDevice",[vk],Object.getOwnPropertyDescriptor(bk.prototype,"setPlaybackDevice"),bk.prototype),qD(bk.prototype,"play",[Ck],Object.getOwnPropertyDescriptor(bk.prototype,"play"),bk.prototype),qD(bk.prototype,"stop",[Ik],Object.getOwnPropertyDescriptor(bk.prototype,"stop"),bk.prototype),qD(bk.prototype,"pipe",[yk],Object.getOwnPropertyDescriptor(bk.prototype,"pipe"),bk.prototype),qD(bk.prototype,"unpipe",[Ak],Object.getOwnPropertyDescriptor(bk.prototype,"unpipe"),bk.prototype),bk);const Dk=new class extends Dw{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),YD(this,"_lastHiddenTime",0),YD(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),YN.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};class Pk extends Dw{constructor(e,t){super(),YD(this,"trackMediaType",OD.DATA),YD(this,"_version",1),YD(this,"_type",3),YD(this,"_config",void 0),YD(this,"_originDataChannel",void 0),YD(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),YD(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),YD(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return _N("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new Wh(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new mw(Ew.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new mw(Ew.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new mw(Ew.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[WD.OPEN,WD.CLOSE,WD.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class Lk extends Pk{constructor(e){super(e),YD(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLengthTf.revokeObjectURL(e)),0),new Worker(Tf.createObjectURL(e))}const Uk=71,xk=1,Vk=2,Fk=1,Bk=2;var jk=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}(jk||{});function Gk(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.getUint8(0);if(i!==Uk)return;const n=e.getUint16(1),r=xk+Vk+n,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:i,tlvLen:n,tlv:[],frame:o};let a=xk+Vk;for(;a>1:127&o})}else if(i===jk.METADATA||i===jk.AUDIO_64_BIT_PTS){const t=new Uint8Array(n);for(let i=0;it;i--,r++)n=n*i/r;return n}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(i)+i*e,qk.set(n,r)}return ri&&n++;t[s]!==n&&(t[s]=n,o=!0)}return o}window.cache=qk;let Jk=0;class Qk{constructor(e){YD(this,"id",void 0),YD(this,"immediates",[]),YD(this,"lastNonSilence",-1),YD(this,"immediateSpeechActivityScore",Kk),YD(this,"lastLevelChangedTime",Date.now()),YD(this,"levels",[]),YD(this,"longs",[]),YD(this,"longSpeechActivityScore",Kk),YD(this,"mediums",[]),YD(this,"mediumSpeechActivityScore",Kk),YD(this,"minLevel",0),YD(this,"nextMinLevel",0),YD(this,"nextMinLevelWindowLength",0),YD(this,"energyScore",0),this.id=e||"".concat(Jk++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,i=this.minLevel+Yk;let n=!1;for(let r=0;rKk&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=zk(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(cr(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let i=e;return e<0&&(i=0),e>Hk&&(i=Hk),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+Yk?i:i/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>Hk&&(e=Hk),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class Zk{constructor(e){YD(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}class $k{constructor(e,t,i){YD(this,"isDominant",void 0),YD(this,"energyRanking",void 0),YD(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class eM extends Dw{constructor(e){super(),YD(this,"dominantId",null),YD(this,"lastDecisionTime",0),YD(this,"lastLevelChangedTime",0),YD(this,"lastLevelIdleTime",0),YD(this,"relativeSpeechActivities",[]),YD(this,"speakers",new Map),YD(this,"enableSilence",!1),YD(this,"timeoutToSilenceInterval",0),YD(this,"decisionMaker",null),YD(this,"loudest",[]),YD(this,"numLoudestToTrack",3),YD(this,"energyExpireTimeMs",250),YD(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=i&&(this.energyAlphaPct=i),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const i=Date.now(),n=this.getOrCreateSpeaker(e);this.lastLevelChangedTime0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new Qk(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,i){const n=e.id===this.dominantId;if(t<0){let t=0;for(;t=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.lengththis.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new $k(n,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new Zk(this),this.decisionMaker.execute())}makeDecision(e){let t=null,i=null;const n=this.speakers.size;let r=null;if(0===n)r=null;else if(1===n){var o;const t=Zh(o=this.speakers).call(o).next().value;this.enableSilence&&t&&(r=t.id,t.evaluateSpeechActivityScores(e),e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null))}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(r=e.value[0],t=e.value[1])}else r=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const i=this.relativeSpeechActivities;let n=2;for(const o of this.speakers.entries()){const[s,a]=o;if(a===t)continue;a.evaluateSpeechActivityScores(e);for(let e=0;e3&&d>2&&l>0&&d>n&&(n=d,r=s)}this.enableSilence&&null!=t&&r===t.id&&e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null)}null==r&&!this.enableSilence||r===this.dominantId||(t=this.dominantId,this.dominantId=r,i=this.dominantId),null==i&&!this.enableSilence||i===t||this.emit("ActiveSpeakerChanged",i)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let i=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):i=t;let n=300-(e-this.lastDecisionTime);return n<=0&&(this.lastDecisionTime=e,this.makeDecision(e),n=300-(Date.now()-e)),n>0&&i>n&&(i=n),i}timeoutIdleLevels(e){const t=[];for(const n of Zh(i=this.speakers).call(i)){var i;const r=e-n.getLastLevelChangedTime();36e5this.speakers.delete(e)))}}const tM=new Map;let iM=null,nM=null;const rM=3;let oM=[];const sM=new Map,aM=new Map;class cM{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){YD(this,"id",void 0),YD(this,"track",void 0),YD(this,"score",0),YD(this,"active",!0),YD(this,"muted",!1),YD(this,"timer",0),YD(this,"actives",0),YD(this,"inactives",0),this.id=e,this.track=t,this.setActive(sM.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const{actives:t,inactives:i}=function(){const e=[],t=[];return Array.from(Zh(sM).call(sM)).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}();if(t.length>3){let e;t.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(t.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score40&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(Zh(sM).call(sM)).forEach((i=>{!i.active||i.id===e||i.samples<40||(!t||i.score.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(Zh(sM).call(sM)).forEach((i=>{i.active||i.id===e||i.samples<40||(!t||i.score>t.score)&&(t=i)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let dM;function lM(e){const t=sM.get(e);t&&(sM.delete(e),t.clearTimer())}const uM=new Map,hM=new Map;function pM(e,t,i){let n=new Uint8Array(e,t,i),r=[],o=0;for(;r.length34,iD.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}(),iD.supportMinBitrate=e.name===Lb.CHROME||e.name===Lb.EDGE,iD.supportSetRtpSenderParameters=function(){const e=xb();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!dw()||!(!Wb()&&!jb())||e.name===Lb.FIREFOX&&Number(e.version)>=64)}(),e.name===Lb.SAFARI&&(Number(e.version)>=14?iD.supportDualStream=!0:iD.supportDualStream=!1),iD.webAudioMediaStreamDest=function(){const e=xb();return!(e.name===Lb.SAFARI&&Number(e.version)<12)}(),iD.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,iD.supportWebGL="undefined"!=typeof WebGLRenderingContext,iD.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,dw()||(iD.webAudioWithAEC=!0),iD.supportShareAudio=function(){const e=xb();return(e.os===Pb.WIN_10||e.os===Pb.WIN_81||e.os===Pb.WIN_7||e.os===Pb.LINUX||e.os===Pb.MAC_OS||e.os===Pb.CHROMIUM_OS)&&e.name===Lb.CHROME&&Number(e.version)>=74}(),iD.supportDataChannel=!!(qb(76)||function(e){const t=xb();return!(t.name!==Lb.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||Qb(14)),iD.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!Kb()&&!!e&&e.prototype.setConfiguration instanceof Function}(),iD.supportWebRTCEncodedTransform=function(){const e=xb();return"Chrome"===e.name&&Number(e.version)>=87||"Safari"===e.name&&Number(e.version)>=15}(),iD.supportWebRTCInsertableStream=function(){const e=xb();return(e.name===Lb.CHROME||e.name===Lb.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),iD.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,iD.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,$w((()=>{iD.supportDualStreamEncoding=function(){const e=xb();return!!_N("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&_N("CHROME_DUAL_STREAM_USE_ENCODING")))}(),YN.debug("browser ua: ",navigator.userAgent),YN.info("browser info: ",e),YN.info("browser compatibility: ",iD)}))}();const mM=["CHINA","GLOBAL"];const fM=[[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]],TM=[],SM=[];function gM(e,t){return!!t&&TM.some((i=>i.uid===e&&i.channelName===t))}function RM(){return SM.length>0}var vM=Ev.forEach,CM=Bn("forEach")?[].forEach:function(e){return vM(this,e,arguments.length>1?arguments[1]:void 0)};wi({target:"Array",proto:!0,forced:[].forEach!=CM},{forEach:CM});var IM=Ji("Array").forEach,yM=pn,AM=Ze,bM=l,wM=IM,OM=Array.prototype,NM={DOMTokenList:!0,NodeList:!0},DM=function(e){var t=e.forEach;return e===OM||bM(OM,e)&&t===OM.forEach||AM(NM,yM(e))?wM:t},PM=i(DM),LM=Xe,kM=to;wi({target:"Object",stat:!0,forced:n((function(){kM(1)}))},{keys:function(e){return kM(LM(e))}});var MM=i(ie.Object.keys),UM=i(zn),xM=i(ar),VM=wi,FM=Qn,BM=Gc,jM=te,GM=xi,WM=Gi,HM=Z,KM=sp,YM=ht,qM=Qc,zM=OR("slice"),XM=YM("species"),JM=Array,QM=Math.max;VM({target:"Array",proto:!0,forced:!zM},{slice:function(e,t){var i,n,r,o=HM(this),s=WM(o),a=GM(e,s),c=GM(void 0===t?s:t,s);if(FM(o)&&(i=o.constructor,(BM(i)&&(i===JM||FM(i.prototype))||jM(i)&&null===(i=i[XM]))&&(i=void 0),i===JM||void 0===i))return qM(o,a,c);for(n=new(void 0===i?JM:i)(QM(c-a,0)),r=0;a\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw YN.error("Invalid Channel Name ".concat(e)),new tD(Ew.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function TU(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||Iw(e,1,255)))throw new tD(Ew.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&&YN.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 SU=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const gU={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},RU={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function vU(e,t){Rw(e.url,"".concat(t,".url"),1,1e3,!1),Cw(e.x)||Sw(e.x,"".concat(t,".x"),0,1e4),Cw(e.y)||Sw(e.y,"".concat(t,".y"),0,1e4),Cw(e.width)||Sw(e.width,"".concat(t,".width"),0,1e4),Cw(e.height)||Sw(e.height,"".concat(t,".height"),0,1e4),Cw(e.zOrder)||Sw(e.zOrder,"".concat(t,".zOrder"),0,255),Cw(e.alpha)||Sw(e.alpha,"".concat(t,".alpha"),0,1,!1)}const CU={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let IU=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),yU=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),AU=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});function bU(e){if(!e.channelName)throw new tD(Ew.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new tD(Ew.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Rw(e.token,"info.token",1,2047),TU(e.uid),fU(e.channelName),!0}let wU=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),OU=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}({}),NU=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}({}),DU=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}({}),PU=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),LU=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}({}),kU=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}({}),MU=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),UU=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 xU=[UU.AFRICA,UU.ASIA,UU.CHINA,UU.EUROPE,UU.GLOBAL,UU.INDIA,UU.JAPAN,UU.NORTH_AMERICA,UU.OCEANIA,UU.OVERSEA,UU.SOUTH_AMERICA];let VU=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 FU={CHINA:{},ASIA:{CODE:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:VU.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:{}};oN&&(FU.CHINA={CODE:VU.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 BU=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e}({});function jU(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class GU extends Dw{constructor(e,t){super(),QI(this,"onICEConnectionStateChange",void 0),QI(this,"onConnectionStateChange",void 0),QI(this,"onDTLSTransportStateChange",void 0),QI(this,"onDTLSTransportError",void 0),QI(this,"onICETransportStateChange",void 0),QI(this,"onFirstAudioReceived",void 0),QI(this,"onFirstVideoReceived",void 0),QI(this,"onFirstAudioDecoded",void 0),QI(this,"onFirstVideoDecoded",void 0),QI(this,"onFirstVideoDecodedTimeout",void 0),QI(this,"onSelectedLocalCandidateChanged",void 0),QI(this,"onSelectedRemoteCandidateChanged",void 0),QI(this,"onICECandidateError",void 0),QI(this,"getLocalVideoStats",void 0)}}class WU extends GU{constructor(e,t){super(e,t),QI(this,"establishPromise",void 0)}}let HU=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),KU=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),YU=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 qU=["disconnected","failed"];let zU=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),XU=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),JU=function(e){return e.AudioMetadata="audioMetadata",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}({}),QU=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),ZU=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),$U=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}({}),ex=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),tx=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}({}),ix=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),nx=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}({}),rx=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),ox=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}({}),sx=function(e){return e.ABORT="abort",e}({}),ax=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}({}),cx=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const dx={[oU.ACCESS_POINT]:{[cU.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[cU.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[cU.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[cU.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[cU.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[cU.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[cU.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[oU.UNILBS]:{[aU.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[aU.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[aU.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[aU.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[aU.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[aU.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[aU.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[aU.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[aU.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[aU.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[aU.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[aU.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[oU.STRING_UID_ALLOCATOR]:{[sU.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[sU.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[sU.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function lx(e){const t=dx[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===oU.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 ux={[dU.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[dU.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[dU.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[dU.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[dU.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[dU.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[dU.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[dU.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[dU.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[dU.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[dU.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[dU.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[dU.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[dU.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[dU.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[dU.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[dU.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[dU.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[dU.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[dU.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[dU.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[dU.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[dU.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[dU.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[dU.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[dU.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[dU.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[dU.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[dU.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[dU.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[dU.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[dU.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[dU.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[dU.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[dU.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[dU.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[dU.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[dU.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[dU.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[dU.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[dU.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[dU.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[dU.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[dU.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[dU.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[dU.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[dU.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[dU.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[dU.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[dU.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[dU.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[dU.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[dU.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[dU.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[dU.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[dU.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[dU.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[dU.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[dU.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[dU.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[dU.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[dU.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[dU.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[dU.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function hx(e){const t=ux[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function px(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _x(e){for(var t=1;t{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{var i;return Dn(i=e.host).call(i,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(Ex(_x(_x({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=_x({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}a.push(Ex(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 tD(Ew.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=wb();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:kU.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();xb().os===Pb.MAC_OS&&Kb()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(mx)||[],t||([,i,n]=e.match(fx)||[]),i&&n||([,i,n]=e.match(Tx)||[]),i&&n||([,i]=e.match(Sx)||[]),i||YN.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(YN.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function vx(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 Cx extends Dw{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Dn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(mU.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(mU.CONNECTED):"closed"===this._state?this.emit(mU.CLOSED):"failed"===this._state&&this.emit(mU.FAILED))}resetReconnectCount(e){YN.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(),QI(this,"connectionID",0),QI(this,"currentURLIndex",0),QI(this,"urls",[]),QI(this,"_reconnectMode","tryNext"),QI(this,"reconnectReason",void 0),QI(this,"_initMutex",void 0),QI(this,"name",void 0),QI(this,"_state","closed"),QI(this,"reconnectInterrupter",void 0),QI(this,"websocket",void 0),QI(this,"retryConfig",void 0),QI(this,"reconnectCount",0),QI(this,"forceCloseTimeout",5e3),QI(this,"onlineReconnectListener",void 0),QI(this,"useCompress",void 0),QI(this,"tryDoubleDomain",!1),QI(this,"use443PortOnly",!1),QI(this,"wsInflateLength",0),QI(this,"wsDeflateLength",0),QI(this,"closeEstablishingWs",(()=>{})),QI(this,"store",void 0),QI(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===Hw.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=wb(),t=this.urls[this.currentURLIndex];_N("ENABLE_PREALLOC_PC")&&this.emit(ex.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(mU.CLOSED,(()=>{e.reject(new mw(Ew.WS_DISCONNECT))})),this.once(mU.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void YN.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),YN.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 mw(Ew.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new mw(Ew.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=wb();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),YN.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(YN.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 mw(Ew.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=zw(this,mU.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void YN.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new mw(Ew.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},o=e=>{this.emit(mU.ON_MESSAGE,e)},s=e=>{YN.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),_N("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=_N("GATEWAY_WSS_ADDRESS")),YN.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=o,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,n=e instanceof mw,o=n&&e.code===Ew.WS_ABORT,s=n&&e.code===Ew.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());YN.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 mw(Ew.WS_DISCONNECT,"websocket is closed: ".concat(c)):new mw(Ew.WS_ERR,"init websocket failed: ".concat(c))),s&&YN.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;YN.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||Jw.isOnline||!Jw.onlineWaiter||(this.onlineReconnectListener=Jw.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=bO(this.reconnectCount,this.retryConfig);YN.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Wh.race([uO(t),this.onlineReconnectListener||new Wh((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(mU.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);YN.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&&(YN.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await Yw(this,mU.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;YN.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&Dn(n).call(n,"dynamic key expired")?(this.emit(mU.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class Ix extends Cx{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=wb(),n=function(e,t){return new Rx(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{YN.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new mw(Ew.WS_ABORT,"choose best websocket aborted"))};const r=_N("GATEWAY_DOMAINS");return YN.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 yx extends Cx{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new Wh(((i,n)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{YN.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new mw(Ew.WS_ABORT,"choose best websocket aborted"))};const s=_N("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=s.find((t=>-1!==c?Dn(e).call(e,t,c):Dn(e).call(e,t)));YN.debug("[choose-best-ws] currentDomain: ",d,", domains: ",s);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{s.forEach((t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",o.push(n),YN.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(YN.debug("[choose-best-ws] ws create failed, fallback to single url"),o.forEach((e=>e.close()));o.length;)o.pop();l=!0}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},t),o.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;YN.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{YN.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,i(e)},e.onclose=e=>{if(a=e,r)return;o.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(YN.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a))},e.onmessage=t=>{YN.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),uO(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;YN.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),o.push(r),r.binaryType="arraybuffer"}catch(e){const t=new mw(Ew.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return YN.error("[".concat(this.name,"]").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{YN.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},uO(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class Ax extends Dw{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===lU.CONNECTED?this.emit(uU.WS_CONNECTED):e===lU.RECONNECTING?this.emit(uU.WS_RECONNECTING,this._websocketReconnectReason):e===lU.CLOSED&&this.emit(uU.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),QI(this,"_disconnectedReason",void 0),QI(this,"_websocketReconnectReason",void 0),QI(this,"_connectionState",lU.CLOSED),QI(this,"reconnectToken",void 0),QI(this,"websocket",void 0),QI(this,"openConnectionTime",void 0),QI(this,"clientId",void 0),QI(this,"lastMsgTime",Date.now()),QI(this,"uploadCache",[]),QI(this,"uploadCacheInterval",void 0),QI(this,"rttRolling",new NO(5)),QI(this,"pingpongTimer",void 0),QI(this,"wsInflateDataTimer",void 0),QI(this,"pingpongTimeoutCount",0),QI(this,"joinResponse",void 0),QI(this,"multiIpOption",void 0),QI(this,"initError",void 0),QI(this,"spec",void 0),QI(this,"store",void 0),QI(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(uU.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===_U.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===_U.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(Vw.UID_BANNED);break;case 15:this.close(Vw.IP_BANNED);break;case 16:this.close(Vw.CHANNEL_BANNED)}if(t._type===_U.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case dU.ERR_LICENSE_MISSING:this.close(Vw.LICENSE_MISSING);break;case dU.ERR_LICENSE_EXPIRED:this.close(Vw.LICENSE_EXPIRED);break;case dU.ERR_LICENSE_MINUTES_EXCEEDED:this.close(Vw.LICENSE_MINUTES_EXCEEDED);break;case dU.ERR_LICENSE_PERIOD_INVALID:this.close(Vw.LICENSE_PERIOD_INVALID);break;case dU.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(Vw.LICENSE_MULTIPLE_SDK_SERVICE);break;case dU.ERR_LICENSE_ILLEGAL:this.close(Vw.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Ix("gateway-".concat(this.clientId),this.spec.retryConfig,!0,_N("JOIN_GATEWAY_USE_DUAL_DOMAIN"),_N("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===lU.CONNECTED&&this.reconnect("retry",Ww.OFFLINE)}))}async request(e,t,i,n){const r=hO(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((t,i)=>{if(this.connectionState===lU.CONNECTED)return t();const n=()=>{this.off(uU.WS_CLOSED,r),t()},r=()=>{this.off(uU.WS_CONNECTED,n),i(new tD(Ew.WS_ABORT))};this.once(uU.WS_CONNECTED,n),this.once(uU.WS_CLOSED,r),e!==hU.PUBLISH&&e!==hU.PUBLISH_DATASTREAM&&e!==hU.SUBSCRIBE&&e!==hU.SUBSCRIBE_DATASTREAM&&e!==hU.UNSUBSCRIBE&&e!==hU.UNSUBSCRIBE_DATASTREAM&&e!==hU.UNPUBLISH&&e!==hU.UNPUBLISH_DATASTREAM&&e!==hU.CONTROL&&e!==hU.RESTART_ICE||this.once(uU.DISCONNECT_P2P,(()=>{i(new tD(Ew.DISCONNECT_P2P))})),e!==hU.PUBLISH&&e!==hU.RESTART_ICE||this.once(uU.ABORT_P2P_EXECUTION,(()=>{i(new tD(Ew.DISCONNECT_P2P))}))}));if(this.connectionState!==lU.CONNECTING&&this.connectionState!==lU.RECONNECTING||e===hU.JOIN||e===hU.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Wh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(uU.WS_CLOSED,c),this.off(uU.WS_RECONNECTING,c),this.emit(uU.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new tD(Ew.WS_ABORT,"type: ".concat(e))),this.off(uU.WS_CLOSED,c),this.off(uU.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(uU.WS_CLOSED,c),this.once(uU.WS_RECONNECTING,c),uO(_N("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(YN.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(uU.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===lU.CLOSED||e===hU.LEAVE)throw new tD(Ew.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===hU.JOIN||e===hU.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=hx(l),h=new tD(Ew.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(YN.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===dU.ERR_TOO_MANY_BROADCASTERS?e===hU.JOIN||e===hU.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===dU.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,YN.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ww.MULTI_IP)):this.reconnect(u.action,Ww.SERVER_ERROR),e===hU.JOIN||e===hU.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void YN.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(pU.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=_N("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!==lU.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)}),_N("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Wh(((t,i)=>{this.once(uU.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(uU.WS_CLOSED,(e=>i(this.initError||new tD(Ew.WS_ABORT,e)))),this.connectionState=lU.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||Vw.LEAVE,this.connectionState=lU.CLOSED,YN.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(uU.ABORT_P2P_EXECUTION);const e=await Yw(this,uU.REQUEST_JOIN_INFO),t=await this.request(hU.JOIN,e);if(!t)return this.emit(uU.REPORT_JOIN_GATEWAY,kU.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(uU.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=lU.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new tD(Ew.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Xw(this,uU.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(hU.REJOIN,e);return!!t&&(this.connectionState=lU.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(_U.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(_U.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(_U.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(_U.MUTE_AUDIO,{uid:e.uid}):this.emit(_U.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(_U.MUTE_VIDEO,{uid:e.uid}):this.emit(_U.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(_U.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(_U.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(_U.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(_U.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(_U.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){YN.debug("[".concat(this.clientId,"] receive notification: "),e);const t=hx(e.code);if(28===e.code&&"detail"in e&&(YN.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(uU.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(Vw.UID_BANNED),void this.close()):void this.reconnect(t.action,Ww.SERVER_ERROR);YN.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=_N("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(YN.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>_N("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ww.TIMEOUT):this.request(hU.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),_N("REPORT_STATS")&&this.send(hU.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(pU.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(mU.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(uU.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(mU.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(mU.CLOSED,(()=>{this.connectionState=lU.CLOSED})),this.websocket.on(mU.FAILED,(()=>{this._disconnectedReason=Vw.NETWORK_ERROR,this.connectionState=lU.CLOSED})),this.websocket.on(mU.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===lU.CONNECTED?this.connectionState=lU.RECONNECTING:this.connectionState=lU.CONNECTING})),this.websocket.on(mU.WILL_RECONNECT,((e,t,i)=>{const n=Xw(this,uU.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(YN.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=kU.P2P_DISCONNECTED),r&&(YN.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(uU.REPORT_JOIN_GATEWAY,t||kU.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(uU.DISCONNECT_P2P)),i(e)})),this.websocket.on(mU.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{YN.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Ww.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(uU.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof tD){if(e.code===Ew.UNEXPECTED_RESPONSE&&e.data.code===dU.ERR_NO_AUTHORIZED)return this.initError=new tD(Ew.TOKEN_EXPIRE,"dynamic key expired"),void this.close(Vw.TOKEN_EXPIRE);YN.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ww.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(mU.REQUEST_NEW_URLS,((e,t)=>{Yw(this,uU.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(mU.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(_U.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(ex.PRE_CONNECT_PC,(()=>{this.emit(uU.PRE_CONNECT_PC)}))}}let bx=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),wx=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}({});function Ox(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 Nx(e){for(var t=1;t{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}}));const i=_N("GATEWAY_DOMAINS");let n=i[1]&&Dn(t).call(t,i[1])?1:0;return e.map((e=>{let{domain_prefix:t,port:r,ip:o}=e;if(t)return{address:"".concat(t,".").concat(i[n++%i.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(r):"".concat(o,":").concat(r);return s||YN.debug("Cannot recognized as ip address: ".concat(o,", use as host")),{ip:o,port:r,address:a}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function Ux(e,t){let i,n,r;switch(t){case wx.CHOOSE_SERVER:n=4096,r="choose server";break;case wx.CLOUD_PROXY:n=1048576,r="proxy";break;case wx.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case wx.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new tD(Ew.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=>Nx(Nx({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:Nx(Nx({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new tD(Ew.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function xx(e,t){return await Wh.all(e.addresses.map((async e=>({address:_N("USE_TURN_IP")?e.ip:Dx(e.ip),tcpport:e.port,udpport:e.port,username:t&&_N("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():aN.username,password:t&&_N("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await Nw(t.toString()):aN.password}))))}function Vx(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(Lx(e.height),Lx(e.width)),1):(YN.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function Fx(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:o,protocol:s}=e;const a={candidateType:t,relayProtocol:i,protocol:s};if("local-candidate"!==n){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),a.address=e.join("."),a.port=o}return a}function Bx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:_N("SVC_MODE");if(_N("ENABLE_SVC"))return function(e){return e in zO}(e)?e:zO.L1T3}const jx={[HU.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"}],[HU.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 Gx(e,t,i){t.forEach((t=>{var n;const r=jx[e].find((e=>{var i;let{key:n}=e;return Dn(i=t.extensionName).call(i,n)}));if(!r)return;const o=i.find((e=>{let{extensionName:t}=e;return Dn(t).call(t,r.key)}));o&&Dn(n=o.extensionName).call(n,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function Wx(e,t){t.forEach((t=>{var i;const n=jx[e].find((e=>{var i;let{key:n}=e;return Dn(i=t.extensionName).call(i,n)}));Dn(i=t.extensionName).call(i,"gdpr_forbidden")&&n&&(t.extensionName=n.extensionName)}))}function Hx(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Dn(e).call(e,"abs-send-time")}function Kx(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Dn(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function Yx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function qx(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(yN(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0))})),!p||0===u.length)throw new Error("Cannot get video capabilities from SDP.");if(!h||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");if(u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(l=l.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),u=u.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),s&&(l=l.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(l=l.filter((e=>{var t;return Dn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=u.filter((e=>{var t;return Dn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));u=e.concat(r?[]:hV(e,u))}const m=_N("UNSUPPORTED_VIDEO_CODEC");return m&&m.length>0&&(u=u.filter((e=>!(e.rtpMap&&Dn(m).call(m,e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p}}function Xx(e){const t=yN(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 Jx(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function Qx(e,t,i){const{cname:n}=e;let r=[];t&&(r=Zx(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:{}}))),YN.debug("Using candidates from gateway."));const o={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let a;switch(e.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}const c=dV(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach((e=>{d.push({kind:HU.VIDEO,ssrcId:e.v,rtx:e.v_rtx,mslabel:"".concat(e.v,"_").concat(e.a)},{kind:HU.AUDIO,ssrcId:e.a,mslabel:"".concat(e.v,"_").concat(e.a)})})),{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:c,setup:a,cname:n,preSSRCs:d}}function Zx(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:{}}],YN.debug("Using remote candidate from AP ".concat(e.ip,":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),YN.debug("Using IPV6 remote candidate from AP ".concat(e.ip6,":").concat(e.port)))),t}function $x(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=hO(8,"track-"),c={ssrcId:o,attributes:qx({label:a,mslabel:i=i||hO(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:qx({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:r}}function eV(e,t){t instanceof IL&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!Kb()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))}))}function tV(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 iV(e,t){var i;if(!(t instanceof pk&&t._encoderConfig&&-1===t._hints.indexOf(vD.SCREEN_TRACK)))return;const n=t._encoderConfig;nD().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin))})),nD().supportMinBitrate&&!Dn(i=t._hints).call(i,vD.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(_N("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))}))}function nV(e){if("video"!==e.media.mediaType)return;const t=xb();if(t.name!==Lb.SAFARI&&t.os!==Pb.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function rV(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=>Kx(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>Kx(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=>Kx(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=>Hx(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=>Hx(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function oV(e,t,i){if(Kb())return;if("video"!==e.media.mediaType)return;if(!(t instanceof pk))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!_N("SIMULCAST"))return;if("vp9"===i&&_N("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(await i.createOffer()).sdp,{send:r,recv:o,sendrecv:s}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=zx(i,e,t,"sendonly"),r=zx(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(cV(n,r,"videoExtensions",o,s,a),cV(n,r,"videoCodecs",o,s,a),cV(n,r,"audioExtensions",o,s,a),cV(n,r,"audioCodecs",o,s,a),_N("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];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&&fV(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!==_N("FIRST_H264_PROFILE_LEVEL_ID")||_N("FIRST_PACKETIZATION_MODE")&&l!==_N("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&&(YN.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=fV(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))}})),s.videoCodecs=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"])!==_N("FIRST_H264_PROFILE_LEVEL_ID"))})),_N("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"])!==_N("FIRST_H264_PROFILE_LEVEL_ID"))}))))}return{send:o,recv:s,sendrecv:a}}(e,t,n);try{i.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function aV(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=zx(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(cV(e,t,"videoExtensions",i,n,r),cV(e,t,"videoCodecs",i,n,r),cV(e,t,"audioExtensions",i,n,r),cV(e,t,"audioCodecs",i,n,r),_N("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:r}}function cV(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 dV(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=n,{send:r,recv:o}}function lV(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 uV(e,t,i,n){let r=[];if(e===HU.VIDEO){if(_N("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===_N("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Dn(i).call(i,n)?e.push(t):Dn(i).call(i,"vp9")?o.push(t):Dn(i).call(i,"vp8")?s.push(t):Dn(i).call(i,"h264")&&a.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==a.length&&(e=a,t="h264"),YN.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&&(YN.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),_N("USE_PUB_RTX")||_N("USE_SUB_RTX")){const e=hV(r,t.videoCodecs);r=[...r,...e]}}else r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)})),0===r.length&&(YN.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")})));return r}function hV(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Dn(i).call(i,e.fmtp&&e.fmtp.parameters.apt)))}async function pV(e,t,i){const n=t.toString(),r=EV(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=_V(s,i||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function _V(e,t,i){const n=yN(e),{useXR:r}=t;return n.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(i)&&!Dn(i).call(i,e.attributes.mid)||("audio"===e.media.mediaType&&lV(e),r&&Dn(t=["audio","video"]).call(t,e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),AN(n)}function EV(e,t,i,n){if(_N("SDP_LOGGING"))return YN.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{EV(e,"answer","local"===i?"remote":"local",n)}:void 0}function mV(e){const t=_N("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Dn(e).call(e,t)))}function fV(e,t){try{var i;return(null===(i=e.fmtp)||void 0===i?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}function TV(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 SV(e,t){return typeof _N(e)===t?_N(e):void 0}function gV(){try{const e=_N("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:function(e){for(var t=1;t1&&void 0!==arguments[1])||arguments[1])&&YN.debug("install service ".concat(e.name)),RV[e.name]=e}function CV(e){const t=RV[e];if(!t)throw new mw(Ew.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function IV(e,t){return CV("DataStream").create(e,t)}function yV(){return CV("InterceptFrame").create()}function AV(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 bV(e){for(var t=1;t{let{address:i}=t;const[n,r]=i.split(":"),o={host:n,port:r};return e.proxyServer&&(o.proxy=e.proxyServer),o}));o=(await this.signal.init(t)).uid,YN.debug("[".concat(this.store.clientId,"] websocket join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var a;throw YN.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),eD.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(a=t.data)||void 0===a?void 0:a.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!s,signalChannel:"0",preload:e.preload}),r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),YN.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{YN.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(LU.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(LU.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(LU.NETWORK_QUALITY,{uplinkNetworkQuality:Mx(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Mx(this._statsCollector.trafficStats.B_dnq)}):this.emit(LU.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),o}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==Vw.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==lU.CONNECTED||await function(e,t){return t===1/0?e:Wh.race([e,lO(t)])}(this.signal.request(hU.LEAVE,void 0,!0),3e3)}catch(e){YN.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==Vw.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new tD(Ew.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:_N("PUB_EXTEND"),twcc:!!_N("PUBLISH_TWCC"),rtx:!!_N("USE_PUB_RTX")};try{return(await this.signal.request(hU.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===dU.ERR_PUBLISH_REQUEST_INVALID)return YN.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 tD(Ew.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(hU.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===dU.ERR_PUBLISH_REQUEST_INVALID)return YN.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 tD(Ew.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(hU.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){YN.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new tD(Ew.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(hU.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){YN.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new tD(Ew.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:!!_N("SUBSCRIBE_TWCC"),rtx:!!_N("USE_SUB_RTX")||void 0,extend:_N("SUB_EXTEND"),svc:Array.isArray(_N("SVC"))&&0!==_N("SVC").length?_N("SVC"):void 0};try{return await this.signal.request(hU.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===dU.ERR_SUBSCRIBE_REQUEST_INVALID)return YN.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 tD(Ew.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:!!_N("SUBSCRIBE_TWCC"),rtx:!!_N("USE_SUB_RTX"),extend:_N("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(_N("SVC"))&&0!==_N("SVC").length?_N("SVC"):void 0};try{return(await this.signal.request(hU.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===dU.ERR_SUBSCRIBE_REQUEST_INVALID)return YN.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 tD(Ew.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(hU.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===dU.ERR_SUBSCRIBE_REQUEST_INVALID)return YN.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 tD(Ew.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!_N("USE_SUB_RTX"),twcc:!!_N("SUBSCRIBE_TWCC"),svc:Array.isArray(_N("SVC"))&&0!==_N("SVC").length?_N("SVC"):void 0};try{return await this.signal.request(hU.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===dU.ERR_SUBSCRIBE_REQUEST_INVALID)return YN.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(hU.SET_VIDEO_PROFILE,t);YN.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(hU.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){YN.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new tD(Ew.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Wh.all(e.map((e=>this.signal.request(hU.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){YN.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(hU.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){YN.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(hU.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(hU.GATEWAY_INFO)}async renewToken(e){await this.signal.request(hU.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),_N("CLIENT_ROLE_OPTIONS")&&(YN.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(_N("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},_N("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),_N("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},_N("CLIENT_ROLE_OPTIONS")),YN.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(_N("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,await this.signal.request(hU.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(hU.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(hU.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(hU.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(hU.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(hU.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),bV({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(hU.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=wV.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:aN.username,password:aN.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(bV(bV({},aN),{},{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(hU.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&&$w((()=>{this.emit(LU.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new tD(Ew.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=_N("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}var n;i&&i.length>128&&(i=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(LU.UPDATE_GATEWAY_CONFIG),n=this.store.clientId,Dn(SM).call(SM,n)||SM.push(n);const r=!(Kb()||zb(87)||oD())&&("boolean"==typeof _N("ENABLE_PRE_SUB")&&_N("ENABLE_PRE_SUB")),o=!oD()&&SV("ENABLE_PREALLOC_PC","boolean"),s=gV(),a=qb(87)||function(){const e=xb();if(e.name!==Lb.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}(),c=bV({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:rN,browser:navigator.userAgent,process_id:_N("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:_N("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:bV({enableEncodedTransform:!!_N("ENABLE_AUDIO_METADATA")&&a||!!_N("ENABLE_AUDIO_TOPN")&&Xb(Lb.CHROME,87,116)||void 0,enableAudioMetadata:!!_N("ENABLE_AUDIO_METADATA")&&a,enableAudioPts:!!_N("ENABLE_AUDIO_PTS_METADATA")&&a,topnSmoothLevel:_N("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:_N("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:_N("TOPN_SWITCH_HOLD_MS"),topnAudioGain:_N("TOPN_AUDIO_GAIN"),enablePublishedUserList:_N("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:_N("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:SV("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:SV("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:SV("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===_N("USE_PUB_RTX")||!0===_N("USE_SUB_RTX")||void 0,disableFEC:_N("DISABLE_FEC"),enableNTPReport:!!_N("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!_N("ENABLE_INSTANT_VIDEO")||void 0,enableFulllinkAvSync:!!_N("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:SV("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!_N("ENABLE_AUT_FEEDBACK")||void 0,rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!_N("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:SV("USE_XR","boolean"),enableLossbasedBwe:SV("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!_N("ENABLE_AUT_CC")||void 0,enableCCFallback:SV("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:o,preSubNum:r?SV("PRE_SUB_NUM","number"):void 0,enablePubTWCC:SV("PUBLISH_TWCC","boolean"),enableSubTWCC:SV("SUBSCRIBE_TWCC","boolean"),enablePubRTX:SV("USE_PUB_RTX","boolean"),enableSubRTX:SV("USE_SUB_RTX","boolean"),enableSubSVC:_N("ENABLE_SVC")?_N("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(_N("SVC"))&&0!==_N("SVC").length?_N("SVC"):void 0,enableSvcExtended:_N("ENABLE_SVC")&&Array.isArray(_N("SVC_EXTENDED"))&&0!==_N("SVC_EXTENDED").length?_N("SVC_EXTENDED"):void 0},s)},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(c.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(c.aes_mode=this.joinInfo.aesmode,_N("ENCRYPT_AES")?(c.aes_secret=this.joinInfo.aespassword,c.aes_encrypt=!0):c.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(c.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(c.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(c.default_video_stream=this.joinInfo.defaultVideoStream),c}getRejoinMessage(){if(!this.joinInfo)throw new tD(Ew.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(uU.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(uU.WS_RECONNECTING,(e=>{this.joinInfo&&eD.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Ww.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",eD.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(uU.WS_CLOSED,(e=>{let t;switch(e){case Vw.LEAVE:t=Ww.LEAVE;break;case Vw.UID_BANNED:case Vw.IP_BANNED:case Vw.CHANNEL_BANNED:case Vw.SERVER_ERROR:t=Ww.SERVER_ERROR;break;case Vw.FALLBACK:t=Ww.FALLBACK;break;case Vw.LICENSE_MISSING:case Vw.LICENSE_EXPIRED:case Vw.LICENSE_MINUTES_EXCEEDED:case Vw.LICENSE_PERIOD_INVALID:case Vw.LICENSE_MULTIPLE_SDK_SERVICE:case Vw.LICENSE_ILLEGAL:case Vw.TOKEN_EXPIRE:t=e;break;default:t=Ww.NETWORK_ERROR}YN.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+Ww.NETWORK_ERROR)),this.joinInfo&&eD.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===Vw.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==Vw.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(uU.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=_N("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(YN.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(eD.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void YN.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));pN("EVENT_REPORT_DOMAIN",e[1]),pN("EVENT_REPORT_BACKUP_DOMAIN",e[1]),pN("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(_U.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(uU.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new tD(Ew.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,Yw(this,LU.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(uU.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const r=eO(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(_N("NEW_TURN_MODE")&&r){let e=r.servers,t=r.serversFromGateway;const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],r.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],r.serversFromGateway=t),YN.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const{iceParameters:o,dtlsParameters:s,rtpCapabilities:a}=await Yw(this,LU.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:r});try{e(this.getJoinMessage({ortc:{iceParameters:o,dtlsParameters:s,rtpCapabilities:a,version:"2"}}))}catch(e){t(e)}})),this.signal.on(uU.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(uU.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var r;e instanceof tD?(i=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,n=e.message):i=e;eD.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload})})),this.signal.on(uU.IS_P2P_DISCONNECTED,(e=>{e(Xw(this,LU.IS_P2P_DISCONNECTED))})),this.signal.on(uU.DISCONNECT_P2P,(()=>{this.emit(LU.DISCONNECT_P2P)})),this.signal.on(uU.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(uU.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(uU.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(LU.JOIN_RESPONSE,e,t)})),this.signal.on(uU.PRE_CONNECT_PC,(async()=>{if(this.joinInfo){this.updateTurnConfigFromSignal();const e=this.getCurrentGatewayAddress(),t=_N("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(e&&t){const i=Zx(e);this.emit(LU.PRE_CONNECT_PC,{candidates:i,fingerprint:t})}}})),this.signal.on(uU.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof _N("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(_N("AP_REQUEST_DETAIL"),";").concat(e))}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(hU.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(hU.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw YN.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(hU.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(hU.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw YN.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(hU.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===PU.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(hU.CONTROL,i,!0,!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===PU.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(hU.CONTROL,i,!0,!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===HU.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(hU.CONTROL,i,!0,!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===HU.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(hU.CONTROL,i,!0,!0)}catch(e){throw YN.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(hU.RESTART_ICE,t,!0)}catch(e){throw YN.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||Ww.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!_N("GATEWAY_WSS_ADDRESS"))return _N("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(YN.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(hU.SET_PARAMETER,{enablePublishAudioFilter:e})}}let NV=0,DV=0;function PV(e,t,i,n){return new Wh(((r,o)=>{t.timeout=t.timeout||_N("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),NV+=cO(t.data)):i&&(t.data.size?NV+=t.data.size:t.data instanceof FormData?NV+=dO(t.data):NV+=cO(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Ab.request(t).then((e=>{"string"==typeof e.data?DV+=cO(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?DV+=e.data.byteLength:DV+=cO(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{Ab.isCancel(e)?o(new tD(Ew.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new tD(Ew.NETWORK_TIMEOUT,e.message)):e.response?o(new tD(Ew.NETWORK_RESPONSE_ERROR,e.response.status)):o(new tD(Ew.NETWORK_ERROR,e.message))}))}))} /*! formdata-polyfill. MIT License. Jimmy W?rting */!function(){var e;function i(e){var t=0;return function(){return t>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r{const e=_N("AREAS");0===e.length&&e.push(UU.GLOBAL);return Xn(e).call(e,((e,t,i)=>{const n=kV(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},kV=e=>e===UU.OVERSEA?"".concat(VU.ASIA,",").concat(VU.EUROPE,",").concat(VU.AFRICA,",").concat(VU.NORTH_AMERICA,",").concat(VU.SOUTH_AMERICA,",").concat(VU.OCEANIA):VU[e],MV=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=FU[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},UV={GLOBAL:{ASIA:[UU.CHINA,UU.JAPAN,UU.INDIA,UU.KOREA,UU.HKMC],EUROPE:[],NORTH_AMERICA:[UU.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},xV=Object.keys(UV[UU.GLOBAL]),VV=[UU.CHINA,UU.NORTH_AMERICA,UU.EUROPE,UU.ASIA,UU.JAPAN,UU.INDIA,UU.OCEANIA,UU.SOUTH_AMERICA,UU.AFRICA,UU.KOREA,UU.HKMC,UU.US],FV=function(e,t){let i=[];if(Dn(e).call(e,UU.GLOBAL)){const o=[UU.GLOBAL,UU.OVERSEA],s=Object.keys(FU);if(t===UU.GLOBAL)throw new tD(Ew.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===UU.CHINA)i=[UU.OVERSEA];else if(r=t,Dn(xV).call(xV,r)){const e=(n=t,UV[UU.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter((e=>!Dn(r).call(r,e)))}else if(function(e){let t=!1;return xV.forEach((i=>{var n;Dn(n=UV[UU.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return xV.forEach((i=>{var n;Dn(n=UV[UU.GLOBAL][i]).call(n,e)&&(t=i)})),t}(t),n=[...o,e,t];i=s.filter((e=>!Dn(n).call(n,e)))}else i=e;i=function(e){const t=[];return VV.forEach((i=>{Dn(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!Dn(VV).call(VV,e))))}(i)}else i=e;var n,r;return i};function BV(e){var t,i;if(!e&&Dn(t=_N("AREAS")).call(t,UU.EXTENSIONS))return YN.debug("update area from ap : reset"),void jV(mM,!0);if(!Dn(i=_N("AREAS")).call(i,UU.GLOBAL)||!e)return;let n=FU.EXTENSIONS;n&&(n={CODE:kV(UU.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")]},YN.debug("update area from ap success: ".concat(e,",config is "),n),pN("AREAS",[UU.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){pN(e,n[e][0])}else pN(e,n[e])})))}function jV(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=eD.reportApiInvoke(null,{name:kw.SET_AREA,options:e,tag:Mw.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Dn(xU).call(xU,e))throw new tD(Ew.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new tD(Ew.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?FV(r,i):r}if(!t){if(mN.AREAS){const e=new tD(Ew.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void YN.warning("setArea is prohibited because of config-distribute")}if(Dn(n).call(n,UU.GLOBAL)&&_N("AREAS")===UU.EXTENSIONS){const e=new tD(Ew.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void YN.warning("setArea is prohibited because of ap extensions")}}pN("AREAS",n,t);const r=MV(n);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){pN(e,r[e][0])}else pN(e,r[e])})),YN.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function GV(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 WV(e){for(var t=1;t{a=Date.now();const e=await PV(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 tD(Ew.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw YN.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new tD(Ew.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw YN.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new tD(Ew.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw YN.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(_N("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return _N("LIVE_STREAMING_ADDRESS")&&(r.addressList=_N("LIVE_STREAMING_ADDRESS")instanceof Array?_N("LIVE_STREAMING_ADDRESS"):[_N("LIVE_STREAMING_ADDRESS")]),WV(WV({},r),{},{responseTime:c})}),((n,r)=>(eD.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)=>(eD.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==Ew.OPERATION_ABORTED&&n.code!==Ew.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let YV=1;function qV(e,t,i,n){let{url:r,areaCode:o}=e;const{clientId:s,sid:a}=t,c=Date.now();let d;const l=t.role,[u,h]=ZV(t,o,[wx.CHOOSE_SERVER]);let p=Jw.networkState;return wO((async()=>{p&&Jw.networkState===Hw.OFFLINE&&Jw.onlineWaiter&&await Wh.race([Jw.onlineWaiter,uO(n&&n.maxRetryTimeout||AO.maxRetryTimeout)]),p=Jw.networkState;const{data:e,headers:o}=await PV(r,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===o.http3?1:-1,eD.reportResourceTiming(r,a),XV(e,r,t,c,[wx.CHOOSE_SERVER],d);const s=Ux(e,wx.CHOOSE_SERVER);return JV(s),Px(s,r)}),(e=>(e&&eD.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:h,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[wx.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38]}),!1)),(e=>e.code!==Ew.OPERATION_ABORTED&&(e.code===Ew.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eD.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:h,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[wx.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),YN.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function zV(e,t,i,n){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),d=t.role,[l,u]=ZV(t,s,a);let h;return wO((async()=>{h&&Jw.networkState===Hw.OFFLINE&&Jw.onlineWaiter&&await Wh.race([Jw.onlineWaiter,uO(n&&n.maxRetryTimeout||AO.maxRetryTimeout)]),h=Jw.networkState;const{data:e,headers:s}=await PV(o,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,eD.reportResourceTiming(o,t.sid),XV(e,o,t,c,a,r);const d=Ux(e,wx.CHOOSE_SERVER),u=Ux(e,"proxy5"===t.cloudProxyServer?wx.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?wx.CLOUD_PROXY:wx.CLOUD_PROXY_FALLBACK);return JV(d),{gatewayInfo:Px(d,o),proxyInfo:u,url:o}}),(e=>(e.gatewayInfo&&eD.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38]}),e.proxyInfo&&eD.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!==Ew.OPERATION_ABORTED&&(e.code===Ew.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eD.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:h})}),YN.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const XV=(e,t,i,n,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=i,d=[],l=a=>{4096===a.flag?eD.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||eD.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)YN.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 tD(Ew.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=lx(i),r={error:new tD(Ew.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?YN.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw YN.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 tD(Ew.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)))]})},JV=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new tD(Ew.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});_N("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?BV(e.detail[23].toLowerCase()):BV());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t0){YN.debug("assign gateway address to",_N("GATEWAY_ADDRESS"));const t=_N("GATEWAY_ADDRESS").map((t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r}}));e.addresses=t}},QV=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=lx(t.buffer.code);throw new tD(Ew.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw YN.debug("update ticket request received ap response without response body:",t),new tD(Ew.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},ZV=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r="host"===e.role?"1":"audience"===e.role?"2":void 0,o={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:WV(WV(WV({6:e.stringUid,11:t,12:_N("USE_NEW_TOKEN")?"1":void 0},r?{17:r}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};o.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const s=new FormData;return s.append("request",JSON.stringify(o)),[s,n]},$V=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};let eF=0;function tF(e){return Wh.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const iF=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:o}=e,s=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*a,t=e+a;return i.slice(e,t).map(n)})();o&&o.push(...e);try{c=await tF(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},nF=async e=>{let{referenceList:t,asyncMapHandler:i,closeFn:n}=e;const r=t.length;let o=0;const s=async()=>{const e=i(t.shift());try{return await e}catch(e){if(o++,o>=r||null!=n&&n(e))throw e;return s()}};return s()};async function rF(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=_N("WEBCS_DOMAIN").slice(0,_N("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:LV()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await iF({fragementLength:_N("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(YN.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),qV(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 uO(1e3),null!==r)return r;const s=_N("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:LV()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await iF({fragementLength:_N("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(YN.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),qV(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 tF([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 oF(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await rF(e,t,i,r);if(_N("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:o}=await lF(e,t,i,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:n};const a=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||aN.tcpport,udpport:e.udpport||aN.udpport,username:e.username||aN.username,password:e.password||aN.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:n.uid,i="glb:".concat(t.toString()),r=await Nw(i),c=o.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||aN.tcpport,udpport:e.udpport||aN.udpport,username:i,password:r,forceturn:!1,security:!0})));a.push(...c)}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:n}}return await rF(e,t,i,r)}const{proxyInfo:a,gatewayInfo:c}=await lF(e,t,i,r),d={gatewayInfo:c},l=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:aN.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:aN.udpport,username:e.username||aN.username,password:e.password||aN.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i="glb:".concat(t.toString()),n=await Nw(i),r=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||aN.tcpport,udpport:"proxy4"===o?void 0:e.udpport||aN.udpport,username:i,password:n,forceturn:"proxy4"!==o,security:"proxy5"===o})));l.push(...r)}return e.turnServer={mode:"manual",servers:l},YN.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),d}async function sF(e,t,i,n,r){const o=_N("ACCOUNT_REGISTER").slice(0,_N("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 wO((()=>PV(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 YN.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),eD.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:Ew.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new tD(Ew.INVALID_UINT_UID_FROM_STRING_UID);return eD.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=lx(i.code);return r.retry&&(a=e[(n+1)%e.length]),eD.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!==Ew.OPERATION_ABORTED&&(eD.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=lx(c.code);throw new tD(Ew.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 aF(e,t,i){const n=_N("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?n.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):n.map((e=>"https://".concat(e,"/api/v1")));try{const n=await nF({referenceList:r,asyncMapHandler:n=>async function(e,t,i,n){const r=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};try{const t=await PV(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=lx(t.code);throw new tD(Ew.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new tD(Ew.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:r,url:e,req:o,uid:t.uid,elapse:Date.now()-r}}catch(e){throw e}}(n,e,t,i),closeFn:e=>e.code===Ew.OPERATION_ABORTED||e.code===Ew.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function cF(e,t,i){const n=_N("CDS_AP").slice(0,_N("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=xb(),o={flag:64,cipher_method:0,features:WV(WV(WV(WV(WV({install_id:nN(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:rN,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:bx.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 wO((()=>PV(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==Ew.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,s=null,a={};try{o=await tF(r)}catch(e){if(e.code===Ew.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(eD.reportApiInvoke(e.sid,{name:kw.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=OT(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 dF(e,t){const i=_N("WEBCS_DOMAIN").concat(_N("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:LV(),serviceIds:[wx.CHOOSE_SERVER,wx.CLOUD_PROXY_FALLBACK]})));try{const n=await nF({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,{url:r,areaCode:o,serviceIds:s}=e;const a=Date.now(),[c,d]=ZV(t,o,s);let l=Jw.networkState;try{l&&Jw.networkState===Hw.OFFLINE&&Jw.onlineWaiter&&await Wh.race([Jw.onlineWaiter,uO(AO.maxRetryTimeout)]),l=Jw.networkState;const{data:e,headers:t}=await PV(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);n="1"===t.http3?1:-1;const o=e=>{const t=[];if(e.response_body.forEach((i=>{const n=i.buffer.code;if(23===i.uri&&0===n&&!i.buffer.edges_services)if(4194310===i.buffer.flag)i.buffer.edges_services=[];else{const n={error:new tD(Ew.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:i.buffer.flag};t.push(n)}if(0!==n){const r=lx(n),o={error:new tD(Ew.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:i.buffer.flag};4194310===i.buffer.flag?YN.warning(o.error.toString()):t.push(o)}})),t.length)throw new tD(Ew.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})};o(e);const s=Ux(e,wx.CHOOSE_SERVER),u=Ux(e,wx.CLOUD_PROXY_FALLBACK);return JV(s),{gatewayInfo:Px(s,r),proxyInfo:u,opid:d,requestTime:a,url:r,isHttp3:n,elapse:Date.now()-a}}catch(e){throw e}}(i,e,t),closeFn:e=>e.code===Ew.OPERATION_ABORTED||e.code===Ew.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function lF(e,t,i,n){const r=_N("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=_N("WEBCS_DOMAIN").slice(0,_N("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:LV(),serviceIds:[wx.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?wx.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?wx.CLOUD_PROXY:wx.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await iF({fragementLength:_N("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(YN.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),zV(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 uO(1e3),null!==s)return s;const r=_N("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:LV(),serviceIds:[wx.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?wx.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?wx.CLOUD_PROXY:wx.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await iF({fragementLength:_N("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(YN.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),zV(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await tF([c(),d()]))}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!u)throw new tD(Ew.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];Dn(r).call(r,t)&&(e.proxyServer=t,YN.setProxyServer(t),eD.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await xx(u,l.uid)},s}async function uF(e,t,i){const n=_N("UAP_AP").slice(0,_N("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))),r=n.map((n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:rN,cname:t.cname,uid:t.uid.toString(),requestId:YV,seq:YV};YV+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return wO((async()=>{const t=await PV(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new tD(Ew.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw YN.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new tD(Ew.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw YN.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new tD(Ew.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw YN.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(_N("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(_N("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==Ew.OPERATION_ABORTED&&e.code!==Ew.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),n)}(n,e,t,i)));try{const e=await tF(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function hF(e,t,i){let n=null;const r=[],o=async o=>{const s=_N(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 uO(1e3),null!==n)?n:await iF({fragementLength:_N("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(YN.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=$V(t,[wx.CHOOSE_SERVER]);let o=Jw.networkState;return wO((async()=>{o&&Jw.networkState===Hw.OFFLINE&&Jw.onlineWaiter&&await Wh.race([Jw.onlineWaiter,uO(n&&n.maxRetryTimeout||AO.maxRetryTimeout)]),o=Jw.networkState;const t=await PV(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return QV(t,e)}),(()=>!1),(e=>e.code!==Ew.OPERATION_ABORTED&&(e.code===Ew.UPDATE_TICKET_FAILED?e.data.retry:(YN.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 tF([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}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{this.updateConfigDistribute()}),_N("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;eD.reportApiInvoke(null,{options:void 0,name:kw.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:Mw.TRACER}).onSuccess(JSON.stringify(mN))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void YN.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await cF(this.joinInfo,this.cancelToken,this.retryConfig),YN.debug("[config-distribute] get config distribute",JSON.stringify(e));const i=function(e){var t;const i=vS(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;tt;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();let 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 tD(Ew.NETWORK_RESPONSE_ERROR,e);YN.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){jU(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(BU.UPDATE_BITRATE_LIMIT,e):this.emit(BU.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&_F({},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===EN.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(uN,e)||!RM()&&Object.prototype.hasOwnProperty.call(cN,e)?(d=1,!0):void 0)),n.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(r)})})),n.forEach((e=>{let{tag:t,feature:i,params:n,isApplied:r}=e;this.store.sessionId&&eD.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){YN.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]=_F(_F({value:n[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var i;const n=null===(i=t.LIMIT_BITRATE)||void 0===i?void 0:i.value;delete t.LIMIT_BITRATE,n&&jU(n)&&this.handleBitrateLimit(n),this.limit_bitrate=n,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{const{value:n,type:r,expires:o}=e[i];o&&o<=t||((r===EN.REALTIME||Object.prototype.hasOwnProperty.call(uN,i))&&(mN[i]=n,hN[i]=n,YN.debug("Update realtime parameters from config distribute",i,n)),r||RM()||!Object.prototype.hasOwnProperty.call(cN,i)||(mN[i]=n,hN[i]=n,YN.debug("Update gateway parameters from config distribute",i,n)))}))}catch(t){YN.error("Error update config immediately: ".concat(e),t.message)}}(t);const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),YN.debug("Caching global parameters ".concat(r))}catch(e){YN.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((i=>{if("CLIENT_ROLE_OPTIONS"===i)if(Object.prototype.hasOwnProperty.call(hN,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;(function(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}})(hN[i],n)||(mN[i]=n,hN[i]=n,this.emit(BU.UPDATE_CLIENT_ROLE_OPTIONS,n),YN.debug("Updating client role options: ".concat(JSON.stringify(n))))}}))}catch(e){YN.error("Error handling global parameter config:",e.message)}}}class mF extends Dw{constructor(){super(...arguments),QI(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(_N("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=Dn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",fF[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",fF[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof bL&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Lx(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof bL&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const fF={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const TF=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 SF(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 gF(e){for(var t=1;t{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new mF,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(zU.LocalAudioTrack)||gF({},DD)}getLocalVideoTrackStats(){return this.localStats.get(zU.LocalVideoTrack)||gF({},PD)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(zU.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(zU.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(zU.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?TF.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?TF.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&&YN.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case zU.LocalVideoTrack:case zU.LocalVideoLowTrack:{const t=n,o=gF({},PD),s=e.getStats(),a=e.getLocalMedia(i);if(s){const i=s.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(zU.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(o.codecType=i.codec),o.sendBytes=i.bytes,o.sendBitrate=t?8*Math.max(0,o.sendBytes-t.sendBytes):0,i.inputFrame?(o.captureFrameRate=i.inputFrame.frameRate,o.captureResolutionHeight=i.inputFrame.height,o.captureResolutionWidth=i.inputFrame.width):n&&(o.captureResolutionWidth=n.width,o.captureResolutionHeight=n.height),i.sentFrame?(o.sendFrameRate=i.sentFrame.frameRate,o.sendResolutionHeight=i.sentFrame.height,o.sendResolutionWidth=i.sentFrame.width):n&&(o.sendResolutionWidth=n.width,o.sendResolutionHeight=n.height),i.avgEncodeMs&&(o.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(o.targetSendBitrate=1e3*r.bitrateMax),o.sendPackets=i.packets,o.sendPacketsLost=i.packetsLost,o.sendJitterMs=i.jitterMs,o.sendRttMs=i.rttMs,o.totalDuration=t?t.totalDuration+1:1,o.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(o.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(YN.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(o.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;if(this.localStats.set(i,o),(null==t?void 0:t.sendResolutionWidth)!==o.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==o.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:o.sendResolutionWidth,height:o.sendResolutionHeight});o&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,o);break}case zU.LocalAudioTrack:{const t=n,r=gF({},DD),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(zU.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let[r,{videoStats:o,audioStats:s,videoPcStats:a}]=t;const c=s,d=o,l=a,u=gF({},LD),h=gF({},MD),p=gF({},kD),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let T;T=this.store.useP2P?e.getStats(!0):e.getStats();const S=null===(i=T)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===m)),g=null===(n=T)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===f)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(S&&("opus"!==S.codec&&"aac"!==S.codec&&"PCMU"!==S.codec&&"PCMA"!==S.codec&&"G722"!==S.codec||(u.codecType=S.codec),S.outputLevel?u.receiveLevel=Math.round(32767*S.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=S.bytes,u.receivePackets=S.packets,u.receivePacketsLost=S.packetsLost,u.receivePacketsDiscarded=S.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=S.jitterBufferMs,u.totalDuration>10&&RF.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),g){var v;"H264"!==g.codec&&"H265"!==g.codec&&"VP8"!==g.codec&&"VP9"!==g.codec&&"AV1X"!==g.codec&&"AV1"!==g.codec||(h.codecType=g.codec),h.receiveBytes=g.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,h.renderFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,g.outputFrame&&(h.renderFrameRate=g.outputFrame.frameRate),g.receivedFrame?(h.receiveFrameRate=g.receivedFrame.frameRate,h.receiveResolutionHeight=g.receivedFrame.height,h.receiveResolutionWidth=g.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==g.framesRateFirefox&&(h.receiveFrameRate=Math.round(g.framesRateFirefox)),h.receivePackets=g.packets,h.receivePacketsLost=g.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost);const t=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=null!==(v=g.totalFreezesDuration)&&void 0!==v?v:t||0,h.receiveDelay=g.jitterBufferMs||0;const n=!!f&&e.getRemoteVideoIsReady(f);void 0===g.totalFreezesDuration&&E&&n&&RF.isRemoteVideoFreeze(E,g,l)&&(h.totalFreezeTime+=1),h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-t)/(h.totalDuration-i),1))}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:u,videoStats:h,videoPcStats:g,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h)}))}}class vF{constructor(){QI(this,"destChannelMediaInfos",new Map),QI(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){bU(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){bU(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){fU(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function CF(e){if(!(e instanceof vF)){return new tD(Ew.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new tD(Ew.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new tD(Ew.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class IF{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){QI(this,"uid",void 0),QI(this,"_uintid",void 0),QI(this,"_trust_in_room_",!0),QI(this,"_trust_audio_enabled_state_",!0),QI(this,"_trust_video_enabled_state_",!0),QI(this,"_trust_audio_mute_state_",!0),QI(this,"_trust_video_mute_state_",!0),QI(this,"_audio_muted_",!1),QI(this,"_video_muted_",!1),QI(this,"_audio_enabled_",!0),QI(this,"_video_enabled_",!0),QI(this,"_audio_added_",!1),QI(this,"_video_added_",!1),QI(this,"_is_pre_created",!1),QI(this,"_video_pre_subscribed",!1),QI(this,"_audio_pre_subscribed",!1),QI(this,"_trust_video_stream_added_state_",!0),QI(this,"_trust_audio_stream_added_state_",!0),QI(this,"_audioTrack",void 0),QI(this,"_videoTrack",void 0),QI(this,"_dataChannels",[]),QI(this,"_audioSSRC",void 0),QI(this,"_videoSSRC",void 0),QI(this,"_audioOrtc",void 0),QI(this,"_videoOrtc",void 0),QI(this,"_cname",void 0),QI(this,"_rtxSsrcId",void 0),QI(this,"_videoMid",void 0),QI(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function yF(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 AF(e){for(var t=1;t=t.length-1&&n===DF.DOWN)return e;let o=NF(NF({},e),{},{scale:n===DF.DOWN?++r:--r});switch(i){case"maintain-framerate":o=NF(NF({},o),t[r].motion);break;case"maintain-resolution":o=NF(NF({},o),t[r].detail);break;case"balanced":o=NF(NF({},o),t[r].balanced)}return o}function kF(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:MF(t)};PF.set(e,i)}else PF.delete(e)}function MF(e){const t=NF({},e),{bitrateMax:i,frameRate:n,scaleResolutionDownBy:r,bitrateMin:o}=t,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:a,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:u,BWE_SCALE_DOWN_THRESHOLD:h,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:_,BALANCE_BITRATE_FACTOR:E,BALANCE_FRAMERATE_FACTOR:m,BALANCE_RESOLUTION_FACTOR:f,MOTION_RESOLUTION_FACTOR:T,MOTION_BITRATE_FACTOR:S,DETAIL_FRAMERATE_FACTOR:g,DETAIL_BITRATE_FACTOR:R}=dN,v=Math.min(t.frameRate,a),C=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(p,1)*v),fps_up:n},balanced:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(u,e)*i),bwe_down:Math.round(Math.pow(h,e+1)*i),fps_up:Math.round(Math.pow(_,e)*v),fps_down:Math.round(Math.pow(p,e+1)*v)},a={scaleResolutionDownBy:r/Math.pow(f,e),frameRate:Math.max(Math.round(Math.pow(m,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:r/Math.pow(T,e),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(S,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(S,e)*o),d)},I={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(g,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(R,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};C.push({scale:e,threshold:t,balanced:a,motion:c,detail:I})}return C}function UF(e,t,i,n,r,o){const s=PF.get(e)||{overUse:0,underUse:0,adaptationList:MF(r)},{adaptationList:a}=s;PF.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=dN,{scale:l}=n;let u,h;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let{threshold:{fps_down:r}}=i[t];return _N("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[0].threshold.fps_down),ec)||"number"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;const{threshold:{bwe_down:n}}=i[t];return ec)?(s.overUse=0,s.underUse=0,u=LF(n,a,o,DF.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let{threshold:{fps_up:r}}=i[t];return _N("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(r=i[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,i){if(0===t)return;const{threshold:{bwe_up:n}}=i[t];return e>n}(i,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=LF(n,a,o,DF.UP),0===u.scale&&(h=qO.NONE))),[u,h])}function xF(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 VF(e){for(var t=1;t=e}(14)&&Zb(17,4,!0)||Qb(14)&&$b(17,4,!0))))}const BF=new Map;function jF(e,t){const i=BF.get(e);if(i){const{timer:t}=i;window.clearTimeout(t),BF.delete(e)}t.qualityLimitationReason=qO.NONE,kF(e)}function GF(e,t){var i;let n;switch(t){case zU.LocalAudioTrack:n=PU.Audio;break;case zU.LocalVideoTrack:n=Dn(i=e._hints).call(i,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:n=PU.Low}return n}function WF(e){const t=nD();if(e.some((e=>e._bypassWebAudio)))throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function HF(e,t){WF(e);const i=t||new bL;return e.forEach((e=>i.addAudioTrack(e))),i}const KF=!nD().supportUnifiedPlan||_N("CHROME_FORCE_PLAN_B")&&dw();function YF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;return KF?(i={spec:t,store:e},CV("PlanBConnection").create(i)):new ZF(t,e)}function qF(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function zF(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(Fw(e.turnServer.servers))return!1;if(_N("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var XF;function JF(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 QF(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(TN)).call(t,e)})))]}constructor(t,i){super(t,i),QI(this,"id",hO(5,"connection-")),QI(this,"store",void 0),QI(this,"peerConnection",void 0),QI(this,"forceTurn",!1),QI(this,"remoteSDP",void 0),QI(this,"initialOffer",void 0),QI(this,"transportEventReceiver",void 0),QI(this,"statsFilter",void 0),QI(this,"extension",{useXR:_N("USE_XR")}),QI(this,"localCapabilities",void 0),QI(this,"remoteCodecs",void 0),QI(this,"localCandidateCount",0),QI(this,"allCandidatesReceived",!1),QI(this,"isPreallocation",!1),QI(this,"preSSRCMap",new Map),QI(this,"dataStreamChannelMap",new Map),QI(this,"establishPromise",void 0),QI(this,"recoveredDataChannelIds",[]),QI(this,"currentDataChannelId",1),QI(this,"supportAV1RtpSpec",!1),QI(this,"mutex",void 0),QI(this,"qualityLimitationReason",qO.NONE),QI(this,"isFirstConnected",!1),this.store=i,this.forceTurn=zF(t),this.mutex=new IO("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=tN(this.peerConnection,_N("STATS_UPDATE_INTERVAL"),void 0,Kb()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}getPreMedia(e){const t=this.preSSRCMap.get(e);if(void 0!==t){const e=this.peerConnection.getTransceivers().find((e=>e.mid===t));if(e)return{transceiver:e,track:e.receiver.track,id:t}}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void YN.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 YN.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=Xx(i.sdp),r=await sV({filterRTX:!_N("USE_PUB_RTX")&&!_N("USE_SUB_RTX"),filterVideoFec:_N("FILTER_VIDEO_FEC"),filterAudioFec:_N("FILTER_AUDIO_FEC"),filterVideoCodec:_N("FILTER_VIDEO_CODEC")},this.extension);if(this.localCapabilities=dV(r),this.initialOffer=i,_N("ENABLE_SVC")&&"av1"==this.store.codec){const t=await async function(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:zO.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=yN(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&&mV(i.sdp)&&(o=eO(r),(t=o).send&&(Wx(HU.VIDEO,t.send.videoExtensions),Wx(HU.AUDIO,t.send.audioExtensions)),t.recv&&(Wx(HU.VIDEO,t.recv.videoExtensions),Wx(HU.AUDIO,t.recv.audioExtensions)),t.sendrecv&&(Wx(HU.VIDEO,t.sendrecv.videoExtensions),Wx(HU.AUDIO,t.sendrecv.audioExtensions))),QF(QF({},n),{},{rtpCapabilities:o||r,offerSDP:i.sdp})}catch(e){throw new mw(Ew.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&&mV(this.initialOffer.sdp)&&(t=e.rtpCapabilities,i=this.localCapabilities,t.send&&(Gx(HU.VIDEO,t.send.videoExtensions,i.send.videoExtensions),Gx(HU.AUDIO,t.send.audioExtensions,i.send.audioExtensions)),t.recv&&(Gx(HU.VIDEO,t.recv.videoExtensions,i.recv.videoExtensions),Gx(HU.AUDIO,t.recv.audioExtensions,i.recv.audioExtensions))),this.remoteSDP=new class{get localCapabilities(){return eO(this._localCapabilities)}get rtpCapabilities(){return eO(this._rtpCapabilities)}get candidates(){return eO(this._candidates)}get iceParameters(){return eO(this._iceParameters)}get dtlsParameters(){return eO(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];QI(this,"sessionDesc",void 0),QI(this,"_localCapabilities",void 0),QI(this,"_rtpCapabilities",void 0),QI(this,"_candidates",void 0),QI(this,"_originCandidates",void 0),QI(this,"_iceParameters",void 0),QI(this,"_isUseExtmapAllowMixed",void 0),QI(this,"_dtlsParameters",void 0),QI(this,"setup",void 0),QI(this,"currentMidIndex",void 0),QI(this,"cname",void 0),QI(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,e=eO(e);const{iceParameters:i,dtlsParameters:n,candidates:r,rtpCapabilities:o,setup:s,localCapabilities:a,cname:c}=e;this._rtpCapabilities=o,this._candidates=r,this._originCandidates=eO(r),this._iceParameters=i,this._dtlsParameters=n,this._localCapabilities=a,this.setup=s,this.cname=c,this.sessionDesc=this.updateRemoteRTPCapabilities(o),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}preloadRemoteMedia(e){const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;let o=this.sessionDesc.mediaDescriptions.length-1;for(let s=1;se.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:l,ssrcGroups:u,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++o)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:bF,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:c,ssrcGroups:d,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++o)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return AN(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=$x(t,this.cname,_N("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Kb()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(Wb()||function(){const e=xb();return!(e.name!==Lb.CHROME||!e.osVersion)&&Number(e.version)<=90}()||_N("ENABLE_ENCODED_TRANSFORM")&&Gb())||0===t&&_N("USE_SUB_RTX")||tw()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=eO(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Kb()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||Kb()||tw()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||yN((i=this._isUseExtmapAllowMixed,"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;const n=this.rtpCapabilities.send,r=this.localCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(0===n.videoCodecs.length){const t=r.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"vp8")}))||[r.videoCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=n.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=n.videoCodecs,e.attributes.extmaps=n.videoExtensions,_N("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=$x([{ssrcId:wF,rtx:_N("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType)if(0===n.audioCodecs.length){const t=r.audioCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,"opus")}))||[r.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=n.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=n.audioCodecs,e.attributes.extmaps=n.audioExtensions,lV(e),_N("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=$x([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,this.sessionDesc}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(AF(AF({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case KU.TCP_RELAY:this._candidates=i;break;case KU.UDP_TCP_RELAY:case KU.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=eO(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Kb()){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:bF,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=uV(s,a,this.localCapabilities.send,s===HU.VIDEO?n:r),d=s===HU.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:bF,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(TN)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return YN.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return Dn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t)}))));if(0===o.length)return YN.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(YN.debug("updateRemoteCodec, from ".concat(n," to ").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&Dn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return YN.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(_N("USE_PUB_RTX")||_N("USE_SUB_RTX")){const e=hV(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=uV(HU.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));YN.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===HU.VIDEO?o.videoCodecs:o.audioCodecs,a=e===HU.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:bF,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=eO(e);return tV(n),eV(n,t),iV(n,t),nV(n),rV(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=eO(e);return rV(i,t,this.localCapabilities.recv),lV(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=>Kb()?"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}}(QF(QF({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const n=this.remoteSDP.toString(),r=_V(this.initialOffer.sdp,this.extension),o=this.logSDPExchange(r||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==o||o(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});const s=this.peerConnection.getTransceivers()[0];if(null!=s&&s.receiver&&this.tryBindTransportEvents(s.receiver),_N("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia(_N("PRELOAD_MEDIA_COUNT"));const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}const{preSSRCs:a}=e;if(Array.isArray(a)&&a.length>0){const{mids:e}=this.remoteSDP.batchSend(a.map((e=>({kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(a[t].ssrcId,e)})),await pV(this.peerConnection,this.remoteSDP,this.extension),YN.debug("[".concat(this.store.clientId,"] [P2PConnection] pre-batchReceive exchange SDP."))}}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}var t,i}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");const{rtpCapabilities:t}=e;this.remoteSDP.updateRemoteRTPCapabilities(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const{preSSRCs:i}=e;if(Array.isArray(i)&&i.length>0){const{mids:e}=this.remoteSDP.batchSend(i.map((e=>Object.assign({},{kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(i[t].ssrcId,e)}))}await pV(this.peerConnection,this.remoteSDP,this.extension),YN.debug("[P2PConnection] updateRemoteRTPCapabilities by exchanging SDP.")}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return FA((function*(){const r=yield BA(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=Bx();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,QF({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),Kb()&&!0===_N("SIMULCAST")&&(yield BA(n.applySimulcastForFirefox(o,e)));const a=yield BA(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(a.sdp,e,c),l=yN(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 Jx(t,_N("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 BA(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield BA(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield BA(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 BA(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield BA(n.applySimulcastEncodings(o,e)),yield BA(n.applySendEncodings(o,e)),null==_||_(p),yield BA(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 mw?e:new mw(Ew.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)YN.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:_N("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),YN.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else YN.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof mw?e:new mw(Ew.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 mw?e:new mw(Ew.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;jF(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 mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);o&&(await pV(this.peerConnection,this.remoteSDP,this.extension),YN.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:r,transceiver:s}}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await pV(this.peerConnection,this.remoteSDP,this.extension),YN.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preSSRCMap.entries()).some((t=>{let[i,n]=t;if(n===e)return this.preSSRCMap.delete(i),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new mw(Ew.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 mw(Ew.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 mw(Ew.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 mw(Ew.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 mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return FA((function*(){const i=yield BA(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=nD().supportPCSetConfiguration,r=_N("FORCE_TURN_TCP")||t.forceTurn;if(e===KU.RELAY&&!n)return;if(n&&!r){const i=e===KU.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(YN.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 BA(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=Xx(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield BA(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield BA(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){YN.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(KU.TCP_RELAY),await pV(this.peerConnection,this.remoteSDP,this.extension)}catch(e){YN.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{jF(this.id+e.mid,this)})),this.preSSRCMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return QF(QF({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new mw(Ew.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)?Kb()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:QF(QF({},FO),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:QF(QF({},FO),{},{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):"";YN.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(e.url||"",", 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&&YN.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,YN.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,YN.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),_N("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(Fw(t.turnServer.servers)?i.iceServers=t.turnServer.servers:_N("NEW_TURN_MODE")&&i.iceServers?(_N("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),_N("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),_N("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),_N("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),_N("ENABLE_ENCODED_TRANSFORM")&&nD().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Dx(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!_N("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=_N("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(Dx(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(Dx(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();YN.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,n;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return YN.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return YN.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!nD().supportSetRtpSenderParameters)return YN.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;case"balanced":r.degradationPreference="balanced"}const s=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack),a=kP(e);if(FF(e)&&s&&t&&a&&this.getLocalVideoStats&&Dn(i=["vp8","vp9"]).call(i,this.store.codec)){var c;const i=r.degradationPreference||(Dn(c=e._hints).call(c,vD.CUSTOM_TRACK)?_N("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");!function(e,t,i,n,r,o){if(jF(e,i),r(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;kF(e,t);const a=window.setInterval((()=>{const a=BF.get(e);if(!_N("ENABLE_AG_ADAPTATION")||!a)return jF(e,i),void r(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,[l,u]=UF(e,o,d,a.adaptationConfig,t,n);u&&(i.qualityLimitationReason=u),l&&a.adaptationConfig.scale!==l.scale&&(YN.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(l.scale," ")),a.adaptationConfig=VF(VF({},a.adaptationConfig),l),r(l))}}),_N("CHECK_LOCAL_STATS_INTERVAL")),c=VF({},t);BF.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),YN.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}(this.id+s.mid,a,this,i,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(o.maxBitrate=1e3*t),(Dn(d=e._hints).call(d,vD.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=Lx(i)),n&&n>=1&&(o.scaleResolutionDownBy=n))}const{maxFramerate:l}=_N("ENCODER_CONFIG_LIMIT");if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),_N("DSCP_TYPE")&&dw()){var u;const e=_N("DSCP_TYPE");Dn(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(n=h.encodings)||void 0===n?void 0:n[0];Kb()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),YN.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await async function(e,t,i){try{var n;if(!nD().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!_N("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];o.scalabilityMode=Bx(i),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),YN.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){YN.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,_N("SVC_MODE"))}async updateAdaptation(e,t){var i,n;if(!e)return YN.debug("[updateAdaptation] no rtpSender found");if(!nD().supportSetRtpSenderParameters)return YN.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},{bitrateMax:o,frameRate:s,scaleResolutionDownBy:a}=t;o&&(r.maxBitrate=1e3*o),s&&(r.maxFramerate=Lx(s)),a&&a>=1&&Dn(i=["vp8","vp9"]).call(i,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(n=c.encodings)||void 0===n?void 0:n[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),YN.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?YN.debug("[updateAdaptation] peerConnection not connected}"):YN.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):YN.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!nD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(eV(o,e),oV(o,e,this.store.codec))})),AN(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Kb()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(_N("SDP_LOGGING"))return YN.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(nD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},rU(XF.prototype,"updateRemoteRTPCapabilities",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"updateRemoteRTPCapabilities"),XF.prototype),rU(XF.prototype,"connect",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"connect"),XF.prototype),rU(XF.prototype,"updateRemoteConnect",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"updateRemoteConnect"),XF.prototype),rU(XF.prototype,"createDataChannels",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"createDataChannels"),XF.prototype),rU(XF.prototype,"receive",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"receive"),XF.prototype),rU(XF.prototype,"batchReceive",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"batchReceive"),XF.prototype),rU(XF.prototype,"stopReceiving",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"stopReceiving"),XF.prototype),rU(XF.prototype,"muteRemote",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"muteRemote"),XF.prototype),rU(XF.prototype,"unmuteRemote",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"unmuteRemote"),XF.prototype),rU(XF.prototype,"muteLocal",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"muteLocal"),XF.prototype),rU(XF.prototype,"unmuteLocal",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"unmuteLocal"),XF.prototype),rU(XF.prototype,"close",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"close"),XF.prototype),rU(XF.prototype,"updateEncoderConfig",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"updateEncoderConfig"),XF.prototype),rU(XF.prototype,"updateSendParameters",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"updateSendParameters"),XF.prototype),rU(XF.prototype,"replaceTrack",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"replaceTrack"),XF.prototype),rU(XF.prototype,"updateAdaptation",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"updateAdaptation"),XF.prototype),rU(XF.prototype,"getRemoteSSRC",[$F],Object.getOwnPropertyDescriptor(XF.prototype,"getRemoteSSRC"),XF.prototype),XF);function $F(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(YN.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=iP((()=>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),YN.debug("clean low stream renderer")},c}var tB=function(e){return e[e.HEIGHT=2033]="HEIGHT",e[e.FRAME_RATE=2034]="FRAME_RATE",e[e.WIDTH=2035]="WIDTH",e}(tB||{}),iB=function(e){return e[e.FRAME_RATE=2002]="FRAME_RATE",e[e.WIDTH=2003]="WIDTH",e[e.HEIGHT=2004]="HEIGHT",e[e.PACKAGE_LOST=2005]="PACKAGE_LOST",e[e.AVG_ENCODE=2007]="AVG_ENCODE",e[e.NACKS=2009]="NACKS",e[e.PLIS=2010]="PLIS",e[e.FIRS=2011]="FIRS",e[e.BITRATE=2012]="BITRATE",e[e.PACKAGE_RATE=2031]="PACKAGE_RATE",e[e.ADAPTATION=2032]="ADAPTATION",e[e.ACTUAL_ENCODED=2060]="ACTUAL_ENCODED",e[e.BANDWIDTH=2061]="BANDWIDTH",e[e.RETRANSMIT=2062]="RETRANSMIT",e[e.TARGET_ENCODED=2064]="TARGET_ENCODED",e[e.TRANSMIT=2066]="TRANSMIT",e[e.FREEZE=2082]="FREEZE",e[e.DISABLED=2095]="DISABLED",e[e.PLAYER_STATUS=2128]="PLAYER_STATUS",e[e.QP_SUM=2143]="QP_SUM",e[e.BYTES_RETRANSMIT=2173]="BYTES_RETRANSMIT",e[e.PACKAGES_RETRANSMIT=2172]="PACKAGES_RETRANSMIT",e[e.HUGE_FRAME_SENT=2174]="HUGE_FRAME_SENT",e[e.KEY_FRAMES_ENCODED=2207]="KEY_FRAMES_ENCODED",e}(iB||{}),nB=function(e){return e[e.BITRATE=2069]="BITRATE",e[e.PACKAGE_LOST=2070]="PACKAGE_LOST",e[e.PACKAGE_RATE=2071]="PACKAGE_RATE",e[e.HEIGHT=2073]="HEIGHT",e[e.FRAME_RATE=2075]="FRAME_RATE",e[e.WIDTH=2077]="WIDTH",e}(nB||{}),rB=function(e){return e[e.JITTER=-1]="JITTER",e[e.PACKAGE_LOST=2014]="PACKAGE_LOST",e[e.WIDTH=2018]="WIDTH",e[e.HEIGHT=2019]="HEIGHT",e[e.FRAME_RATE=2020]="FRAME_RATE",e[e.JITTER_BUFFER=2023]="JITTER_BUFFER",e[e.CURRENT_DELAY=2024]="CURRENT_DELAY",e[e.NACKS=2026]="NACKS",e[e.PLIS=2027]="PLIS",e[e.FIRS=2028]="FIRS",e[e.BITRATE=2029]="BITRATE",e[e.PACKAGE_RATE=2078]="PACKAGE_RATE",e[e.FREEZE=2084]="FREEZE",e[e.DISABLED=2101]="DISABLED",e[e.PLAYER_STATUS=2129]="PLAYER_STATUS",e[e.QP_SUM=2144]="QP_SUM",e[e.I_FRAME_DELAY=2149]="I_FRAME_DELAY",e[e.FRAMES_DROPPED=2181]="FRAMES_DROPPED",e[e.BYTES_RETRANSMIT=2175]="BYTES_RETRANSMIT",e[e.PACKAGES_RETRANSMIT=2176]="PACKAGES_RETRANSMIT",e[e.PACKAGES_DISCARDED=2198]="PACKAGES_DISCARDED",e[e.AVG_DECODE=2200]="AVG_DECODE",e[e.AVG_PROCESSING_DELAY=2202]="AVG_PROCESSING_DELAY",e[e.AVG_ASSEMBLY_TIME=2203]="AVG_ASSEMBLY_TIME",e[e.AVG_INTER_FRAME_DELAY=2204]="AVG_INTER_FRAME_DELAY",e[e.KEY_FRAMES_DECODED=2206]="KEY_FRAMES_DECODED",e}(rB||{}),oB=function(e){return e[e.FRAME_RATE_DECODE=2021]="FRAME_RATE_DECODE",e[e.FRAME_RATE_RENDER=2022]="FRAME_RATE_RENDER",e[e.FRAME_RATE_OUTPUT=2155]="FRAME_RATE_OUTPUT",e[e.FREEZE_TIME=2109]="FREEZE_TIME",e[e.FREEZE_TIME_RENDER=2147]="FREEZE_TIME_RENDER",e[e.FREEZE_DURATION=2156]="FREEZE_DURATION",e}(oB||{}),sB=function(e){return e[e.PCM_LEVEL=2104]="PCM_LEVEL",e}(sB||{}),aB=function(e){return e[e.PACKAGE_LOST=-1]="PACKAGE_LOST",e[e.LEVEL=2038]="LEVEL",e[e.BITRATE=2039]="BITRATE",e[e.PACKAGE_RATE=2040]="PACKAGE_RATE",e[e.AEC_RETURN_LOSS=2041]="AEC_RETURN_LOSS",e[e.AEC_RETURN_LOSS_ENH=2042]="AEC_RETURN_LOSS_ENH",e[e.FREEZE=2081]="FREEZE",e[e.DISABLED=2096]="DISABLED",e[e.BYTES_RETRANSMIT=2179]="BYTES_RETRANSMIT",e[e.PACKAGES_RETRANSMIT=2180]="PACKAGES_RETRANSMIT",e}(aB||{}),cB=function(e){return e[e.BITRATE=2044]="BITRATE",e[e.PACKAGE_LOST=2045]="PACKAGE_LOST",e[e.PACKAGE_RATE=2046]="PACKAGE_RATE",e[e.CURRENT_DELAY=2047]="CURRENT_DELAY",e[e.JITTER_BUFFER=2054]="JITTER_BUFFER",e[e.JITTER=2055]="JITTER",e[e.FREEZE=2083]="FREEZE",e[e.DISABLED=2102]="DISABLED",e[e.PCM_LEVEL=2105]="PCM_LEVEL",e[e.PLAYER_STATUS=2130]="PLAYER_STATUS",e[e.CONCEALED_SAMPLES=2148]="CONCEALED_SAMPLES",e[e.BYTES_RETRANSMIT=2178]="BYTES_RETRANSMIT",e[e.PACKAGES_RETRANSMIT=2177]="PACKAGES_RETRANSMIT",e[e.PACKAGES_DISCARDED=2199]="PACKAGES_DISCARDED",e[e.AVG_PROCESSING_DELAY=2201]="AVG_PROCESSING_DELAY",e[e.TOTAL_SAMPLES_RECEIVED=2224]="TOTAL_SAMPLES_RECEIVED",e}(cB||{}),dB=function(e){return e[e.FREEZE_TIME=-1]="FREEZE_TIME",e[e.LEVEL=2043]="LEVEL",e}(dB||{}),lB=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}(lB||{}),uB=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e}(uB||{});const hB=1e3,pB=6,_B=3,EB=Math.max(pB,_B);function mB(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function fB(e){const t={[lB.CONN_TYPE]:0,[lB.RTT]:e.rtt,[lB.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[lB.CONN_TYPE]=1),"tcp"===i&&(t[lB.CONN_TYPE]=3),"tls"===i&&(t[lB.CONN_TYPE]=4);break}case"srflx":t[lB.CONN_TYPE]=2;break;case"unknown":t[lB.CONN_TYPE]=5;break;default:t[lB.CONN_TYPE]=0}return t}function TB(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 SB extends Dw{constructor(e){super(),QI(this,"store",void 0),QI(this,"uploadWRTCStatsTimer",void 0),QI(this,"uploadOutboundDenoiserStatsTimer",void 0),QI(this,"uploadExtStatsTimer",void 0),QI(this,"uploadExtUsageStatsTimer",void 0),QI(this,"uploadInboundExtStatsTimer",void 0),QI(this,"requestStats",void 0),QI(this,"requestTransportStats",void 0),QI(this,"requestLocalMedia",void 0),QI(this,"requestRemoteMedia",void 0),QI(this,"requestAllTracks",void 0),QI(this,"requestVideoIsReady",void 0),QI(this,"requestUploadStats",void 0),QI(this,"requestUpload",void 0),QI(this,"uploadOutboundStarted",!1),QI(this,"uploadInboundStarted",!1),QI(this,"uploadTransportStarted",!1),QI(this,"uploadBaseStatsStarted",!1),QI(this,"uploadExtensionUsageStarted",!1),QI(this,"lastRecvStats",void 0),QI(this,"lastSendStats",void 0),QI(this,"lastRefRecvStats",void 0),QI(this,"lastRefSendStats",void 0),QI(this,"lastFullRecvStats",void 0),QI(this,"lastFullSendStats",void 0),QI(this,"needUploadRenderFreezeTime",!0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%_B==0,i=e%pB==0;let n,r;if(this.uploadTransportStarted&&(n=this.requestStats(),this.store.useP2P&&(r=this.requestStats(!0))),!n&&this.uploadOutboundStarted&&(n=this.requestStats()),!r&&this.uploadInboundStarted&&(r=this.requestStats(!0)),n||r){var o;const e={};if(this.uploadTransportStarted&&n){const i=this.getTransportStats(n,r,t);i&&(e.misc=[i])}if(this.uploadOutboundStarted&&n){const r=this.getOutboundStats(n,i?this.lastFullSendStats:t?this.lastRefSendStats:this.lastSendStats,t,i);r&&(e.outbound=[r])}if(this.uploadInboundStarted&&r){const n=this.getInboundStats(r,i?this.lastFullRecvStats:t?this.lastRefRecvStats:this.lastRecvStats,t,i);n&&(e.inbound=n)}const s=null===(o=this.requestTransportStats)||void 0===o?void 0:o.call(this).connectState;s&&(Array.isArray(e.misc)?e.misc[0]&&e.misc[0].addition&&(e.misc[0].addition[uB.RTC_PEER_CONNECTION_STATE]=XO[s]):e.misc=[{addition:{[uB.RTC_PEER_CONNECTION_STATE]:XO[s]}}]),this.requestUploadStats(e)}this.lastRecvStats=r,this.lastSendStats=n,i&&(this.lastFullRecvStats=r,this.lastFullSendStats=n),t&&(this.lastRefRecvStats=r,this.lastRefSendStats=n)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0;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:{[uB.RTC_PEER_CONNECTION_STATE]:XO[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===EB+1&&(e=1)}),hB)}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0)}getTransportStats(e,t,i){if(!this.requestStats)return;if(!i)return null==e.rtt?void 0:{addition:{[lB.RTT]:e.rtt,[lB.CONN_TYPE]:void 0,[lB.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const n=fB(e);if(this.store.useP2P){if(t){const e=fB(t);n[lB.CONN_TYPE]+=e[lB.CONN_TYPE]<<3}n[lB.CONN_TYPE]+=110}else n[lB.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i,n){if(!this.requestUploadStats||!this.requestLocalMedia)return;const r=this.requestLocalMedia();if(!r||0===r.length)return;let o,s,a;return r.forEach((r=>{let[c,{track:d,ssrcs:l}]=r;switch(c){case zU.LocalVideoLowTrack:case zU.LocalVideoTrack:if(c===zU.LocalVideoTrack){const r=function(e,t,i,n,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},{sentFrame:c,inputFrame:d}=s;if(o&&(mB(a,iB.QP_SUM,s.qpSumPerFrame),d&&c)){const e=d.frameRate,t=c.frameRate;a[iB.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&&(mB(a,iB.HEIGHT,c.height),mB(a,iB.WIDTH,c.width),mB(a,iB.FRAME_RATE,c.frameRate)),a[iB.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[iB.ADAPTATION]=0;break;case"cpu":a[iB.ADAPTATION]=1;break;case"bandwidth":a[iB.ADAPTATION]=2;break;case"other":a[iB.ADAPTATION]=3}let o=0;s.adaptionChangeReason&&(o+=TB(s.adaptionChangeReason)),t.qualityLimitationReason&&(o+=TB(t.qualityLimitationReason)<<3),a[iB.ADAPTATION]=o,a[iB.PLAYER_STATUS]=GD[n._player?n._player.videoElementStatus:"uninit"],mB(a,iB.NACKS,s.nacksCount),mB(a,iB.PLIS,s.plisCount),mB(a,iB.FIRS,s.firsCount),mB(a,iB.AVG_ENCODE,s.avgEncodeMs),mB(a,iB.HUGE_FRAME_SENT,s.hugeFramesSent),mB(a,iB.BYTES_RETRANSMIT,s.retransmittedBytesSent),mB(a,iB.PACKAGES_RETRANSMIT,s.retransmittedPacketsSent),mB(a,iB.KEY_FRAMES_ENCODED,s.keyFramesEncoded);const d=i&&i.videoSend.find((t=>t.ssrc===e));if(d){let e=r?hB:hB*pB;d.timestamp&&s.timestamp&&(e=s.timestamp-d.timestamp),null!=d.packets&&null!=s.packets&&mB(a,iB.PACKAGE_RATE,1e3*(s.packets-d.packets)/e),null!=s.packetsLost&&null!=d.packetsLost&&mB(a,iB.PACKAGE_LOST,s.packetsLost-d.packetsLost),null!=d.bytes&&null!=s.bytes&&mB(a,iB.BITRATE,8*(s.bytes-d.bytes)/e)}}return a}(l[0].ssrcId,e,t,d,i,n),o=d&&function(e,t,i,n){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(n){const e=r.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,s=e&&e.frameRate||0;mB(o,tB.HEIGHT,t),mB(o,tB.WIDTH,n),mB(o,tB.FRAME_RATE,s)}return o}(l[0].ssrcId,e,d,i),a=function(e,t){const i={};return t&&(mB(i,iB.RETRANSMIT,e.bitrate.retransmit),mB(i,iB.TARGET_ENCODED,e.bitrate.targetEncoded),mB(i,iB.ACTUAL_ENCODED,e.bitrate.actualEncoded),mB(i,iB.TRANSMIT,e.bitrate.transmit),mB(i,iB.BANDWIDTH,e.sendBandwidth)),i}(e,i);s=Object.assign({},r,o,a)}else a=function(e,t,i,n){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return;const o={};if(n){const t=r.sentFrame;if(t&&(mB(o,nB.HEIGHT,t.height),mB(o,nB.WIDTH,t.width),mB(o,nB.FRAME_RATE,t.frameRate)),i){const t=i.videoSend.find((t=>t.ssrc===e));if(t){let e=hB*pB;t.timestamp&&r.timestamp&&(e=r.timestamp-t.timestamp),null!=t.packets&&null!=r.packets&&mB(o,nB.PACKAGE_RATE,1e3*(r.packets-t.packets)/e),null!=r.packetsLost&&null!=t.packetsLost&&mB(o,nB.PACKAGE_LOST,r.packetsLost-t.packetsLost),null!=t.bytes&&null!=r.bytes&&mB(o,nB.BITRATE,8*(r.bytes-t.bytes)/e)}}}return o}(l[0].ssrcId,e,t,i);break;case zU.LocalAudioTrack:o=d&&function(e,t,i,n,r){const o=t.audioSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(r){s[aB.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const t=100*n._source.getAccurateVolumeLevel(),r=o.inputLevel;if(null!=r){const e=Math.ceil(50*Math.log10(100*r+1));mB(s,aB.LEVEL,e)}mB(s,sB.PCM_LEVEL,t),mB(s,aB.AEC_RETURN_LOSS,o.aecReturnLoss),mB(s,aB.AEC_RETURN_LOSS_ENH,o.aecReturnLossEnhancement),mB(s,aB.BYTES_RETRANSMIT,o.retransmittedBytesSent),mB(s,aB.PACKAGES_RETRANSMIT,o.retransmittedPacketsSent),s[aB.FREEZE]=0;const a=i&&i.audioSend.find((t=>t.ssrc===e));if(a){let e=hB*pB;a.timestamp&&o.timestamp&&(e=o.timestamp-a.timestamp),null!=a.bytes&&null!=o.bytes&&mB(s,aB.BITRATE,8*(o.bytes-a.bytes)/e),null!=a.packets&&null!=o.packets&&mB(s,aB.PACKAGE_RATE,1e3*(o.packets-a.packets)/e)}}return s}(l[0].ssrcId,e,t,d,i)}})),{high:s,low:a,audio:o}}getInboundStats(e,t,i,n){if(!this.requestRemoteMedia)return;const r=this.requestRemoteMedia()||[],o=[];return r.forEach((r=>{let[s,a]=r;const c={peer:s.uid};if(a.has(HU.VIDEO)&&s.videoTrack){const r=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,o=s.videoTrack?function(e,t,i,n,r,o,s,a){const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},{receivedFrame:l,outputFrame:u,decodeFrameRate:h}=c,p=i&&i.videoRecv.find((t=>t.ssrc===e));if(mB(d,oB.FRAME_RATE_DECODE,h),c.framesRateFirefox&&mB(d,rB.FRAME_RATE,c.framesRateFirefox),l&&mB(d,rB.FRAME_RATE,l.frameRate),mB(d,rB.FRAMES_DROPPED,c.framesDroppedCount),mB(d,rB.BYTES_RETRANSMIT,c.retransmittedBytesReceived),mB(d,rB.PACKAGES_RETRANSMIT,c.retransmittedPacketsReceived),mB(d,rB.PACKAGES_DISCARDED,c.packetsDiscarded),mB(d,rB.AVG_DECODE,c.avgDecodeMs),mB(d,rB.AVG_PROCESSING_DELAY,c.avgProcessingDelayMs),mB(d,rB.AVG_ASSEMBLY_TIME,c.avgFramesAssembledFromMultiplePacketsMs),mB(d,rB.AVG_INTER_FRAME_DELAY,c.avgInterFrameDelayMs),mB(d,rB.KEY_FRAMES_DECODED,c.keyFramesDecoded),p){const e=t.timestamp-i.timestamp||hB*(a?pB:s?_B:1);null!=c.packetsLost&&null!=p.packetsLost&&mB(d,rB.PACKAGE_LOST,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&mB(d,rB.BITRATE,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&mB(d,rB.PACKAGE_RATE,1e3*(c.packets-p.packets)/e)}if(a&&(mB(d,rB.QP_SUM,c.qpSumPerFrame),d[rB.FREEZE]=r&&RF.isRemoteVideoFreeze(n,c,p)?1:0),s){var _;l?(mB(d,rB.HEIGHT,l.height),mB(d,rB.WIDTH,l.width)):n&&(mB(d,rB.HEIGHT,n._videoHeight||0),mB(d,rB.WIDTH,n._videoWidth||0)),u&&mB(d,oB.FRAME_RATE_OUTPUT,u.frameRate);const e=null===(_=n._player)||void 0===_?void 0:_.rendFrameRate.toFixed(0);if(e&&mB(d,oB.FRAME_RATE_RENDER,+e),mB(d,rB.JITTER_BUFFER,c.jitterBufferMs),mB(d,rB.CURRENT_DELAY,c.currentDelayMs),mB(d,rB.FIRS,c.firsCount),mB(d,rB.NACKS,c.nacksCount),mB(d,rB.PLIS,c.plisCount),n){d[rB.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i,videoElementStatus:n}=e;if(t&&t.length>0&&mB(d,oB.FREEZE_TIME,t.splice(0,1)[0]),o&&"visible"===Dk.visibility&&n===BD.PLAYING&&nD().supportRequestVideoFrameCallback){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),mB(d,oB.FREEZE_TIME_RENDER,t)}if("number"==typeof c.totalFreezesDuration){const e=p&&p.totalFreezesDuration?c.totalFreezesDuration-p.totalFreezesDuration:c.totalFreezesDuration;mB(d,oB.FREEZE_DURATION,1e3*e)}}}if(d[rB.PLAYER_STATUS]=GD[n._player?n._player.videoElementStatus:"uninit"],p&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==p.totalInterFrameDelay&&void 0!==p.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-p.totalInterFrameDelay,t=c.totalSquaredInterFrameDelay-p.totalSquaredInterFrameDelay,i=c.framesDecodeCount-p.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(d[rB.I_FRAME_DELAY]=r)}}return d}(s._videoSSRC,e,t,s.videoTrack,!0===r,this.needUploadRenderFreezeTime,i,n):void 0;o&&(c.video=o)}if(a.has(HU.AUDIO)&&s.audioTrack){const r=s.audioTrack?function(e,t,i,n,r,o){const s=t.audioRecv.find((t=>t.ssrc===e));if(!s)return;const a={},c=i&&i.audioRecv.find((t=>t.ssrc===e));if(mB(a,cB.JITTER,s.jitterMs),mB(a,cB.BYTES_RETRANSMIT,s.retransmittedBytesReceived),mB(a,cB.PACKAGES_RETRANSMIT,s.retransmittedPacketsReceived),mB(a,cB.PACKAGES_DISCARDED,s.packetsDiscarded),mB(a,cB.AVG_PROCESSING_DELAY,s.avgProcessingDelayMs),c){const e=t.timestamp-i.timestamp||hB*(o?pB:r?_B:1);null!=s.packets&&null!=c.packets&&mB(a,cB.PACKAGE_RATE,1e3*(s.packets-c.packets)/e),r&&null!=c.bytes&&null!=s.bytes&&mB(a,cB.BITRATE,8*(s.bytes-c.bytes)/e),null!=s.packetsLost&&null!=c.packetsLost&&mB(a,cB.PACKAGE_LOST,s.packetsLost-c.packetsLost)}if(o){const{receivedFrames:e,droppedFrames:t}=s;null!=e&&null!=t&&(a[cB.FREEZE]=0===(d=e)||100*t/d>20?1:0)}var d;if(r){const e=100*n._source.getAccurateVolumeLevel(),t=s.outputLevel;if(null!=t){const e=Math.ceil(50*Math.log10(100*t+1));mB(a,dB.LEVEL,e)}if(mB(a,cB.PCM_LEVEL,e),n&&(a[cB.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),mB(a,cB.JITTER_BUFFER,s.jitterBufferMs),mB(a,cB.CURRENT_DELAY,s.jitterBufferMs),a[cB.PLAYER_STATUS]=GD[vP.getPlayerState(n.getTrackId())],c){const e=s.concealedSamples-c.concealedSamples;e>0&&mB(a,cB.CONCEALED_SAMPLES,e);const t=s.totalSamplesReceived-c.totalSamplesReceived;t>0&&mB(a,cB.TOTAL_SAMPLES_RECEIVED,t)}}return a}(s._audioSSRC,e,t,s.audioTrack,i,n):void 0;r&&(c.audio=r)}(c.video||c.audio)&&o.push(c)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,o}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof yL));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(pU.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let[t,i]=e;if(i.has(HU.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(HU.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:_N("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of o)t.has(HU.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(HU.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:s,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(s))&&void 0!==n?n:0,l=2===a?e+_N("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,o;t.set(s,l),i[s]?(2===a&&(i[s].value=a),c>i[s].level&&(i[s].level=c),"remote"===d&&(i[s].remoteUidCount+=1),i[s].totalTs=null!==(r=t.get(s))&&void 0!==r?r:0):i[s]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(s))&&void 0!==o?o:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}}))}(n,e);const s=Date.now(),a=s>t?s:t+1;this.requestUpload&&this.requestUpload(pU.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a})}),_N("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1}}const gB=_N("ICE_RESTART_INTERVAL");let RB=new Map,vB=new Map,CB=[KU.UDP_TCP_RELAY,KU.TCP_RELAY,KU.RELAY],IB=_N("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&nD().supportPCSetConfiguration;function yB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=RB.get(e.id);i&&(window.clearTimeout(i),RB.delete(e.id));const n=vB.get(e.id);t&&n&&n.index===CB.length-1&&(YN.debug("[".concat(e.id,"] reset ICE restart policy")),vB.delete(e.id))}function AB(e,t,i){if(0===RB.size&&0===vB.size&&(Array.isArray(_N("RESTART_SEQUENCE"))&&_N("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let i=0;ie===n)).length!==t.filter((e=>e===n)).length)return!1}return!0}(CB,_N("RESTART_SEQUENCE"))&&(CB=_N("RESTART_SEQUENCE").filter((e=>{var t;if(Dn(t=Object.values(KU)).call(t,e))return!0})),YN.debug("use reconnection policy from config distribution, queues: ".concat(CB.join(" => ")))),IB=_N("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&nD().supportPCSetConfiguration),0===CB.length)return void i();let n,{index:r=0,type:o}=vB.get(e.id)||{};if(IB&&o===KU.RELAY)return void i();let s=o&&r>=CB.length-1;if(IB)o=KU.RELAY;else{if(s)return void i();o?(r++,o=CB[r]):(o=CB[0],r=0)}YN.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(o,", index: ").concat(r)),t(o),vB.set(e.id,{index:r,type:o}),n=window.setTimeout((()=>AB(e,t,i)),gB),RB.set(e.id,n)}var bB;function wB(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 OB(e){for(var t=1;t{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==XU.Connected)return void i(new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){o[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(r);await qw(this,JU.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),QI(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==XU.Connected)return void i(new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const t=o[1];if(t.track._originMediaStreamTrack.stop(),!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=eB(e,Xw(this,JU.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r);await qw(this,JU.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),QI(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(zU.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==XU.Connected)return void t();const{id:n,track:s}=i;await this.connection.updateSendParameters(n,s),await this.connection.updateEncoderConfig(n,s),this.emit(JU.UpdateVideoEncoder,s),t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),QI(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(zU.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==XU.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),QI(this,"handleReplaceMixingTrack",(async(e,t,i,n)=>{if(!this.connection||this.state!==XU.Connected)return void t();const r=HF([e]);let o;YN.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()}})),QI(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;YN.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==XU.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]===zU.LocalVideoTrack&&!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding){const t=this.localTrackMap.get(zU.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),QI(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),QI(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),QI(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),QI(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),QI(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new SB(this.store),this.bindStatsUploaderEvents(),this.mutex=new IO("P2PChannel-mutex",this.store.clientId),this.isPlanB=!nD().supportUnifiedPlan||_N("CHROME_FORCE_PLAN_B")&&dw(),this.shouldForwardP2PCreation=_N("FORWARD_P2P_CREATION")&&nD().supportPCSetConfiguration&&cw(),this.shouldForwardP2PCreation&&(this.connection=YF(this.store),this.emit(JU.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}async startP2PConnection(e){var t;this.state=XU.New,this._forceTurn=zF(e),YN.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&"closed"===(null===(t=this.connection)||void 0===t?void 0:t.peerConnectionState);if(this.shouldForwardP2PCreation&&!i||(i&&this.connection&&(YN.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=YF(this.store,e),this.emit(JU.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new mw(Ew.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=_N("NEW_ICE_RESTART")?YU.FIRST_CONNECTION:YU.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e){if(!this.connection)throw new mw(Ew.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");_N("ENABLE_PREALLOC_PC")&&this.state===XU.Connected?await this.connection.updateRemoteConnect(e):(this.store.peerConnectionStart(),await this.connection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=XU.Connected)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[i]=e;return Dn(t=[zU.LocalVideoLowTrack,zU.LocalVideoTrack]).call(t,i)})),i=t.map((e=>{let[,{id:t}]=e;return t})),n=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof ZF){if(eD.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Dn(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Dn(e).call(e,t)));t&&(this.store.codec=t,YN.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){var e;if(this.connection instanceof ZF&&"closed"!==this.connection.peerConnectionState&&Dn(e=[XU.New,XU.Connected]).call(e,this.state))return this.connection.establishPromise}async publishDataChannel(e){if(!this.connection||this.state!==XU.Connected){if(this.state===XU.Disconnected)throw new mw(Ew.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Dn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,i){var n=this;return FA((function*(){const r=yield BA(n.mutex.lock("From P2PChannel.publish"));try{var o;const s=n.connection&&Dn(o=["disconnected","failed"]).call(o,n.connection.peerConnectionState);if(!n.connection||n.state!==XU.Connected||s){if(n.state===XU.Disconnected)throw new mw(Ew.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,TF.markPublishStart(n.store.clientId,n.store.pubId);const a=n.filterTobePublishedTracks(e,t,i);if(0===a.length)return void(yield BA(n.tryToUnmuteAudio(e)));yield*jA(NB(n.doPublish(n.connection,a)))}finally{r()}}))()}doPublish(e,t){var i=this;return FA((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===zU.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),r=yield BA(e.send(n,i.store.codec,i.store.audioCodec)),o=(yield BA(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)===Ew.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(s,a,n),d=(yield BA(r.next(c))).value;if(i.state===XU.Disconnected)throw new mw(Ew.UNEXPECTED_ERROR,"PeerConnection already disconnected.");_N("ENABLE_VIDEO_SEI");const l=_N("ENABLE_ENCODED_TRANSFORM"),u=_N("ENABLE_AUDIO_METADATA");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const{interceptLocalVideoFrame:i,interceptLocalAudioFrame:n}=yV();e.trackMediaType===HU.VIDEO?await i(t.sender,e):e.trackMediaType===HU.AUDIO&&await n(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===zU.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 pk))return YN.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=Vx(e,t)),i.maxFramerate=e.framerate?Lx(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==zU.LocalVideoLowTrack||!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return YN.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Lx(t.width)),t.height&&(i.height=Lx(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=iP((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),Lx(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}),YN.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return FA((function*(){if(!t.connection||t.state!==XU.Connected)return;const i=yield BA(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(zU.LocalVideoTrack);if(!r)throw new mw(Ew.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(zU.LocalVideoLowTrack))throw new mw(Ew.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:zU.LocalVideoLowTrack}];if(yield*jA(NB(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(zU.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield BA(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(YN.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Yw(this,JU.RequestRePublish,this.pendingLocalTracks),this.emit(JU.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(YN.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await Yw(this,JU.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==HU.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==HU.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await Yw(this,JU.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===HU.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(JU.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==XU.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!==XU.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!==XU.Connected)return;const e=this.localTrackMap.get(zU.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[zU.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==XU.Connected)throw new mw(Ew.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var o;if(!this.connection||this.state!==XU.Connected)throw new mw(Ew.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c;const d=this.connection.getPreMedia(i);if(d)YN.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=d.transceiver,s=d.track,a=d.id;else if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new mw(Ew.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 ZF&&(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 ZF&&(c=r.transceiver),s=r.track,a=r.id}if(t===HU.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Nk(s,e.uid,e._uintid,this.store),YN.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new Ok(s,e.uid,e._uintid,this.store),YN.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)),c&&_N("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:i,interceptRemoteAudioFrame:n}=yV();t==HU.VIDEO?await i(c.receiver,{onSei:_N("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)})}):t==HU.AUDIO&&await n(c.receiver,{enableTopn:!!_N("ENABLE_AUDIO_TOPN"),enableMetadata:!!_N("ENABLE_AUDIO_METADATA"),onMetadata:e=>{this.safeEmit(JU.AudioMetadata,e)}})}const l=this.remoteUserMap.get(e);l?l.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==u&&(this.pendingRemoteTracks.splice(u,1),this.emit(JU.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==XU.Connected)throw new mw(Ew.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=[],i=new Map;e.forEach((e=>{if(!this.connection)return;const n=this.connection.getPreMedia(e.ssrcId);n?i.set(e.ssrcId,n):t.push(e)}));const n=await this.connection.batchReceive(t.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{i.set(e.ssrcId,n[t])}));for(const{user:t,mediaType:n,ssrcId:r}of e){const e=i.get(r);if(!e)return void YN.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(t.uid," subscribe data,").concat(n,", ").concat(r));const{track:o,id:s,transceiver:a}=e;if(a&&_N("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=yV();n==HU.VIDEO?await e(a.receiver,{onSei:_N("ENABLE_VIDEO_SEI")&&(e=>{var i;return null===(i=t._videoTrack)||void 0===i?void 0:i._onSei(e)})}):n==HU.AUDIO&&await i(a.receiver,{enableTopn:!!_N("ENABLE_AUDIO_TOPN"),enableMetadata:!!_N("ENABLE_AUDIO_METADATA"),onMetadata:e=>{this.safeEmit(JU.AudioMetadata,e)}})}if(n===HU.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(o):(t._audioTrack=new Nk(o,t.uid,t._uintid,this.store),YN.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),a&&t._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(o):(t._videoTrack=new Ok(o,t.uid,t._uintid,this.store),YN.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),a&&t._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._videoTrack)),_N("ENABLE_VIDEO_SEI")&&a){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=yV();n==HU.VIDEO?await e(a.receiver,{onSei:e=>{var i;null===(i=t._videoTrack)||void 0===i||i._onSei(e)}}):n==HU.AUDIO&&await i(a.receiver)}const c=this.remoteUserMap.get(t);c?c.set(n,s):this.remoteUserMap.set(t,new Map([[n,s]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex((e=>{let{user:i,kind:r}=e;return i.uid===t.uid&&n===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(JU.MediaReconnectEnd,t.uid))}}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===XU.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===HU.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===HU.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==XU.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===HU.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===HU.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===HU.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==XU.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===HU.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===HU.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=Xn(e).call(e,((e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,r;i===HU.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===HU.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===HU.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),n}isPreSubScribe(e){if(!this.connection||this.state!==XU.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 YN.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void YN.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===HU.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 YN.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||YN.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(zU.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(zU.LocalAudioTrack);if((null==t?void 0:t.track)instanceof bL){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==zU.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===zU.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===zU.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(zU.LocalAudioTrack),o=n?this.localTrackMap.get(zU.LocalVideoLowTrack):this.localTrackMap.get(zU.LocalVideoTrack);eD.publish(this.store.sessionId,{eventElapse:TF.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(vD.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 IL)),a=n?null===(o=this.localTrackMap.get(zU.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof pk));eD.publish(this.store.sessionId,{eventElapse:TF.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(vD.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===HU.VIDEO?i._videoSSRC:i._audioSSRC;r&&eD.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===HU.VIDEO,audio:n===HU.AUDIO,peerid:i.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:TF.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){YN.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new IO("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=YF(this.store),this.emit(JU.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(zU.LocalAudioTrack);if((null==e?void 0:e.track)instanceof bL){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=XU.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(zU.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(zU.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 pk||t&&t.track instanceof IL?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(MN(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(zU.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=vS(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(YN.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=XU.Reconnecting,_N("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=YF(this.store),this.emit(JU.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case zU.LocalVideoTrack:Dn(t=n._hints).call(t,vD.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case zU.LocalAudioTrack:n instanceof bL?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case zU.LocalVideoLowTrack:}})),this.emit(JU.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(MN(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(JU.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(MN(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),YN.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof IF?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof IF?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 FA((function*(){if(!t.connection||t.state!==XU.Connected)return;const i=yield BA(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield BA(t.connection.restartICE(e));const r=yield BA(n.next());if(r.done)return;const o=r.value,s=yield o;switch(qF(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case KU.UDP_TCP_RELAY:t._pcStatsUploadType=YU.UDP_TCP_RESTART;break;case KU.TCP_RELAY:t._pcStatsUploadType=YU.TCP_RESTART;break;case KU.RELAY:t._pcStatsUploadType=YU.RELAY_RESTART;break;default:t._pcStatsUploadType=YU.OLD_RESTART}t._isTryConnecting=!0,n.next(s)}catch(e){var r;null===(r=n)||void 0===r||r.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(zU.LocalVideoTrack),i=this.localTrackMap.get(zU.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=zw(this,JU.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(vD.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return fM[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=zw(this,JU.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Wh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(YN.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==XU.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===zU.LocalVideoTrack&&!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding){const t=this.localTrackMap.get(zU.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=Zw(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(zU.LocalAudioTrack);for(const r of e){if(r instanceof pk&&(this.localTrackMap.has(zU.LocalVideoTrack)||s?new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:zU.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:zU.LocalVideoLowTrack})}if(r instanceof IL)if(a){const e=a.track;if(e instanceof bL)WF([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=HF([e,r]);YN.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 bL)WF([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&nD().webAudioMediaStreamDest&&!r._bypassWebAudio){o=HF(o?[r,o]:[r])}else o=r}return o&&(YN.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),n.push({track:o,type:zU.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=Zw(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof IL){const e=this.localTrackMap.get(zU.LocalAudioTrack);if(!e)continue;e.track instanceof bL?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([zU.LocalAudioTrack,e]),e.track.close())):t.push([zU.LocalAudioTrack,e])}if(i instanceof pk){const e=this.localTrackMap.get(zU.LocalVideoTrack);if(!e)continue;t.push([zU.LocalVideoTrack,e]);const i=this.localTrackMap.get(zU.LocalVideoLowTrack);i&&t.push([zU.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=Zw(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=Zw(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case zU.LocalVideoTrack:t.addListener(RD.GET_STATS,this.handleGetLocalVideoStats),t.addListener(RD.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(RD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(RD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case zU.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case zU.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof bL?e.trackList.forEach((e=>{e.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(RD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(RD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(RD.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case zU.LocalVideoTrack:t.off(RD.GET_STATS,this.handleGetLocalVideoStats),t.off(RD.GET_RTC_STATS,this.handleGetRTCStats),t.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(RD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(RD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case zU.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case zU.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof bL?e.trackList.forEach((e=>{e.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(RD.GET_STATS,this.handleGetLocalAudioStats),e.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(RD.GET_STATS,this.handleGetLocalAudioStats),e.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(RD.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Ok&&t.addListener(RD.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Nk&&t.addListener(RD.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(RD.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(HU.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(HU.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,o,{track:s,type:a}=e;switch(a){case zU.LocalAudioTrack:r=PU.Audio,o={dtx:s instanceof yL&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case zU.LocalVideoTrack:r=Dn(n=s._hints).call(n,vD.SCREEN_TRACK)?PU.Screen:PU.High,o=OB(OB({},kx(s)),{},{codec:this.store.codec,svc_mode:Bx()});break;case zU.LocalVideoLowTrack:r=PU.Low,o=OB(OB({},kx(s)),{},{codec:this.store.codec,svc_mode:Bx()})}return{stream_type:r,attributes:o,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(JU.PeerConnectionStateChange,t),"connecting"===t&&e instanceof ZF&&!Kb()&&_N("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),_N("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 ZF&&yB(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=YU.DISCONNECTED_OR_FAILED;if("CONNECTED"===zw(this,JU.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));eD.reportApiInvoke(this.store.sessionId,{name:kw.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:Mw.TRACER}).onSuccess(),this.republish()}}if(_N("NEW_ICE_RESTART")&&e instanceof ZF&&!Kb()&&!this._forceTurn){if(Dn(qU).call(qU,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(qF(e)){YN.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===zw(this,JU.QueryClientConnectionState)&&this.emit(JU.RequestRestartICE,t)}},i=()=>{qF(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),YN.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(JU.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{AB(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&_N("ICE_RESTART")){"CONNECTED"===zw(this,JU.QueryClientConnectionState)&&this.emit(JU.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(YN.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(JU.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(YN.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(JU.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eD.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Mw.TRACER}).onSuccess(),this.emit(JU.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(MN(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(wD.FIRST_FRAME_DECODED),eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_AUDIO_DECODE,QN.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(MN(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_AUDIO_RECEIVED,QN.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(MN(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_VIDEO_RECEIVED,QN.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(JU.ConnectionTypeChange,i),YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Fx(t))," -> ").concat(JSON.stringify(Fx(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Fx(t))," -> ").concat(JSON.stringify(Fx(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return OB(OB({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}resetConnection(e){e instanceof ZF&&function(e){vB.delete(e.id),yB(e)}(e),e.close(),this.emit(JU.PeerConnectionStateChange,"closed"),function(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(zU.LocalAudioTrack);if(e instanceof IL&&(null==i?void 0:i.track)instanceof bL)return i.track.isActive||t.push([zU.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===zU.LocalVideoTrack)){const e=this.localTrackMap.get(zU.LocalVideoLowTrack);e&&t.push([zU.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(zU.LocalAudioTrack);if(e instanceof IL&&(null==i?void 0:i.track)instanceof bL)return i.track.isActive&&t.push([zU.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===zU.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(zU.LocalVideoLowTrack);e&&t.push([zU.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case HU.VIDEO:return void(i._videoSSRC&&t.push({stream_type:HU.VIDEO,ssrcId:i._videoSSRC}));case HU.AUDIO:return void(i._audioSSRC&&t.push({stream_type:HU.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===HU.VIDEO?e|=MU.Video:e|=MU.Audio,t.set(i,e)}else n===HU.VIDEO?t.set(i,MU.Video):t.set(i,MU.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(zU.LocalVideoTrack),i=this.localTrackMap.get(zU.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var r;let{stream_type:o}=e;const s=null===(r=t.find((e=>{let{stream_type:t}=e;return o===t})))||void 0===r?void 0:r.attributes;if(s&&_N("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(Dn(e).call(e,vD.SCREEN_TRACK)||Dn(e).call(e,vD.SCREEN_LOW_TRACK))&&(s.remb=!1,YN.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let i=0;i{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await qw(this,JU.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(JU.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(JU.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 uO(bO(this.dtlsFailedCount,AO)),this.emit(JU.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await Yw(this,JU.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(JU.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(zU.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof pk))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof pk)).length>1)throw new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof IL)).length>1&&(e.some((e=>e instanceof IL&&e._bypassWebAudio))||!nD().webAudioMediaStreamDest))throw new mw(Ew.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 pk&&this.pendingLocalTracks.some((e=>e instanceof pk)))throw new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof IL&&this.pendingLocalTracks.some((e=>e instanceof IL))&&(!nD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof IL&&e._bypassWebAudio))))throw new mw(Ew.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=!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding,r=OB(OB({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=n?e._mediaStreamTrack.clone():eB(e,r);const s=hO(8,"track-low-"),a=new pk(o,OB(OB({},n&&{scaleResolutionDownBy:Vx(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(AD.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,CD.LOW_STREAM)})),a._hints.push(vD.LOW_STREAM),Dn(i=e._hints).call(i,vD.SCREEN_TRACK)&&a._hints.push(vD.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(RD.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 ZF){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();eD.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:this._iceError||n||"",selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(o=h.candidateType)&&void 0!==o?o:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(s=p.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i,preallocation:this.connection.isPreallocation}),this._iceError=null}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(MN(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));eD.firstRemoteVideoDecode(this.store.sessionId,JN.FIRST_VIDEO_DECODE,QN.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===zU.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,CD.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},rU(bB.prototype,"startP2PConnection",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"startP2PConnection"),bB.prototype),rU(bB.prototype,"connect",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"connect"),bB.prototype),rU(bB.prototype,"updateRemoteRTPCapabilities",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"updateRemoteRTPCapabilities"),bB.prototype),rU(bB.prototype,"publishDataChannel",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"publishDataChannel"),bB.prototype),rU(bB.prototype,"unpublish",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unpublish"),bB.prototype),rU(bB.prototype,"unpublishDataChannel",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unpublishDataChannel"),bB.prototype),rU(bB.prototype,"unpublishLowStream",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unpublishLowStream"),bB.prototype),rU(bB.prototype,"subscribeDataChannel",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"subscribeDataChannel"),bB.prototype),rU(bB.prototype,"subscribe",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"subscribe"),bB.prototype),rU(bB.prototype,"massSubscribe",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"massSubscribe"),bB.prototype),rU(bB.prototype,"unsubscribe",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unsubscribe"),bB.prototype),rU(bB.prototype,"unsubscribeDataChannel",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unsubscribeDataChannel"),bB.prototype),rU(bB.prototype,"massUnsubscribe",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"massUnsubscribe"),bB.prototype),rU(bB.prototype,"muteRemote",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"muteRemote"),bB.prototype),rU(bB.prototype,"unmuteRemote",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"unmuteRemote"),bB.prototype),rU(bB.prototype,"hasRemoteMediaWithLock",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"hasRemoteMediaWithLock"),bB.prototype),rU(bB.prototype,"disconnectForReconnect",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"disconnectForReconnect"),bB.prototype),rU(bB.prototype,"updateBitrateLimit",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"updateBitrateLimit"),bB.prototype),rU(bB.prototype,"remoteMediaSsrcChanged",[LB],Object.getOwnPropertyDescriptor(bB.prototype,"remoteMediaSsrcChanged"),bB.prototype),bB);function LB(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;s0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(t.pop(),jB(i.context,r),a=0):a=Math.min(a,xB),setTimeout((()=>t.length&&BB(e)),a)}function jB(e,t){e.safeEmit(Gw.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function GB(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 jB(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=VB.get(n)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=MB(MB({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),VB.set(n,r);let a=!1;var c;FB.has(n)?a=!(null===(c=FB.get(n))||void 0===c||!c.isSyncing):FB.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||BB(n)}const WB=xb().name;function HB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function KB(e){for(var t=1;t{const e=i.shift();e&&await e(),i.length>0&&n{i.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),n{YN.warn("Your browser does not support preloading, this feature be run in a secure environment")}),"preload_webcrypto_not_supported");if(!i&&null!==i)throw new mw(Ew.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Rw(i,"token",1,2047),Rw(e,"appid",1,2047),fU(t),n&&TU(n);const s=pO();YN.debug("preload channel ".concat(t,", uid is ").concat(n));const a={appId:e,cname:t,token:i||e,uid:"string"!=typeof n?n:null,sid:s,proxyServer:r};let c,d;"string"==typeof n?(a.stringUid=n,[d,c]=await Wh.all([aF(n,{sid:s,appId:e},ij.token),dF(KB(KB({},a),{},{token:i||e,uid:0}),ij.token)]),a.uid=d.uid,c.gatewayInfo.uid=a.uid,c.gatewayInfo.res.uid=a.uid):(o&&(a.stringUid=o),c=await dF(a,ij.token));const l={sid:s,appId:e,cname:t,token:i||e,uid:a.stringUid||n,intUid:a.uid||c.gatewayInfo.uid,stringUid:a.stringUid,ts:Date.now(),sua:d,ap:c};await async function(e){let t;try{e.uid&&oj({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=uj(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",sO(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,rO(window.btoa(JSON.stringify(e))));return oO(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=dj(YB);const r=t?JSON.parse(t):[];r.push({[i]:n}),r.length>_N("AP_CACHE_NUM")&&r.shift(),lj(YB,JSON.stringify(r))}catch(e){YN.warn("Error caching server parameters:",e.message),lj(YB,"")}}(l),ZB++}catch(e){throw $B++,function(e){QB||(QB=window.setTimeout((()=>{let t="";ej.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),eD.reportApiInvoke(null,{name:kw.PRELOAD,options:{success:ZB,failed:$B,err:t}}).onError(e),ZB=0,$B=0,ej.clear(),QB=null}),zB));const t=ej.get(e.code)||0;ej.set(e.code,t+1)}(e),e}}async function rj(e){try{if(_N("AP_REQUEST_DETAIL")||_N("ENABLE_ROLE_SELECT_EDGE"))return;const t=oj(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",sO(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,rO(e));return JSON.parse(window.atob(oO(new Uint8Array(n))))}catch(e){return}}(t,e.token||e.appId);if(!i)return;if(!function(e,t){const i=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!i)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(i,e))return;if(i&&Date.now()-i.ts<_N("AP_CACHE_LIFETIME"))return i}catch(e){YN.warn("Error get preloadInfo",e.message)}}function oj(e){let t;try{if(t=dj(YB),!t)return;const i=JSON.parse(t),n=uj(e),r=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1}(i,(e=>n in e));if(-1===r)return;const o=i.splice(r,1)[0];return lj(YB,JSON.stringify(i)),o[n]}catch(e){YN.warn("Error delete preload info: ".concat(t),e.message),lj(YB,"")}}function sj(e){if(e){let t=XB.get(e);t&&(window.clearTimeout(t),t=null,XB.delete(e)),Dn(JB).call(JB,e)||"disabled"!==e.cloudProxyServer||JB.push(e)}if(XB.size<_N("AP_CACHE_NUM")&&JB.length>0){const e=JB.shift();XB.set(e,window.setTimeout((async()=>{const{appId:t,cname:i,token:n,stringUid:r,uid:o,proxyServer:s}=e;try{await tj(t,i,n,o,s,r),XB.has(e)&&sj(e)}catch(t){YN.warn("update preload failed",t.message),aj(e)}}),_N("AP_UPDATE_INTERVAL")))}}function aj(e){const t=JB.indexOf(e);-1!==t&&JB.splice(t,1);let i=XB.get(e);i&&(window.clearTimeout(i),i=null,XB.delete(e),sj())}function cj(e,t){const i=e.sua,n=e.ap;t&&i&&eD.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),eD.reportResourceTiming(e.ap.url,e.sid),eD.joinWebProxyAP(e.sid,{lts:n.requestTime,elapse:n.elapse,sucess:1,apServerAddr:n.url,turnServerAddrList:n.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[wx.CHOOSE_SERVER,wx.CLOUD_PROXY_FALLBACK].toString()}),eD.joinChooseServer(e.sid,{lts:n.requestTime,elapse:n.elapse,succ:!0,csAddr:n.url,opid:n.opid,serverList:n.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:n.gatewayInfo.cid.toString(),uid:n.gatewayInfo.uid.toString(),csIp:n.gatewayInfo.csIp,unilbsServerIds:[wx.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function dj(e){return window.atob(window.localStorage.getItem(e)||"")}function lj(e,t){window.localStorage.setItem(e,window.btoa(t))}function uj(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),RO(t)}function hj(e){let t=function(){const e=mj.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let i=e.appId;void 0!==i&&(bj(t,10),Cj(t,i));let n=e.cid;void 0!==n&&(bj(t,16),bj(t,n));let r=e.cname;void 0!==r&&(bj(t,26),Cj(t,r));let o=e.deviceId;void 0!==o&&(bj(t,34),Cj(t,o));let s=e.elapse;void 0!==s&&(bj(t,40),Oj(t,s));let a=e.fileSize;void 0!==a&&(bj(t,48),Oj(t,Ej(a)));let c=e.height;void 0!==c&&(bj(t,56),Oj(t,Ej(c)));let d=e.jpg;void 0!==d&&(bj(t,66),bj(t,d.length),Rj(t,d));let l=e.networkType;void 0!==l&&(bj(t,72),Oj(t,Ej(l)));let u=e.osType;void 0!==u&&(bj(t,80),Oj(t,Ej(u)));let h=e.requestId;void 0!==h&&(bj(t,90),Cj(t,h));let p=e.sdkVersion;void 0!==p&&(bj(t,98),Cj(t,p));let _=e.sequence;void 0!==_&&(bj(t,104),Oj(t,Ej(_)));let E=e.sid;void 0!==E&&(bj(t,114),Cj(t,E));let m=e.timestamp;void 0!==m&&(bj(t,120),Oj(t,m));let f=e.uid;void 0!==f&&(bj(t,128),bj(t,f));let T=e.vid;void 0!==T&&(bj(t,136),bj(t,T));let S=e.width;void 0!==S&&(bj(t,144),Oj(t,Ej(S)));let g=e.service;void 0!==g&&(bj(t,152),bj(t,g));let R=e.callbackData;void 0!==R&&(bj(t,162),bj(t,R.length),Rj(t,R));let v=e.ticket;void 0!==v&&(bj(t,170),Cj(t,v));let C=e.vendorConfigs;void 0!==C&&(bj(t,178),Cj(t,C))}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function pj(e){return function(e){let t={};e:for(;!Tj(e);){let i=Aj(e);switch(i>>>3){case 0:break e;case 1:t.code=Aj(e);break;case 2:t.msg=vj(e,Aj(e));break;case 3:t.requestId=vj(e,Aj(e));break;case 4:t.timestamp=wj(e,!1);break;default:_j(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function _j(e,t){switch(t){case 0:for(;128&Ij(e););break;case 2:fj(e,Aj(e));break;case 5:fj(e,4);break;case 1:fj(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Ej(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let mj=[];function fj(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Tj(e){return e.offset>=e.limit}function Sj(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function gj(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function Rj(e,t){let i=Sj(e,t.length);e.bytes.set(t,i)}function vj(e,t){let i=gj(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function Cj(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function Ij(e){return e.bytes[gj(e,1)]}function yj(e,t){let i=Sj(e,1);e.bytes[i]=t}function Aj(e){let t,i=0,n=0;do{t=Ij(e),i<32&&(n|=(127&t)<>>=0;t>=128;)yj(e,127&t|128),t>>>=7;yj(e,t)}function wj(e,t){let i,n=0,r=0,o=0;return i=Ij(e),n=127&i,128&i&&(i=Ij(e),n|=(127&i)<<7,128&i&&(i=Ij(e),n|=(127&i)<<14,128&i&&(i=Ij(e),n|=(127&i)<<21,128&i&&(i=Ij(e),r=127&i,128&i&&(i=Ij(e),r|=(127&i)<<7,128&i&&(i=Ij(e),r|=(127&i)<<14,128&i&&(i=Ij(e),r|=(127&i)<<21,128&i&&(i=Ij(e),o=127&i,128&i&&(i=Ij(e),o|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|o<<24,unsigned:t}}function Oj(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=Sj(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}const Nj={},Dj={},Pj=4294967296,Lj=Pj*Pj,kj=Lj/2,Mj=Bj(0,!0),Uj=Bj(0),xj=jj(0,-2147483648,!1),Vj=jj(-1,2147483647,!1),Fj=jj(-1,-1,!0);function Bj(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=Dj[e],n)?n:(i=jj(e,0,!0),r&&(Dj[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=Nj[e],n)?n:(i=jj(e,e<0?-1:0,!1),r&&(Nj[e]=i),i)}function jj(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function Gj(e,t){if(isNaN(e))return t?Mj:Uj;if(t){if(e<0)return Mj;if(e>=Lj)return Fj}else{if(e<=-kj)return xj;if(e+1>=kj)return Vj}return e<0?t?Mj:Uj:jj(e%Pj|0,e/Pj|0,t)}function Wj(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 Hj extends Dw{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(nx.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),QI(this,"name","AgoraRTCImageModeration"),QI(this,"_connectionState",ix.CONNECTING),QI(this,"_sequence",0),QI(this,"_moderationStartTime",void 0),QI(this,"_workerConnection",void 0),QI(this,"_workerMessageLengthLimit",void 0),QI(this,"_qualityRatio",void 0),QI(this,"_connectInfo",void 0),QI(this,"_cancelTokenSource",Ab.CancelToken.source()),QI(this,"_retryConfig",void 0),QI(this,"_moderationInterval",void 0),QI(this,"_moderationTimer",null),QI(this,"_moderationMode",1),QI(this,"_quality",1),QI(this,"_qualityTimer",null),QI(this,"_ticket",void 0),QI(this,"_moderationIntervalMinimum",void 0),QI(this,"_uploadFailedNum",0),QI(this,"_uploadNum",0),QI(this,"_uploadTimer",null),QI(this,"_extraInfo",void 0),QI(this,"_vendor",""),QI(this,"_encoder",new TextEncoder),QI(this,"_moderationId",void 0),QI(this,"inspectImage",(()=>{if(this.connectionState!==ix.CONNECTED)throw new tD(Ew.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===ix.CONNECTED?this.requestToInspectImage():YN.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval{YN.debug("[".concat(this._moderationId,"] Moderation operation :").concat(rx[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(nx.STATE_CHANGE,rx.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((n,r)=>{this.on(nx.CONNECTION_STATE_CHANGE,((e,t)=>{e===ix.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),YN.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===ix.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=_N("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;eF++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:eF,seq:eF,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return wO((async()=>{h=Date.now();const e=await PV(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new tD(Ew.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw YN.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new tD(Ew.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw YN.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new tD(Ew.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw YN.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new tD(Ew.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw YN.error(e.toString()),e}const n=_N("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(eD.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(eD.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Ew.OPERATION_ABORTED&&t.code!==Ew.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(nx.STATE_CHANGE,rx.AP_CONNECTED);const{addressList:o,ticket:s}=r;return this._ticket=s,o}async connectWorker(e){this.emit(nx.STATE_CHANGE,rx.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(mU.CONNECTED,(async()=>{this.emit(nx.STATE_CHANGE,rx.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=ix.CONNECTED})),this._workerConnection.on(mU.CLOSED,(()=>{this.connectionState=ix.CLOSED})),this._workerConnection.on(mU.FAILED,(()=>{this.connectionState=ix.CLOSED})),this._workerConnection.on(mU.RECONNECTING,(()=>{this.connectionState=this.connectionState===ix.CONNECTED?ix.RECONNECTING:ix.CONNECTING})),this._workerConnection.on(mU.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=pj(new Uint8Array(e.data));_N("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&YN.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,YN.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{eD.reportApiInvoke(this._connectInfo.sid||null,{name:kw.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:Mw.TRACER}).onError(new tD(Ew.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),_N("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else YN.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(mU.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this._workerConnection.on(mU.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=zw(this,nx.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(_N("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&YN.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else _N("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&YN.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await MP(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+hO(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:Hj.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.23.2",sequence:this._sequence,sid:s,timestamp:Gj(c),uid:a,vid:o,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=hj(h);if(p.byteLength1024)throw new tD(Ew.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new tD(Ew.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Yj={name:"ImageModeration",create:function(e){let{config:t}=e;return Kj(t),new Hj(t)}};var qj,zj,Xj,Jj,Qj,Zj,$j,eG,tG,iG,nG,rG,oG,sG,aG,cG,dG,lG,uG,hG,pG,_G,EG,mG,fG,TG,SG,gG,RG,vG,CG,IG,yG,AG,bG,wG,OG,NG,DG,PG,LG,kG;function MG(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 UG(e){for(var t=1;t{if(!Array.isArray(t)){if(!(t instanceof XD))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),Xj=$N({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==OD.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),Jj=$N({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),Qj=$N({argsMap:(e,t,i)=>[t,i]}),Zj=$N({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),$j=$N({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),eG=$N({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),tG=$N(),iG=$N(),nG=$N(),rG=$N(),oG=$N(),sG=$N(),aG=$N(),cG=$N(),dG=$N(),lG=$N(),uG=$N(),hG=$N(),pG=$N(),_G=$N(),EG=$N(),mG=$N({argsMap:(e,t)=>[t]}),fG=$N(),TG=$N(),SG=$N(),gG=$N(),RG=$N(),vG=$N(),CG=$N(),IG=$N(),yG=$N({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),AG=$N(),bG=$N(),wG=$N(),OG=$N(),NG=$N(),DG=$N(),PG=$N({reportResult:!0}),LG=$N(),kG=class extends Dw{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){let i;if(super(),QI(this,"store",void 0),QI(this,"_uid",void 0),QI(this,"_channelName",void 0),QI(this,"_uintUid",void 0),QI(this,"_users",[]),QI(this,"_config",void 0),QI(this,"_clientId",void 0),QI(this,"_appId",void 0),QI(this,"_sessionId",null),QI(this,"_key",void 0),QI(this,"_rtmConfig",{}),QI(this,"_joinInfo",void 0),QI(this,"_gateway",void 0),QI(this,"_statsCollector",void 0),QI(this,"_configDistribute",void 0),QI(this,"_leaveMutex",void 0),QI(this,"_publishMutex",void 0),QI(this,"_renewTokenMutex",void 0),QI(this,"_subscribeMutex",void 0),QI(this,"_encryptionMode","none"),QI(this,"_encryptionSecret",null),QI(this,"_encryptionSalt",null),QI(this,"_encryptDataStream",!1),QI(this,"_encryptDataStreamKey",null),QI(this,"_encryptDataStreamIv",null),QI(this,"_proxyServer",void 0),QI(this,"_turnServer",{servers:[],mode:"auto"}),QI(this,"_cloudProxyServerMode","disabled"),QI(this,"_isDualStreamEnabled",!1),QI(this,"_defaultStreamFallbackType",void 0),QI(this,"_lowStreamParameter",void 0),QI(this,"_streamFallbackTypeCacheMap",new Map),QI(this,"_remoteStreamTypeCacheMap",new Map),QI(this,"_axiosCancelSource",Ab.CancelToken.source()),QI(this,"_audioVolumeIndicationInterval",void 0),QI(this,"_networkQualityInterval",void 0),QI(this,"_userOfflineTimeout",void 0),QI(this,"_streamRemovedTimeout",void 0),QI(this,"_liveTranscodeStreamingClient",void 0),QI(this,"_liveRawStreamingClient",void 0),QI(this,"_channelMediaRelayClient",void 0),QI(this,"_networkQualitySensitivity","normal"),QI(this,"_p2pChannel",void 0),QI(this,"_useLocalAccessPoint",!1),QI(this,"_setLocalAPVersion",void 0),QI(this,"_joinAndNotLeaveYet",!1),QI(this,"_numberOfJoinCount",0),QI(this,"_remoteDefaultVideoStreamType",void 0),QI(this,"_inspect",void 0),QI(this,"_moderation",void 0),QI(this,"_license",void 0),QI(this,"_pendingPublishedUsers",[]),QI(this,"ntpAlignErrorCount",0),QI(this,"remoteInboundOffset",0),QI(this,"_peerConnectionState",void 0),QI(this,"_handleLocalTrackEnable",((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),QI(this,"_handleLocalTrackDisable",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),QI(this,"_handleUserOnline",(e=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(e.uid,this.channelName))return void YN.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&YN.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(Gw.USER_JOINED,t));else{const t=new IF(e.uid,e.uint_id||e.uid);this._users.push(t),YN.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(Gw.USER_JOINED,t)}})),QI(this,"_handleUserOffline",(e=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(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:Qw(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),YN.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(Gw.USER_LEAVED,t,e.reason))})),QI(this,"_handleAddAudioOrVideoStream",((e,t,i,n,r,o,s)=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(t,this.channelName))return;const a=this._users.find((e=>e.uid===t));if(!a)return void YN.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));YN.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),o&&(a._audioOrtc=o)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==s&&(a._rtxSsrcId=s),o&&(a._videoOrtc=o)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(YN.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.safeEmit(Gw.USER_PUBLISHED,a,e)),"video"===e?eD.onGatewayStream(this._sessionId,JN.ON_ADD_VIDEO_STREAM,QN.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):eD.onGatewayStream(this._sessionId,JN.ON_ADD_AUDIO_STREAM,QN.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then((t=>{if(t&&(YN.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof PB))return this._p2pChannel.unsubscribe(a,e,!0).then((()=>this._subscribe(a,e,!0).catch((e=>{YN.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(YN.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch((e=>{YN.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),QI(this,"_handleRemoveStream",(e=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void YN.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));YN.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{YN.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(Gw.USER_UNPUBLISHED,t,"audio"),YN.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(Gw.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{YN.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(Gw.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{YN.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(Gw.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 PB&&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),eD.onGatewayStream(this._sessionId,JN.ON_REMOVE_STREAM,QN.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()})),QI(this,"_handleSetStreamLocalEnable",((e,t,i)=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void YN.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));YN.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";YN.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(Gw.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";YN.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(Gw.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(YN.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(Gw.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),YN.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(Gw.USER_UNPUBLISHED,n,e)):void 0})),QI(this,"_handleMuteStream",((e,t,i)=>{if(_N("BLOCK_LOCAL_CLIENT")&&gM(e,this.channelName))return;YN.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void YN.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";YN.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(Gw.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";YN.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(Gw.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)?(YN.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(Gw.USER_PUBLISHED,n,t)):void YN.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),YN.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(Gw.USER_UNPUBLISHED,n,t)}})),QI(this,"_handleP2PLost",(async e=>{YN.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():YN.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),QI(this,"_handleTokenWillExpire",(()=>{YN.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(Gw.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),QI(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),YN.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),QI(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(Gw.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(Gw.NETWORK_QUALITY,e)})),QI(this,"_handleP2PAddAudioOrVideoStream",((e,t,i,n)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void YN.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));YN.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&&(YN.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(Gw.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(YN.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{YN.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||hO(5,"client-"),this.store=new class{constructor(e,t,i,n){_w(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:sN.Default,hasStartJoinChannel:!1,isABTestSuccess:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case fN.SET_SESSION_ID:return pw(pw({},e),{},{sessionId:t.sessionId});case fN.SET_P2P_ID:return pw(pw({},e),{},{p2pId:t.p2pId});case fN.SET_UID:return pw(pw({},e),{},{uid:t.uid});case fN.SET_INT_UID:return pw(pw({},e),{},{intUid:t.intUid});case fN.SET_PUB_ID:return pw(pw({},e),{},{pubId:t.pubId});case fN.KEY_METRIC_CLIENT_CREATED:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{clientCreated:t.metric})});case fN.KEY_METRIC_JOIN_START:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{joinStart:t.metric})});case fN.AVOID_JOIN_START:return pw(pw({},e),{},{avoidJoinStart:t.avoidJoinStart});case fN.KEY_METRIC_JOIN_END:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{joinEnd:t.metric})});case fN.KEY_METRIC_REQUEST_AP_START:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{requestAPStart:t.metric})});case fN.KEY_METRIC_REQUEST_AP_END:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{requestAPEnd:t.metric})});case fN.KEY_METRIC_JOIN_GATEWAY_START:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case fN.KEY_METRIC_JOIN_GATEWAY_END:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case fN.KEY_METRIC_PEER_CONNECTION_START:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case fN.KEY_METRIC_PEER_CONNECTION_END:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case fN.KEY_METRIC_DESCRIPTION_START:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{descriptionStart:t.metric})});case fN.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case fN.KEY_METRIC_ICE_CONNECTION_END:return pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case fN.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=pw(pw({},i[n]),t.metric),pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{publish:[...i]})})):pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case fN.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]=pw(pw({},i[n]),t.metric),pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{subscribe:[...i]})})):pw(pw({},e),{},{keyMetrics:pw(pw({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case fN.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case fN.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=pw(pw({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case fN.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case fN.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case fN.SET_USE_P2P:return pw(pw({},e),{},{useP2P:t.val});case fN.SET_TRANSPORT_TYPE:return pw(pw({},e),{},{p2pTransport:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:fN.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}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:fN.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:fN.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:fN.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:fN.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:fN.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:fN.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:fN.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:fN.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(e){this.state.hasStartJoinChannel=e}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:fN.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:fN.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:fN.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:fN.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:fN.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:fN.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:fN.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:fN.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:fN.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:fN.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:fN.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:fN.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:fN.KEY_METRIC_PUBLISH,metric:pw(pw({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:fN.KEY_METRIC_SUBSCRIBE,metric:pw(pw(pw(pw(pw({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:fN.KEY_METRIC_SUBSCRIBE,metric:pw(pw(pw({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:fN.RECORD_JOIN_CHANNEL_SERVICE,record:pw(pw({},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:fN.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:fN.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:fN.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:fN.AVOID_JOIN_START,avoidJoinStart:e})}}(e.codec,e.audioCodec,e.mode,this._clientId),this._leaveMutex=new IO("client-leave",this._clientId),this._publishMutex=new IO("client-publish",this._clientId),this._renewTokenMutex=new IO("client-renewtoken",this._clientId),this._subscribeMutex=new IO("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),YN.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(rN," build: ").concat(lN,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{jw(e.clientRoleOptions),i=Object.assign({},e.clientRoleOptions)}catch(e){YN.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var n;this._statsCollector=new RF(this.store),this._statsCollector.onStatsException=(e,t,i)=>{YN.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(Gw.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));r&&eD.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useP2P="p2p"===e.mode,this._gateway=new OV(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||AO,httpRetryConfig:e.httpRetryConfig||AO,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:i}),this._configDistribute=new EF(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(n={store:this.store,statsCollector:this._statsCollector},CV("P2PChannel").create(n)),this._handleP2PEvents()):this._p2pChannel=new PB(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];pN("JOIN_GATEWAY_USE_443PORT_ONLY",o),pN("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof Ix&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,i){Ob.get(e)||Ob.set(e,[]),Nb.get(e)||Nb.set(e,t),Db.get(e)||Db.set(e,0);const n=Ob.get(e),r=Nb.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(Db.get(e)===r){const e=wb();n.push(e),await e.promise}Db.set(e,Db.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a0&&(n[0].resolve(),n.shift()),0===Db.get(e)&&(Ob.set(e,[]),Nb.set(e,0),Db.set(e,0)),c}("client.join",_N("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r)}async join(e,t,i,n,r){const o=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const s="HTTPS"===(OO||OO||(OO=(window.location.protocol.split(":")[0]||"").toUpperCase(),OO)),a=MO()?window.isSecureContext:"Browser Not Support";if(!MO()&&!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";YN.warning(e)}"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),YN.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart))),eD.setAppId(e);try{if(!i&&null!==i)throw new tD(Ew.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Rw(i,"token",1,2047),Rw(e,"appid",1,2047),fU(t),n&&TU(n),r&&Rw(r,"optionalInfo",1,2047)}catch(r){throw eD.reportApiInvoke(pO(),{name:kw.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Mw.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){YN.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),YN.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw eD.reportApiInvoke(pO(),{name:kw.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Mw.TRACER}).onError(r),r}this._gateway.state="CONNECTING";const c=await rj({appId:e,cname:t,uid:n,stringUid:"string"==typeof n?n:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(!this._joinAndNotLeaveYet)throw new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const d=(null==c?void 0:c.sid)||pO();YN.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=d,this.store.sessionId=this._sessionId);const l=eD.reportApiInvoke(d,{id:this._clientId,name:kw.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Mw.TRACER}),u=UG(UG(UG({},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:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!c},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:_N("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(u.stringUid=n,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=await(async e=>{const t=function(e){const t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e{"CONNECTING"===this.connectionState&&h===this._sessionId&&eD.joinChannelTimeout(this._sessionId,5)}),5e3);try{var p;let n;const r=u.cloudProxyServer;if(Dn(p=["proxy3","proxy4","proxy5"]).call(p,r)){const e=_N("PROXY_SERVER_TYPE3");Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(eD.setProxyServer(u.proxyServer),YN.setProxyServer(u.proxyServer),this.store.requestAPStart(),c){if(YN.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(u.stringUid?", ".concat(u.stringUid," => ").concat(c.intUid):""," ")),u.stringUid&&!u.uid&&(u.uid=c.intUid),n={gatewayInfo:c.ap.gatewayInfo},_N("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===u.turnServer.mode)if(0===c.ap.proxyInfo.addresses.length)YN.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await xx(c.ap.proxyInfo,c.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||aN.tcpport,udpport:e.udpport||aN.udpport,username:e.username||aN.username,password:e.password||aN.password,forceturn:!1,security:!0})));u.turnServer={mode:"manual",servers:e}}cj(c,u.stringUid)}else{if(u.stringUid&&!u.uid){let e;[e,n]=await Wh.all([sF(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||AO,this.store),oF(u,this._axiosCancelSource.token,this._config.httpRetryConfig||AO,!0,this.store)]),YN.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(e)),u.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await oF(u,this._axiosCancelSource.token,this._config.httpRetryConfig||AO,!0,this.store);if(!this._joinAndNotLeaveYet)throw new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(BU.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(BU.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)}))}),0),this._key=i||e;const o=n.gatewayInfo,s=u.uid?u.uid:o.uid;this._joinInfo=UG(UG({},u),{},{cid:o.cid,uid:s,vid:o.vid,apResponse:o.res,apGatewayAddress:o.apGatewayAddress,uni_lbs_ip:o.uni_lbs_ip,gatewayAddrs:o.gatewayAddrs}),this.store.intUid=s,this.store.cid=o.cid;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));l.onSuccess(a),this._appId=e,this._channelName=u.cname,this._uid=a,this.store.uid=a,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(Wb()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const d=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return YN.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(d)),setTimeout((()=>{YN.startUpload()}),5e3),this.store.joinEnd(),_=this,Dn(TM).call(TM,_)||TM.push(_),"disabled"===this._cloudProxyServerMode&&nD().supportWebCrypto&&_N("ENABLE_PRELOAD")&&sj(this._joinInfo),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Ew.OPERATION_ABORTED?YN.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):YN.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==Ew.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),l.onError(t),t}var _}_joinGateway(){if(!this._joinInfo||!this._key)throw new tD(Ew.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!_N("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}async leave(){YN.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(Wb()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=TM.indexOf(e);-1!==t&&TM.splice(t,1)}(this),this._statsCollector.stopUpdateStats();const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return YN.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState,Vw.LEAVE),YN.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof XD))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new tD(Ew.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new tD(Ew.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof XD))throw new tD(Ew.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new tD(Ew.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}YN.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 pk&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),YN.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw YN.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{n()}}async _publishDataChannel(e){Sw(e.id,"id",0,65535,!0),fw(e.ordered,"ordered"),Rw(e.metadata,"metadata",0,512),YN.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 tD(Ew.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 tD(Ew.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&_N("FORCE_TURN")&&!_N("TURN_ENABLE_TCP")&&!_N("TURN_ENABLE_UDP"))throw new tD(Ew.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return IV(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw YN.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new tD(Ew.CREATE_DATACHANNEL_ERROR);try{await Wh.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==Ew.DISCONNECT_P2P)throw e}}return YN.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw YN.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new tD(Ew.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof XD))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);YN.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(ox.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),YN.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw YN.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()),YN.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),YN.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw YN.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof IF)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new tD(Ew.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(Tw(t,"mediaType",["audio","video"]),this.store.useP2P)throw new tD(Ew.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===HU.AUDIO,n=t===HU.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:o,ortc:s,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==o)throw new tD(Ew.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new IF(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=o,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),n&&(l._videoSSRC=o,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),null!=a&&(l._rtxSsrcId=a)),YN.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(o)),await this._p2pChannel.subscribe(l,t,o,a,s);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new tD(Ew.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(t){throw YN.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var i;if(Sw(t,"channelId",0,65535,!0),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n)throw YN.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw YN.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new tD(Ew.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 YN.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new tD(Ew.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();YN.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Dn(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw YN.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new tD(Ew.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)!==Ew.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return YN.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,i){if(Tw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");throw YN.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 tD(Ew.INVALID_REMOTE_USER,"user is not published");throw YN.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 tD(Ew.REMOTE_USER_IS_NOT_PUBLISHED);throw YN.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();YN.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}YN.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{YN.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new tD(Ew.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw YN.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(Tw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const n=this._users.find((t=>t===e));if(!n){const t=new tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");throw YN.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 tD(Ew.INVALID_REMOTE_USER,"user is not published");throw YN.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 tD(Ew.REMOTE_USER_IS_NOT_PUBLISHED);throw YN.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?HU.AUDIO:HU.VIDEO,ssrcId:r};const c=await this._subscribeMutex.lock();YN.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?HU.AUDIO:HU.VIDEO,ssrcId:r}),TF.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)!==Ew.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}YN.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{YN.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new tD(Ew.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw YN.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(vw(e,"subscribeList"),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();YN.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const r=(e=[...e]).map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}})),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:o,mediaType:s}=n;if(Tw(s,"mediaType",["audio","video"]),!o){const e=new tD(Ew.INVALID_PARAMS,"user property does not exist in subscribeList item");throw YN.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 tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");YN.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 tD(Ew.REMOTE_USER_IS_NOT_PUBLISHED);YN.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=MU.Video|MU.LwoVideo,d=i.get(o);if(d){if("video"===s?d&c:d&MU.Audio){e.splice(t,1),YN.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,d|("video"===s?c:MU.Audio))}else i.set(o,"video"===s?c:MU.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:o}=n,s=MU.Video|MU.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const n=i.get(r);i.set(r,"video"===o?n^s:n^MU.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=Xn(s=Array.from(i.entries())).call(s,((e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&MU.Audio&&(r.audio_ssrc=i._audioSSRC),n&MU.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===HU.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===HU.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:o}=e;(n||r||o)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:o})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let[i,n]=t;const r=this.remoteUsers.find((e=>e.uid===i));if(r){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=HU.VIDEO:n.audio_error_code&&(t=HU.AUDIO),e.push({user:r,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=hx(i);YN.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new tD(Ew.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;eD.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===HU.VIDEO,audio:e.mediaType===HU.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===HU.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)})),YN.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),n()}}async unsubscribe(e,t,i){if(!(e instanceof IF)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new tD(Ew.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&&Tw(t,"mediaType",["audio","video"]),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");throw YN.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}YN.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&&Qw(this._users,e),YN.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===Ew.DISCONNECT_P2P)return void YN.warning("disconnecting p2p, abort unsubscribe request.");throw YN.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&Sw(t,"id",0,65535,!0),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new tD(Ew.INVALID_REMOTE_USER,"user is not in the channel");throw YN.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 tD(Ew.REMOTE_USER_IS_NOT_PUBLISHED);throw YN.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}YN.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),YN.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===Ew.DISCONNECT_P2P)return void YN.warning("disconnecting p2p, abort unsubscribe request.");throw YN.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(vw(e,"unsubscribeList"),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");YN.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new tD(Ew.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw YN.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Tw(r,"mediaType",["video","audio",void 0]);const o=this._users.find((e=>e===n));if(!o){YN.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const s=MU.Video|MU.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&MU.Audio;break;default:a=o&(MU.Audio|s)}if(a){YN.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue}r?"audio"===r?t.set(n,o|MU.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|MU.Audio|s)}else r?"audio"===r?t.set(n,MU.Audio):"video"===r&&t.set(n,s):t.set(n,MU.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),YN.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===Ew.DISCONNECT_P2P)return void YN.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw YN.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new mw(Ew.INVALID_PARAMS);Cw(e.width)||gw(e.width,"streamParameter.width"),Cw(e.height)||gw(e.height,"streamParameter.height"),Cw(e.framerate)||gw(e.framerate,"streamParameter.framerate"),Cw(e.bitrate)||Sw(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&YN.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),YN.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(Rw(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new tD(Ew.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,eD.setProxyServer(this._proxyServer),YN.setProxyServer(this._proxyServer),YN.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 tD(Ew.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new tD(Ew.INVALID_OPERATION,"You have already set the proxy")}if(Fw(e))return this._turnServer={servers:e,mode:"original-manual"},void YN.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>Bw(e))),this._turnServer={servers:e,mode:"manual"},YN.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new tD(Ew.INVALID_OPERATION,"you should set license before join channel")}if(Rw(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new tD(Ew.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,YN.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new tD(Ew.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 tD(Ew.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 tD(Ew.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,YN.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"Stop proxy server after leave channel");eD.setProxyServer(),YN.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",YN.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 tD(Ew.INVALID_PARAMS,"accessPoints is required.");vw(e.accessPoints.serverList,"accessPoints.serverList"),Rw(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{Sw(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 tD(Ew.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");_N("CLOSE_AFB_FOR_LOCAL_AP")&&(pN("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),pN("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,pN("WEBCS_DOMAIN",s),pN("WEBCS_DOMAIN_BACKUP_LIST",s),pN("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(vw(e.report.hostname,"report.hostname"),pN("EVENT_REPORT_DOMAIN",e.report.hostname[0]),pN("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(pN("EVENT_REPORT_DOMAIN",o[0]),pN("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),pN("STATS_COLLECTOR_PORT",a),e.report?pN("ENABLE_EVENT_REPORT",!0):pN("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(vw(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),pN("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(vw(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),pN("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?pN("ENABLE_CONFIG_DISTRIBUTE",!0):pN("ENABLE_CONFIG_DISTRIBUTE",!1),YN.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(vw(e,"serverList"),Rw(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new tD(Ew.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,pN("WEBCS_DOMAIN",e),pN("WEBCS_DOMAIN_BACKUP_LIST",e),pN("GATEWAY_DOMAINS",[t]),pN("EVENT_REPORT_DOMAIN",e[0]),pN("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),pN("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),YN.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Tw(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 YN.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else YN.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Tw(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 YN.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}YN.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Tw(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw YN.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}YN.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){Tw(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),Rw(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Dn(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new tD(Ew.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new tD(Ew.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(fw(n,"encryptDataStream"),!Dn(r).call(r,e))throw new tD(Ew.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||YN.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=oO(i))}async renewToken(e){if(Rw(e,"token",1,2047),!this._key||!this._joinInfo)throw new tD(Ew.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(_N("USE_NEW_TOKEN")){YN.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await hF(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||AO);YN.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else YN.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});YN.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,YN.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?YN.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(Gw.VOLUME_INDICATOR,e)}),_N("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 tD(Ew.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new tD(Ew.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 tD(Ew.LIVE_STREAMING_TASK_CONFLICT);const i=t?SU.TRANSCODE:SU.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(SU.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new tD(Ew.INVALID_PARAMS,"can not find live streaming url to stop");await Wh.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){CF(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){CF(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 PB&&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 tD(Ew.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Dn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=Xn(n=Array.from(i)).call(n,((e,t)=>e+t),0),o={serverTs:0,seq:CN++,length:i.length,checkSum:r},s=new Uint8Array(SO(r,2)),a=new ArrayBuffer(vN),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=aO(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:SN,additionalData:s},t,i);return aO(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new tD(Ew.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(hU.DATA_STREAM,{payload:oO(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-UB},!i)}sendMetadata(e){if(!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new tD(Ew.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(hU.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:oO(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(zN),!this._joinInfo)throw new tD(Ew.INVALID_OPERATION,"can not send custom report, not joined");await eD.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){Tw(t.spatialLayer,"spatialLayer",[0,1,2,3]),Tw(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw YN.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(fw(t,"apRTM"),Sw(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,YN.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(YN.debug("[".concat(this._clientId,"] reset client")),function(e){const t=SM.indexOf(e);-1!==t&&SM.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this._axiosCancelSource.cancel(),this._axiosCancelSource=Ab.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&aj(this._joinInfo),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&eD.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new IO("client-publish",this._clientId),this._subscribeMutex=new IO("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||pO();e?YN.debug("[".concat(this._clientId,"] new Session ").concat(n)):YN.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,eD.addSid(n);const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:1,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1};eD.sessionInit(this._sessionId,UG({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 tD(Ew.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&_N("FORCE_TURN")&&!_N("TURN_ENABLE_TCP")&&!_N("TURN_ENABLE_UDP"))throw new tD(Ew.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");YN.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(ox.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!==Ew.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 pk&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{YN.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)===Ew.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new tD(Ew.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));YN.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate{if(!this._joinInfo||!this._appId){return new tD(Ew.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},CV("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{eD.reportApiInvoke(this._sessionId,{name:kw.ON_LIVE_STREAM_ERROR,options:[e,t],tag:Mw.TRACER}).onSuccess(),this.safeEmit(Gw.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{eD.reportApiInvoke(this._sessionId,{name:kw.ON_LIVE_STREAM_WARNING,options:[e,t],tag:Mw.TRACER}).onSuccess(),this.safeEmit(Gw.LIVE_STREAMING_WARNING,e,t)},e.on(yU.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new tD(Ew.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const r=_N("UAP_AP").slice(0,_N("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 KV(r,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,AO).then(t).catch(i)})),e};return e===SU.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new tD(Ew.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const{sendResolutionWidth:t,sendResolutionHeight:i}=this.getLocalVideoStats(),n=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:i}},CV("ChannelMediaRelay").create(e));n.on("state",(e=>{e===NU.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(Gw.CHANNEL_MEDIA_RELAY_STATE,e)})),n.on("event",(e=>{this.safeEmit(Gw.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=n,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];if(t){const e=[];this._users.forEach((t=>{t._dataChannels.forEach((n=>{i.every((e=>e.uid!==t._uintid||e.stream_id!==n.id))&&e.push({uid:t._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})}))})),e.length>0&&this._handleUpdateDataChannel({added:[],deleted:e})}Array.isArray(i)&&i.length>0&&i.forEach((e=>{const{uid:i,stream_id:n,ordered:o,max_retrans_times:s,metadata:a}=e,c=this._users.find((e=>e._uintid===i));if(!c)return void YN.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));YN.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Dn(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i);if(!(-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id)))){const e={id:n,ordered:!!o,maxRetransmits:s,metadata:a},i=function(e){return IV(e,!0)}(e);c._dataChannels.push(i),YN.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(Gw.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(YN.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{YN.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})),t&&(this.safeEmit(Gw.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach((e=>{const{uid:t,stream_id:i}=e,n=this._users.find((e=>e._uintid===t));if(!n)return void YN.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=n._dataChannels.find((t=>t.id===e.stream_id));r&&(YN.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then((e=>{if(n._dataChannels=n._dataChannels.filter((e=>e!==r)),e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),YN.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(Gw.USER_UNPUBLISHED,n,"datachannel",r._config))}))}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){YN.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{YN.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(Gw.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 YN.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(LU.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void YN.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach((e=>{const{value:n,type:r,expires:o}=t[e];o&&o<=i||r||RM()||!Object.prototype.hasOwnProperty.call(cN,e)||(mN[e]=n,hN[e]=n,YN.debug("Update gateway parameters from config distribute",e,n))}))}catch(e){YN.error("Error update config from local cache",e.message)}}()})),this._gateway.on(LU.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(LU.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===Vw.FALLBACK)return;const r=()=>{this.safeEmit(Gw.CONNECTION_STATE_CHANGE,e,t,i)};if(eD.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:kw.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:Mw.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),YN.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=>{YN.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{YN.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{YN.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{YN.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{YN.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_||(YN.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,HU.AUDIO,!1)),e._trust_video_mute_state_||(YN.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,HU.VIDEO,!1)),e._trust_audio_enabled_state_||(YN.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(YN.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(YN.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(YN.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(YN.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(LU.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new tD(Ew.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;const i=await rj(UG(UG({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));i?(t=i.ap,cj(i),this._joinInfo.preload=!0):(t=await rF(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||AO,this.store),this._joinInfo.preload=!1),this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[i,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:r}):n.push({host:i,port:r})})),e(n)}catch(e){t(e)}})),this._gateway.on(LU.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(Gw.NETWORK_QUALITY,e)})),this._gateway.on(LU.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(Gw.STREAM_TYPE_CHANGED,e,t);eD.reportApiInvoke(this._sessionId,{name:kw.STREAM_TYPE_CHANGE,options:[e,t],tag:Mw.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.on(LU.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(LU.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();_N("ENABLE_PREALLOC_PC")&&i||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(LU.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let i;e.attributes?i=e.attributes.userAttributes.preSubSsrcs:YN.debug("no attributes in joinResponse");const n=Qx(e.ortc,t,i);this._p2pChannel.connect(n)})),this._gateway.on(LU.PRE_CONNECT_PC,(async e=>{const{candidates:t,fingerprint:i}=e;if(this._joinInfo&&t.length>0&&!this._p2pChannel.isPlanB){var n;await this._p2pChannel.startP2PConnection({turnServer:this._joinInfo.turnServer});const{cert:e,cid:r}=this._joinInfo.apResponse;await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(r,"_").concat(e),icePwd:"".concat(r,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(n=_N("FINGERPRINT"))&&void 0!==n?n:i}]},candidates:t,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0})}}))}_handleGatewaySignalEvents(){this._gateway.signal.on(_U.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(_U.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(_U.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc))),this._gateway.signal.on(_U.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(_U.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(_U.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)})),this._gateway.signal.on(_U.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(_U.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(_U.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,HU.AUDIO,!0))),this._gateway.signal.on(_U.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,HU.AUDIO,!1))),this._gateway.signal.on(_U.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,HU.VIDEO,!0))),this._gateway.signal.on(_U.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,HU.VIDEO,!1))),this._gateway.signal.on(_U.RECEIVE_METADATA,(e=>{const t=rO(e.metadata);this.safeEmit(Gw.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(_U.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let i=rO(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Dn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.lengtht.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==i?void 0:i._audioSSRC)));n=null==r?void 0:r.jitterBufferMs}(null==n||Number.isNaN(n))&&(n=0),GB(UG(UG({},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(_U.ON_CRYPT_ERROR,(()=>{nO((()=>{YN.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(Gw.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(_U.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(_U.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{YN.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,Vw.TOKEN_EXPIRE),this.safeEmit(Gw.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(_U.ON_STREAM_FALLBACK_UPDATE,(e=>{YN.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(Gw.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(_U.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),YN.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(_U.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(_U.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(uU.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case hU.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some((e=>{let{stream_type:t}=e;return t===PU.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t!==PU.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===PU.Screen||t===PU.ScreenLow}));"offer"===t.state&&eD.publish(this._joinInfo.sid,{eventElapse:TF.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Ew.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(i=e.find((e=>{let{stream_type:t}=e;return t===PU.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:o?null===(n=e.find((e=>{let{stream_type:t}=e;return t!==PU.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case hU.SUBSCRIBE:t&&eD.subscribe(this._joinInfo.sid,{succ:!1,ec:Ew.TIMEOUT,audio:t.stream_type===HU.AUDIO,video:t.stream_type===HU.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:TF.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(_U.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(_U.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;_N("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!gM(e.string_id||e.stream_id,this.channelName))));const t=[],i=[];for(const n of e.users){let e=this._users.find((e=>e._uintid===n.stream_id));e?e._trust_in_room_=!0:(e=new IF(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(Gw.PUBLISHED_USER_LIST).length&&(YN.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(Gw.USER_JOINED,e)));const r=MU.Audio&n.stream_type,o=(MU.Video|MU.LwoVideo)&n.stream_type,s=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=o&&e.hasVideo;o&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(Gw.PUBLISHED_USER_LIST).length&&(YN.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(Gw.USER_PUBLISHED,e,"audio")),o&&!c&&0===this.getListeners(Gw.PUBLISHED_USER_LIST).length&&(YN.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(Gw.USER_PUBLISHED,e,"video")),(r&&!a||o&&!c||s)&&t.push(e),o&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(YN.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(i).catch((e=>{YN.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(Gw.PUBLISHED_USER_LIST).length>0?_N("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(YN.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(Gw.PUBLISHED_USER_LIST,t)):YN.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map((e=>e.uid)).join(", ")))})),this._gateway.signal.on(_U.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;this._p2pChannel instanceof PB&&this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return Dn(t=Object.keys(TN)).call(t,e)})))}))}_handleP2PEvents(){this._gateway.signal.on(_U.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(ox.PUBLISH,((e,t,i)=>{const{uid:n}=e;e.forEach((e=>{const{kind:r,ssrcs:o,mid:s,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,n,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===n));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,r,!!a)}))})),this._gateway.signal.on(ox.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(uU.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(ox.UNPUBLISH,(async(e,t,i)=>{if(this.store.useP2P){const{unpubMsg:n,uid:r}=e,o=this._users.find((e=>e.uid===r));if(!o)return YN.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{n.forEach((async e=>{let{stream_type:t}=e;const i=t===PU.Audio?HU.AUDIO:HU.VIDEO;await this._p2pChannel.unsubscribe(o,i),this._handleMuteStream(r,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(ox.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case ax.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,HU.VIDEO,!0);break;case ax.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,HU.AUDIO,!0);break;case ax.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,HU.VIDEO,!1);break;case ax.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,HU.AUDIO,!1)}})),this._gateway.signal.on(ox.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const{direction:i,iceParameter:n}=e;if(i!==EU.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(ox.CANDIDATE,(e=>{if(this.store.useP2P){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(JU.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(ox.RESTART_ICE,e,i===EU.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(JU.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(ox.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(JU.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(ox.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(JU.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===Ew.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(JU.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===Ew.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(JU.StateChange,((e,t)=>{t===XU.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(JU.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(Gw.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(JU.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===Ew.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(JU.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===Ew.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(JU.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(JU.RequestRePublishDataChannel,((e,t,i)=>{Wh.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==Ew.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(JU.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===HU.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(JU.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(JU.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(JU.MediaReconnectStart,(e=>{this.safeEmit(Gw.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(JU.MediaReconnectEnd,(e=>{this.safeEmit(Gw.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(JU.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(JU.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const{iceParameters:o}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r);await t.next({remoteIceParameters:o})})),this._p2pChannel.on(JU.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(JU.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:o}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),s=Qx(r,o);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(JU.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(JU.P2PLost,(()=>{this.safeEmit(Gw.P2P_LOST,this.store.uid)})),this._p2pChannel.on(JU.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(JU.ConnectionTypeChange,(e=>{this.safeEmit(Gw.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(JU.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(JU.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(JU.AudioMetadata,(e=>{this.safeEmit(Gw.AUDIO_METADATA,e)}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new tD(Ew.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},CV("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);const{appId:n,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await i.init({appId:n,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},AO)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on($U.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(Gw.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===QU.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(Gw.CONTENT_INSPECT_ERROR,new tD(Ew.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on($U.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===Ew.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return YN.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(Gw.CONTENT_INSPECT_RESULT,e,t)})),e.on($U.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new tD(Ew.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(fw(e,"enabled"),e){if(!t)throw new tD(Ew.INVALID_PARAMS,"config is required");if(Kj(t),!this._joinInfo)throw new tD(Ew.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},CV("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);const{appId:n,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await e.init({appId:n,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},AO)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new tD(Ew.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(nx.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(Gw.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===ix.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new tD(Ew.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(nx.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){Tw(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new tD(Ew.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,YN.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return YN.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){fw(e,"enabled"),pN("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}},rU(kG.prototype,"leave",[qj],Object.getOwnPropertyDescriptor(kG.prototype,"leave"),kG.prototype),rU(kG.prototype,"publish",[zj],Object.getOwnPropertyDescriptor(kG.prototype,"publish"),kG.prototype),rU(kG.prototype,"unpublish",[Xj],Object.getOwnPropertyDescriptor(kG.prototype,"unpublish"),kG.prototype),rU(kG.prototype,"subscribe",[Jj],Object.getOwnPropertyDescriptor(kG.prototype,"subscribe"),kG.prototype),rU(kG.prototype,"presubscribe",[Qj],Object.getOwnPropertyDescriptor(kG.prototype,"presubscribe"),kG.prototype),rU(kG.prototype,"massSubscribe",[Zj],Object.getOwnPropertyDescriptor(kG.prototype,"massSubscribe"),kG.prototype),rU(kG.prototype,"unsubscribe",[$j],Object.getOwnPropertyDescriptor(kG.prototype,"unsubscribe"),kG.prototype),rU(kG.prototype,"massUnsubscribe",[eG],Object.getOwnPropertyDescriptor(kG.prototype,"massUnsubscribe"),kG.prototype),rU(kG.prototype,"setLowStreamParameter",[tG],Object.getOwnPropertyDescriptor(kG.prototype,"setLowStreamParameter"),kG.prototype),rU(kG.prototype,"enableDualStream",[iG],Object.getOwnPropertyDescriptor(kG.prototype,"enableDualStream"),kG.prototype),rU(kG.prototype,"disableDualStream",[nG],Object.getOwnPropertyDescriptor(kG.prototype,"disableDualStream"),kG.prototype),rU(kG.prototype,"setClientRole",[rG],Object.getOwnPropertyDescriptor(kG.prototype,"setClientRole"),kG.prototype),rU(kG.prototype,"_setClientRoleOptions",[oG],Object.getOwnPropertyDescriptor(kG.prototype,"_setClientRoleOptions"),kG.prototype),rU(kG.prototype,"setProxyServer",[sG],Object.getOwnPropertyDescriptor(kG.prototype,"setProxyServer"),kG.prototype),rU(kG.prototype,"setTurnServer",[aG],Object.getOwnPropertyDescriptor(kG.prototype,"setTurnServer"),kG.prototype),rU(kG.prototype,"setLicense",[cG],Object.getOwnPropertyDescriptor(kG.prototype,"setLicense"),kG.prototype),rU(kG.prototype,"startProxyServer",[dG],Object.getOwnPropertyDescriptor(kG.prototype,"startProxyServer"),kG.prototype),rU(kG.prototype,"stopProxyServer",[lG],Object.getOwnPropertyDescriptor(kG.prototype,"stopProxyServer"),kG.prototype),rU(kG.prototype,"setLocalAccessPointsV2",[uG],Object.getOwnPropertyDescriptor(kG.prototype,"setLocalAccessPointsV2"),kG.prototype),rU(kG.prototype,"setLocalAccessPoints",[hG],Object.getOwnPropertyDescriptor(kG.prototype,"setLocalAccessPoints"),kG.prototype),rU(kG.prototype,"setRemoteDefaultVideoStreamType",[pG],Object.getOwnPropertyDescriptor(kG.prototype,"setRemoteDefaultVideoStreamType"),kG.prototype),rU(kG.prototype,"setRemoteVideoStreamType",[_G],Object.getOwnPropertyDescriptor(kG.prototype,"setRemoteVideoStreamType"),kG.prototype),rU(kG.prototype,"setStreamFallbackOption",[EG],Object.getOwnPropertyDescriptor(kG.prototype,"setStreamFallbackOption"),kG.prototype),rU(kG.prototype,"setEncryptionConfig",[mG],Object.getOwnPropertyDescriptor(kG.prototype,"setEncryptionConfig"),kG.prototype),rU(kG.prototype,"renewToken",[fG],Object.getOwnPropertyDescriptor(kG.prototype,"renewToken"),kG.prototype),rU(kG.prototype,"enableAudioVolumeIndicator",[TG],Object.getOwnPropertyDescriptor(kG.prototype,"enableAudioVolumeIndicator"),kG.prototype),rU(kG.prototype,"startLiveStreaming",[SG],Object.getOwnPropertyDescriptor(kG.prototype,"startLiveStreaming"),kG.prototype),rU(kG.prototype,"setLiveTranscoding",[gG],Object.getOwnPropertyDescriptor(kG.prototype,"setLiveTranscoding"),kG.prototype),rU(kG.prototype,"stopLiveStreaming",[RG],Object.getOwnPropertyDescriptor(kG.prototype,"stopLiveStreaming"),kG.prototype),rU(kG.prototype,"startChannelMediaRelay",[vG],Object.getOwnPropertyDescriptor(kG.prototype,"startChannelMediaRelay"),kG.prototype),rU(kG.prototype,"updateChannelMediaRelay",[CG],Object.getOwnPropertyDescriptor(kG.prototype,"updateChannelMediaRelay"),kG.prototype),rU(kG.prototype,"stopChannelMediaRelay",[IG],Object.getOwnPropertyDescriptor(kG.prototype,"stopChannelMediaRelay"),kG.prototype),rU(kG.prototype,"sendCustomReportMessage",[yG],Object.getOwnPropertyDescriptor(kG.prototype,"sendCustomReportMessage"),kG.prototype),rU(kG.prototype,"pickSVCLayer",[AG],Object.getOwnPropertyDescriptor(kG.prototype,"pickSVCLayer"),kG.prototype),rU(kG.prototype,"setRTMConfig",[bG],Object.getOwnPropertyDescriptor(kG.prototype,"setRTMConfig"),kG.prototype),rU(kG.prototype,"enableContentInspect",[wG],Object.getOwnPropertyDescriptor(kG.prototype,"enableContentInspect"),kG.prototype),rU(kG.prototype,"disableContentInspect",[OG],Object.getOwnPropertyDescriptor(kG.prototype,"disableContentInspect"),kG.prototype),rU(kG.prototype,"setImageModeration",[NG],Object.getOwnPropertyDescriptor(kG.prototype,"setImageModeration"),kG.prototype),rU(kG.prototype,"setP2PTransport",[DG],Object.getOwnPropertyDescriptor(kG.prototype,"setP2PTransport"),kG.prototype),rU(kG.prototype,"getJoinChannelServiceRecords",[PG],Object.getOwnPropertyDescriptor(kG.prototype,"getJoinChannelServiceRecords"),kG.prototype),rU(kG.prototype,"setPublishAudioFilterEnabled",[LG],Object.getOwnPropertyDescriptor(kG.prototype,"setPublishAudioFilterEnabled"),kG.prototype),kG);class VG{constructor(e,t){QI(this,"id",0),QI(this,"element",void 0),QI(this,"peerPair",void 0),QI(this,"context",void 0),QI(this,"audioPlayerElement",void 0),QI(this,"audioTrack",void 0),VG.count+=1,this.id=VG.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new Wh((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new tD(Ew.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 tD(Ew.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new tD(Ew.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(){YN.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 FG,BG;QI(VG,"count",0);const jG=window.AudioContext||window.webkitAudioContext;const GG=new(FG=$N({report:eD}),rU((BG=class{constructor(){QI(this,"units",[]),QI(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return YN.debug("the system does not need to process local aec"),-1;this.context||(this.context=new jG);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new VG(e,this.context),this.units.push(t)),t.startEchoCancellation(),YN.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return xb().name!==Lb.SAFARI}}).prototype,"processExternalMediaAEC",[FG],Object.getOwnPropertyDescriptor(BG.prototype,"processExternalMediaAEC"),BG.prototype),BG);function WG(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 HG(e){for(var t=1;t1&&void 0!==arguments[1]&&arguments[1];if(!KG)return;const i=hz._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(hz.onSecurityPolicyViolation||hz.getListeners(tx.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;_N("CSP_DETECTED_HOSTNAME_LIST").some((e=>Dn(t).call(t,e)))&&(hz.onSecurityPolicyViolation&&"function"==typeof hz.onSecurityPolicyViolation&&hz.onSecurityPolicyViolation(e),hz.getListeners(tx.SECURITY_POLICY_VIOLATION).length>0&&hz.safeEmit(tx.SECURITY_POLICY_VIOLATION,e))};i&&KG.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||hz.getListeners(tx.SECURITY_POLICY_VIOLATION).length>0)&&KG.addEventListener("securitypolicyviolation",n),hz._cspEventHandlerPointer=n}var qG=l,zG=_y,XG=RegExp.prototype,JG=function(e){return e===XG||qG(XG,e)?zG(e):e.flags},QG=i(JG);function ZG(e){let t=e.length;for(;--t>=0;)e[t]=0}const $G=256,eW=286,tW=30,iW=15,nW=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),rW=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),oW=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),sW=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),aW=new Array(576);ZG(aW);const cW=new Array(60);ZG(cW);const dW=new Array(512);ZG(dW);const lW=new Array(256);ZG(lW);const uW=new Array(29);ZG(uW);const hW=new Array(tW);function pW(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let _W,EW,mW;function fW(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}ZG(hW);const TW=e=>e<256?dW[e]:dW[256+(e>>>7)],SW=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},gW=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{gW(e,i[2*t],i[2*t+1])},vW=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},CW=(e,t,i)=>{const n=new Array(16);let r,o,s=0;for(r=1;r<=iW;r++)s=s+i[r-1]<<1,n[r]=s;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=vW(n[t]++,t))}},IW=e=>{let t;for(t=0;t{e.bi_valid>8?SW(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},AW=(e,t,i,n)=>{const r=2*t,o=2*i;return e[r]{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let n,r,o,s,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?RW(e,r,t):(o=lW[r],RW(e,o+$G+1,t),s=nW[o],0!==s&&(r-=uW[o],gW(e,r,s)),n--,o=TW(n),RW(e,o,i),s=rW[o],0!==s&&(n-=hW[o],gW(e,n,s)))}while(a{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let s,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,s=0;s>1;s>=1;s--)bW(e,i,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],bW(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,i[2*c]=i[2*s]+i[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,i[2*s+1]=i[2*a+1]=c,e.heap[1]=c++,bW(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=iW;h++)e.bl_count[h]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=i[2*i[2*l+1]+1]+1,h>c&&(h=c,E++),i[2*l+1]=h,l>n||(e.bl_count[h]++,p=0,l>=a&&(p=s[l-a]),_=i[2*l],e.opt_len+=_*(h+p),o&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>n||(i[2*u+1]!==h&&(e.opt_len+=(h-i[2*u+1])*i[2*u],i[2*u+1]=h),l--)}})(e,t),CW(i,d,e.bl_count)},NW=(e,t,i)=>{let n,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=s,s=t[2*(n+1)+1],++a{let n,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),n=0;n<=i;n++)if(r=s,s=t[2*(n+1)+1],!(++a{gW(e,0+(n?1:0),3),yW(e),SW(e,i),SW(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var kW=e=>{PW||((()=>{let e,t,i,n,r;const o=new Array(16);for(i=0,n=0;n<28;n++)for(uW[n]=i,e=0;e<1<>=7;n{let r,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<$G;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),OW(e,e.l_desc),OW(e,e.d_desc),s=(e=>{let t;for(NW(e,e.dyn_ltree,e.l_desc.max_code),NW(e,e.dyn_dtree,e.d_desc.max_code),OW(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*sW[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=r&&(r=o)):r=o=i+5,i+4<=r&&-1!==t?LW(e,t,i,n):4===e.strategy||o===r?(gW(e,2+(n?1:0),3),wW(e,aW,cW)):(gW(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(gW(e,t-257,5),gW(e,i-1,5),gW(e,n-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(lW[i]+$G+1)]++,e.dyn_dtree[2*TW(t)]++),e.sym_next===e.sym_end),xW=e=>{gW(e,2,3),RW(e,256,aW),(e=>{16===e.bi_valid?(SW(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},VW={_tr_init:kW,_tr_stored_block:LW,_tr_flush_block:MW,_tr_tally:UW,_tr_align:xW};var FW=(e,t,i,n)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;0!==i;){s=i>2e3?2e3:i,i-=s;do{r=r+t[n++]|0,o=o+r|0}while(--s);r%=65521,o%=65521}return r|o<<16|0};const BW=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var jW=(e,t,i,n)=>{const r=BW,o=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return-1^e},GW={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},WW={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:HW,_tr_stored_block:KW,_tr_flush_block:YW,_tr_tally:qW,_tr_align:zW}=VW,{Z_NO_FLUSH:XW,Z_PARTIAL_FLUSH:JW,Z_FULL_FLUSH:QW,Z_FINISH:ZW,Z_BLOCK:$W,Z_OK:eH,Z_STREAM_END:tH,Z_STREAM_ERROR:iH,Z_DATA_ERROR:nH,Z_BUF_ERROR:rH,Z_DEFAULT_COMPRESSION:oH,Z_FILTERED:sH,Z_HUFFMAN_ONLY:aH,Z_RLE:cH,Z_FIXED:dH,Z_DEFAULT_STRATEGY:lH,Z_UNKNOWN:uH,Z_DEFLATED:hH}=WW,pH=286,_H=30,EH=19,mH=2*pH+1,fH=15,TH=258,SH=262,gH=42,RH=113,vH=666,CH=(e,t)=>(e.msg=GW[t],t),IH=e=>2*e-(e>4?9:0),yH=e=>{let t=e.length;for(;--t>=0;)e[t]=0},AH=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let bH=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},OH=(e,t)=>{YW(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,wH(e.strm)},NH=(e,t)=>{e.pending_buf[e.pending++]=t},DH=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},PH=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=FW(e.adler,t,r,i):2===e.state.wrap&&(e.adler=jW(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},LH=(e,t)=>{let i,n,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-SH?e.strstart-(e.w_size-SH):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+TH;let p=d[o+s-1],_=d[o+s];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+s]===_&&d[i+s-1]===p&&d[i]===d[o]&&d[++i]===d[o+1]){o+=2,i++;do{}while(d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&os){if(e.match_start=t,s=n,n>=a)break;p=d[o+s-1],_=d[o+s]}}}while((t=u[t&l])>c&&0!=--r);return s<=e.lookahead?s:e.lookahead},kH=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-SH)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),AH(e),n+=t),0===e.strm.avail_in)break;if(i=PH(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=bH(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=bH(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,n,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outn+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,wH(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(PH(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===s);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(PH(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=o||(n||t===ZW)&&t!==XW&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,s=t===ZW&&0===e.strm.avail_in&&i===n?1:0,KW(e,e.block_start,i,s),e.block_start+=i,wH(e.strm)),s?3:1)},UH=(e,t)=>{let i,n;for(;;){if(e.lookahead=3&&(e.ins_h=bH(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-SH&&(e.match_length=LH(e,i)),e.match_length>=3)if(n=qW(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=bH(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=bH(e,e.ins_h,e.window[e.strstart+1]);else n=qW(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(OH(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ZW?(OH(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(OH(e,!1),0===e.strm.avail_out)?1:2},xH=(e,t)=>{let i,n,r;for(;;){if(e.lookahead=3&&(e.ins_h=bH(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=qW(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=bH(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(OH(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=qW(e,0,e.window[e.strstart-1]),n&&OH(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=qW(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ZW?(OH(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(OH(e,!1),0===e.strm.avail_out)?1:2};function VH(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const FH=[new VH(0,0,0,0,MH),new VH(4,4,8,4,UH),new VH(4,5,16,8,UH),new VH(4,6,32,32,UH),new VH(4,4,16,16,xH),new VH(8,16,32,32,xH),new VH(8,16,128,128,xH),new VH(8,32,128,256,xH),new VH(32,128,258,1024,xH),new VH(32,258,258,4096,xH)];function BH(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=hH,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*mH),this.dyn_dtree=new Uint16Array(2*(2*_H+1)),this.bl_tree=new Uint16Array(2*(2*EH+1)),yH(this.dyn_ltree),yH(this.dyn_dtree),yH(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(fH+1),this.heap=new Uint16Array(2*pH+1),yH(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*pH+1),yH(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const jH=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==gH&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==RH&&t.status!==vH?1:0},GH=e=>{if(jH(e))return CH(e,iH);e.total_in=e.total_out=0,e.data_type=uH;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?gH:RH,e.adler=2===t.wrap?0:1,t.last_flush=-2,HW(t),eH},WH=e=>{const t=GH(e);return t===eH&&(e=>{e.window_size=2*e.w_size,yH(e.head),e.max_lazy_match=FH[e.level].max_lazy,e.good_match=FH[e.level].good_length,e.nice_match=FH[e.level].nice_length,e.max_chain_length=FH[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},HH=(e,t,i,n,r,o)=>{if(!e)return iH;let s=1;if(t===oH&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||i!==hH||n<8||n>15||t<0||t>9||o<0||o>dH||8===n&&1!==s)return CH(e,iH);8===n&&(n=9);const a=new BH;return e.state=a,a.strm=e,a.status=gH,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<{if(jH(e)||t>$W||t<0)return e?CH(e,iH):iH;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===vH&&t!==ZW)return CH(e,0===e.avail_out?rH:iH);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(wH(e),0===e.avail_out)return i.last_flush=-1,eH}else if(0===e.avail_in&&IH(t)<=IH(n)&&t!==ZW)return CH(e,rH);if(i.status===vH&&0!==e.avail_in)return CH(e,rH);if(i.status===gH&&0===i.wrap&&(i.status=RH),i.status===gH){let t=hH+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=aH||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,DH(i,t),0!==i.strstart&&(DH(i,e.adler>>>16),DH(i,65535&e.adler)),e.adler=1,i.status=RH,wH(e),0!==i.pending)return i.last_flush=-1,eH}if(57===i.status)if(e.adler=0,NH(i,31),NH(i,139),NH(i,8),i.gzhead)NH(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),NH(i,255&i.gzhead.time),NH(i,i.gzhead.time>>8&255),NH(i,i.gzhead.time>>16&255),NH(i,i.gzhead.time>>24&255),NH(i,9===i.level?2:i.strategy>=aH||i.level<2?4:0),NH(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(NH(i,255&i.gzhead.extra.length),NH(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=jW(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(NH(i,0),NH(i,0),NH(i,0),NH(i,0),NH(i,0),NH(i,9===i.level?2:i.strategy>=aH||i.level<2?4:0),NH(i,3),i.status=RH,wH(e),0!==i.pending)return i.last_flush=-1,eH;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=jW(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,wH(e),0!==i.pending)return i.last_flush=-1,eH;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=jW(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=jW(e.adler,i.pending_buf,i.pending-n,n)),wH(e),0!==i.pending)return i.last_flush=-1,eH;n=0}t=i.gzindexn&&(e.adler=jW(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=jW(e.adler,i.pending_buf,i.pending-n,n)),wH(e),0!==i.pending)return i.last_flush=-1,eH;n=0}t=i.gzindexn&&(e.adler=jW(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(wH(e),0!==i.pending))return i.last_flush=-1,eH;NH(i,255&e.adler),NH(i,e.adler>>8&255),e.adler=0}if(i.status=RH,wH(e),0!==i.pending)return i.last_flush=-1,eH}if(0!==e.avail_in||0!==i.lookahead||t!==XW&&i.status!==vH){let n=0===i.level?MH(i,t):i.strategy===aH?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(kH(e),0===e.lookahead)){if(t===XW)return 1;break}if(e.match_length=0,i=qW(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(OH(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ZW?(OH(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(OH(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===cH?((e,t)=>{let i,n,r,o;const s=e.window;for(;;){if(e.lookahead<=TH){if(kH(e),e.lookahead<=TH&&t===XW)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){o=e.strstart+TH;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=qW(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=qW(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(OH(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ZW?(OH(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(OH(e,!1),0===e.strm.avail_out)?1:2})(i,t):FH[i.level].func(i,t);if(3!==n&&4!==n||(i.status=vH),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),eH;if(2===n&&(t===JW?zW(i):t!==$W&&(KW(i,0,0,!1),t===QW&&(yH(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),wH(e),0===e.avail_out))return i.last_flush=-1,eH}return t!==ZW?eH:i.wrap<=0?tH:(2===i.wrap?(NH(i,255&e.adler),NH(i,e.adler>>8&255),NH(i,e.adler>>16&255),NH(i,e.adler>>24&255),NH(i,255&e.total_in),NH(i,e.total_in>>8&255),NH(i,e.total_in>>16&255),NH(i,e.total_in>>24&255)):(DH(i,e.adler>>>16),DH(i,65535&e.adler)),wH(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?eH:tH)},YH=(e,t)=>{let i=t.length;if(jH(e))return iH;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==gH||n.lookahead)return iH;if(1===r&&(e.adler=FW(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(yH(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,kH(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=bH(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,kH(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,n.wrap=r,eH},qH={deflateInit:(e,t)=>HH(e,t,hH,15,8,lH),deflateInit2:HH,deflateReset:WH,deflateResetKeep:GH,deflateSetHeader:(e,t)=>jH(e)||2!==e.state.wrap?iH:(e.state.gzhead=t,eH),deflate:KH,deflateEnd:e=>{if(jH(e))return iH;const t=e.state.status;return e.state=null,t===RH?CH(e,nH):eH},deflateSetDictionary:YH,deflateInfo:"pako deflate (from Nodeca project)"};const zH=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var XH={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)zH(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;QH[254]=QH[254]=1;var ZH={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,o,s=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const o=new Array(2*i);for(r=0,n=0;n4)o[r++]=65533,n+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&n1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&JH)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+QH[e[i]]>t?i:t}};var $H=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const eK=Object.prototype.toString,{Z_NO_FLUSH:tK,Z_SYNC_FLUSH:iK,Z_FULL_FLUSH:nK,Z_FINISH:rK,Z_OK:oK,Z_STREAM_END:sK,Z_DEFAULT_COMPRESSION:aK,Z_DEFAULT_STRATEGY:cK,Z_DEFLATED:dK}=WW;function lK(e){this.options=XH.assign({level:aK,method:dK,chunkSize:16384,windowBits:15,memLevel:8,strategy:cK},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $H,this.strm.avail_out=0;let i=qH.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==oK)throw new Error(GW[i]);if(t.header&&qH.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ZH.string2buf(t.dictionary):"[object ArrayBuffer]"===eK.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=qH.deflateSetDictionary(this.strm,e),i!==oK)throw new Error(GW[i]);this._dict_set=!0}}function uK(e,t){const i=new lK(t);if(i.push(e,!0),i.err)throw i.msg||GW[i.err];return i.result}lK.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?rK:tK,"string"==typeof e?i.input=ZH.string2buf(e):"[object ArrayBuffer]"===eK.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(o===iK||o===nK)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=qH.deflate(i,o),r===sK)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=qH.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===oK;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},lK.prototype.onData=function(e){this.chunks.push(e)},lK.prototype.onEnd=function(e){e===oK&&(this.result=XH.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var hK={Deflate:lK,deflate:uK,deflateRaw:function(e,t){return(t=t||{}).raw=!0,uK(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,uK(e,t)},constants:WW};const pK=16209;var _K=function(e,t){let i,n,r,o,s,a,c,d,l,u,h,p,_,E,m,f,T,S,g,R,v,C,I,y;const A=e.state;i=e.next_in,I=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,u=A.window,h=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<>>24,h>>>=S,p-=S,S=T>>>16&255,0===S)y[r++]=65535&T;else{if(!(16&S)){if(0==(64&S)){T=_[(65535&T)+(h&(1<>>=S,p-=S),p<15&&(h+=I[i++]<>>24,h>>>=S,p-=S,S=T>>>16&255,!(16&S)){if(0==(64&S)){T=E[(65535&T)+(h&(1<a){e.msg="invalid distance too far back",A.mode=pK;break e}if(h>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&A.sane){e.msg="invalid distance too far back",A.mode=pK;break e}if(v=0,C=u,0===l){if(v+=c-S,S2;)y[r++]=C[v++],y[r++]=C[v++],y[r++]=C[v++],g-=3;g&&(y[r++]=C[v++],g>1&&(y[r++]=C[v++]))}else{v=r-R;do{y[r++]=y[v++],y[r++]=y[v++],y[r++]=y[v++],g-=3}while(g>2);g&&(y[r++]=y[v++],g>1&&(y[r++]=y[v++]))}break}}break}}while(i>3,i-=g,p-=g<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,T=0,S=0,g=0,R=0,v=0,C=0,I=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=EK;E++)A[E]=0;for(m=0;m=1&&0===A[T];T--);if(S>T&&(S=T),0===T)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f0&&(0===e||1!==T))return-1;for(b[1]=0,E=1;E852||2===e&&C>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=y[s[m]-_]):(O=96,N=0),d=1<>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<>=1;if(0!==d?(I&=d-1,I+=d):I=0,m++,0==--A[E]){if(E===T)break;E=t[i+s[m]]}if(E>S&&(I&h)!==u){for(0===R&&(R=S),p+=f,g=E-R,v=1<852||2===e&&C>592)return 1;u=I&h,r[u]=S<<24|g<<16|p-o|0}}return 0!==I&&(r[p+I]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:RK,Z_BLOCK:vK,Z_TREES:CK,Z_OK:IK,Z_STREAM_END:yK,Z_NEED_DICT:AK,Z_STREAM_ERROR:bK,Z_DATA_ERROR:wK,Z_MEM_ERROR:OK,Z_BUF_ERROR:NK,Z_DEFLATED:DK}=WW,PK=16180,LK=16190,kK=16191,MK=16192,UK=16194,xK=16199,VK=16200,FK=16206,BK=16209,jK=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function GK(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const WK=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},HK=e=>{if(WK(e))return bK;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=PK,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,IK},KK=e=>{if(WK(e))return bK;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,HK(e)},YK=(e,t)=>{let i;if(WK(e))return bK;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?bK:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,KK(e))},qK=(e,t)=>{if(!e)return bK;const i=new GK;e.state=i,i.strm=e,i.window=null,i.mode=PK;const n=YK(e,t);return n!==IK&&(e.state=null),n};let zK,XK,JK=!0;const QK=e=>{if(JK){zK=new Int32Array(512),XK=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(gK(1,e.lens,0,288,zK,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;gK(2,e.lens,0,32,XK,0,e.work,{bits:5}),JK=!1}e.lencode=zK,e.lenbits=9,e.distcode=XK,e.distbits=5},ZK=(e,t,i,n)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>n&&(r=n),o.window.set(t.subarray(i-n,i-n+r),o.wnext),(n-=r)?(o.window.set(t.subarray(i-n,i),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,n,r,o,s,a,c,d,l,u,h,p,_,E,m,f,T,S,g,R,v,C,I=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(WK(e)||!e.output||!e.input&&0!==e.avail_in)return bK;i=e.state,i.mode===kK&&(i.mode=MK),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,C=IK;e:for(;;)switch(i.mode){case PK:if(0===i.wrap){i.mode=MK;break}for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=jW(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=BK;break}if((15&d)!==DK){e.msg="unknown compression method",i.mode=BK;break}if(d>>>=4,l-=4,v=8+(15&d),0===i.wbits&&(i.wbits=v),v>15||v>i.wbits){e.msg="invalid window size",i.mode=BK;break}i.dmax=1<>8&1),512&QG(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=jW(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=jW(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>8),512&QG(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=jW(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&QG(i)){for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=jW(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&QG(i)&&(p=i.length,p>a&&(p=a),p&&(i.head&&(v=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(o,o+p),v)),512&QG(i)&&4&i.wrap&&(i.check=jW(i.check,n,p,o)),a-=p,o+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&QG(i)){if(0===a)break e;p=0;do{v=n[o+p++],i.head&&v&&i.length<65536&&(i.head.name+=String.fromCharCode(v))}while(v&&p>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=kK;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>=7&l,l-=7&l,i.mode=FK;break}for(;l<3;){if(0===a)break e;a--,d+=n[o++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(QK(i),i.mode=xK,t===CK){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=BK}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=BK;break}if(i.length=65535&d,d=0,l=0,i.mode=UK,t===CK)break e;case UK:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,i.length-=p;break}i.mode=kK;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[o++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=BK;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},C=gK(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,C){e.msg="invalid code lengths set",i.mode=BK;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=m,l-=m,i.lens[i.have++]=T;else{if(16===T){for(b=m+2;l>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=BK;break}v=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===T){for(b=m+3;l>>=m,l-=m,v=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l>>=m,l-=m,v=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=BK;break}for(;p--;)i.lens[i.have++]=v}}if(i.mode===BK)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=BK;break}if(i.lenbits=9,A={bits:i.lenbits},C=gK(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,C){e.msg="invalid literal/lengths set",i.mode=BK;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},C=gK(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,C){e.msg="invalid distances set",i.mode=BK;break}if(i.mode=xK,t===CK)break e;case xK:i.mode=VK;case VK:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=d,i.bits=l,_K(e,h),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===kK&&(i.back=-1);break}for(i.back=0;I=i.lencode[d&(1<>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],m=I>>>24,f=I>>>16&255,T=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,i.length=T,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=kK;break}if(64&f){e.msg="invalid literal/length code",i.mode=BK;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;I=i.distcode[d&(1<>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],m=I>>>24,f=I>>>16&255,T=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=BK;break}i.offset=T,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=BK;break}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=BK;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=s-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[s++]=E[_++]}while(--p);0===i.length&&(i.mode=VK);break;case 16205:if(0===c)break e;r[s++]=i.length,c--,i.mode=VK;break;case FK:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[o++]<qK(e,15),inflateInit2:qK,inflate:$K,inflateEnd:e=>{if(WK(e))return bK;let t=e.state;return t.window&&(t.window=null),e.state=null,IK},inflateGetHeader:(e,t)=>{if(WK(e))return bK;const i=e.state;return 0==(2&i.wrap)?bK:(i.head=t,t.done=!1,IK)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,o;return WK(e)?bK:(n=e.state,0!==n.wrap&&n.mode!==LK?bK:n.mode===LK&&(r=1,r=FW(r,t,i,0),r!==n.check)?wK:(o=ZK(e,t,i,i),o?(n.mode=16210,OK):(n.havedict=1,IK)))},inflateInfo:"pako inflate (from Nodeca project)"};var tY=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const iY=Object.prototype.toString,{Z_NO_FLUSH:nY,Z_FINISH:rY,Z_OK:oY,Z_STREAM_END:sY,Z_NEED_DICT:aY,Z_STREAM_ERROR:cY,Z_DATA_ERROR:dY,Z_MEM_ERROR:lY}=WW;function uY(e){this.options=XH.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $H,this.strm.avail_out=0;let i=eY.inflateInit2(this.strm,t.windowBits);if(i!==oY)throw new Error(GW[i]);if(this.header=new tY,eY.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=ZH.string2buf(t.dictionary):"[object ArrayBuffer]"===iY.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=eY.inflateSetDictionary(this.strm,t.dictionary),i!==oY)))throw new Error(GW[i])}function hY(e,t){const i=new uY(t);if(i.push(e),i.err)throw i.msg||GW[i.err];return i.result}uY.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?rY:nY,"[object ArrayBuffer]"===iY.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),o=eY.inflate(i,s),o===aY&&r&&(o=eY.inflateSetDictionary(i,r),o===oY?o=eY.inflate(i,s):o===dY&&(o=aY));i.avail_in>0&&o===sY&&i.state.wrap>0&&0!==e[i.next_in];)eY.inflateReset(i),o=eY.inflate(i,s);switch(o){case cY:case dY:case aY:case lY:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===sY))if("string"===this.options.to){let e=ZH.utf8border(i.output,i.next_out),t=i.next_out-e,r=ZH.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==oY||0!==a){if(o===sY)return o=eY.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},uY.prototype.onData=function(e){this.chunks.push(e)},uY.prototype.onEnd=function(e){e===oY&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=XH.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var pY={Inflate:uY,inflate:hY,inflateRaw:function(e,t){return(t=t||{}).raw=!0,hY(e,t)},ungzip:hY,constants:WW};const{Deflate:_Y,deflate:EY,deflateRaw:mY,gzip:fY}=hK,{Inflate:TY,inflate:SY,inflateRaw:gY,ungzip:RY}=pY;var vY=EY,CY=SY,IY=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(IY||{});class yY{constructor(){QI(this,"_sequence",0),QI(this,"_startTime",Date.now()),QI(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;_N("SHOW_DATASTREAM2_LOG")&&YN.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let o=0;if(r.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,r.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,r.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),o),o+=e.byteLength}if(n.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let o,s;if(i+=4,_N("SHOW_DATASTREAM2_LOG")&&YN.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){s=this.deserializeExtension(e.slice(i)),i+=2+s.length,o=e.slice(i);let t=!1;if(s.datas.length>0){const e=s.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,i),n.forEach((e=>{t?(s.setUint8(a++,e.id),s.setUint8(a++,e.length),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(s.setUint8(a++,e.id|e.length<<4),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const o=n===IY.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),s.push({id:e,length:t,data:i})}if(c!==r)throw Error("parse error");return{profile:n,length:r,datas:s}}decompress(e){return CY(new Uint8Array(e))}compress(e){return vY(new Uint8Array(e))}}const AY={name:"DataStream",create:(e,t)=>{const i=t?new Lk(e):new kk(e);return i.useDataStream(new yY),i}};class bY extends Dw{constructor(e,t,i){super(),QI(this,"ws",void 0),QI(this,"requestId",1),QI(this,"heartBeatTimer",void 0),QI(this,"joinInfo",void 0),QI(this,"clientId",void 0),QI(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),QI(this,"onClose",(e=>{this.emit("close"),this.dispose()})),QI(this,"onMessage",(e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new yx("cross-channel-".concat(this.clientId),i),this.ws.on(mU.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(mU.CONNECTED,this.onOpen),this.ws.on(mU.ON_MESSAGE,this.onMessage),this.ws.on(mU.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Wh(((t,i)=>{const n=window.setTimeout((()=>{i(new tD(Ew.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new tD(Ew.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(n),i(new tD(Ew.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new tD(Ew.WS_DISCONNECT);const t=()=>new Wh(((e,t)=>{this.ws.once(mU.CLOSED,(()=>t(new tD(Ew.WS_ABORT)))),this.ws.once(mU.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Wh(((e,t)=>{const n=()=>{t(new tD(Ew.WS_ABORT))};this.ws.once(mU.RECONNECTING,n),this.ws.once(mU.CLOSED,n),this.once("req_".concat(i),e),uO(3e3).then((()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(mU.RECONNECTING,n),this.ws.off(mU.CLOSED,n),t(new tD(Ew.TIMEOUT,"cross channel ws request timeout"))}))})),r=await n;if(!r||200!==r.code)throw new tD(Ew.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(mU.REQUEST_NEW_URLS),this.ws.on(mU.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class wY extends Dw{set state(e){e!==this._state&&(e!==NU.RELAY_STATE_FAILURE&&(this.errorCode=DU.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),QI(this,"joinInfo",void 0),QI(this,"sid",void 0),QI(this,"clientId",void 0),QI(this,"cancelToken",Ab.CancelToken.source()),QI(this,"workerToken",void 0),QI(this,"requestId",0),QI(this,"signal",void 0),QI(this,"prevChannelMediaConfig",void 0),QI(this,"httpRetryConfig",void 0),QI(this,"_resolution",void 0),QI(this,"_state",NU.RELAY_STATE_IDLE),QI(this,"errorCode",DU.RELAY_OK),QI(this,"onStatus",(e=>{YN.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",OU.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",OU.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=DU.SRC_TOKEN_EXPIRED,this.state=NU.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=DU.DEST_TOKEN_EXPIRED,this.state=NU.RELAY_STATE_FAILURE))})),QI(this,"onReconnect",(async()=>{YN.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",OU.NETWORK_DISCONNECTED),this.state=NU.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==NU.RELAY_STATE_IDLE&&(YN.error("auto restart channel media relay failed",e.toString()),this.errorCode=DU.SERVER_CONNECTION_LOST,this.state=NU.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=pO(),this.signal=new bY(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==NU.RELAY_STATE_IDLE)throw new tD(Ew.INVALID_OPERATION);this.state=NU.RELAY_STATE_CONNECTING,await this.connect(),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new tD(Ew.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new tD(Ew.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new tD(Ew.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==NU.RELAY_STATE_RUNNING)throw new tD(Ew.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==NU.RELAY_STATE_RUNNING)throw new tD(Ew.INVALID_OPERATION);const t=this.genMessage(wU.SetVideoProfile);await this.signal.request(t),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),YN.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=NU.RELAY_STATE_IDLE,this.dispose()}dispose(){YN.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=Ab.CancelToken.source(),this.state=NU.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await uF(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",OU.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(wU.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(wU.SetSdkProfile,e);await this.signal.request(i),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(wU.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",OU.PACKET_JOINED_SRC_CHANNEL),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(wU.SetSourceUserId,e);await this.signal.request(r),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(wU.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",OU.PACKET_JOINED_DEST_CHANNEL),YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const s=this.genMessage(wU.StartPacketTransfer,e);await this.signal.request(s),this.emit("event",OU.PACKET_SENT_TO_DEST_CHANNEL),this.state=NU.RELAY_STATE_RUNNING,YN.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(wU.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",OU.PACKET_UPDATE_DEST_CHANNEL),YN.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(wU.StopPacketTransfer);await this.signal.request(e),YN.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:rN,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.23.2"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case wU.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case wU.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new tD(Ew.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case wU.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new tD(Ew.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case wU.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new tD(Ew.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},o;case wU.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case wU.Reconnect:return o.clientRequest={command:"Reconnect"},o;case wU.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case wU.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new tD(Ew.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},o;case wU.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const OY={name:"ChannelMediaRelay",create:function(e){return new wY(e.joinInfo,e.clientId,e.websocketRetryConfig||AO,e.httpRetryConfig||AO,e.resolution)}};function NY(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 DY(e){for(var t=1;t{this.reconnectMode="retry",this.startPingPong()})),QI(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(eD.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===SU.TRANSCODE?1:2}),this.emit(IU.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new yx("live-streaming",i),this.websocket.on(mU.CONNECTED,this.handleWebSocketOpen),this.websocket.on(mU.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(mU.REQUEST_NEW_URLS,((e,t)=>{Yw(this,IU.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(mU.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new tD(Ew.UNEXPECTED_ERROR);const s=DY({command:e,sdkVersion:"4.23.2"===rN?"0.0.1":rN,seq:o,requestId:o,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new tD(Ew.WS_DISCONNECT);const a=()=>new Wh(((e,t)=>{this.websocket.once(mU.CLOSED,(()=>t(new tD(Ew.WS_ABORT)))),this.websocket.once(mU.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Wh(((e,t)=>{const i=()=>{t(new tD(Ew.WS_ABORT))};this.websocket.once(mU.RECONNECTING,i),this.websocket.once(mU.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&eD.workerEvent(this.spec.sid,DY(DY({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let l=null;try{l=await c}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&eD.workerEvent(this.spec.sid,DY(DY({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.23.2"===rN?"0.0.1":rN;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case AU.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void YN.warning("live stream response already exists stream");case AU.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case AU.LIVE_STREAM_RESPONSE_BAD_STREAM:case AU.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new tD(Ew.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case AU.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case AU.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new tD(Ew.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case AU.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new tD(Ew.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(IU.WARNING,t,e.serverResponse.url)}case AU.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new tD(Ew.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(IU.WARNING,t,e.serverResponse.url)}case AU.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case AU.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new tD(Ew.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case AU.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new tD(Ew.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(IU.WARNING,t,e.serverResponse.url)}case AU.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case AU.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case AU.LIVE_STREAM_RESPONSE_WORKER_LOST:case AU.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case AU.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case AU.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new tD(Ew.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(_O)}),6e3)}}function LY(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 kY(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:AO,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:AO;super(),QI(this,"onLiveStreamWarning",void 0),QI(this,"onLiveStreamError",void 0),QI(this,"spec",void 0),QI(this,"retryTimeout",1e4),QI(this,"connection",void 0),QI(this,"httpRetryConfig",void 0),QI(this,"wsRetryConfig",void 0),QI(this,"streamingTasks",new Map),QI(this,"isStartingStreamingTask",!1),QI(this,"taskMutex",new IO("live-streaming")),QI(this,"cancelToken",Ab.CancelToken.source()),QI(this,"transcodingConfig",void 0),QI(this,"uapResponse",void 0),QI(this,"lastTaskId",1),QI(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=kY(kY({},CU),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(YN.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>kY(kY(kY({},gU),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){Cw(e.width)||Sw(e.width,"config.width",0,1e4),Cw(e.height)||Sw(e.height,"config.height",0,1e4),Cw(e.videoBitrate)||Sw(e.videoBitrate,"config.videoBitrate",1,1e6),Cw(e.videoFrameRate)||Sw(e.videoFrameRate,"config.videoFrameRate"),Cw(e.lowLatency)||fw(e.lowLatency,"config.lowLatency"),Cw(e.audioSampleRate)||Tw(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Cw(e.audioBitrate)||Sw(e.audioBitrate,"config.audioBitrate",1,128),Cw(e.audioChannels)||Tw(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Cw(e.videoGop)||Sw(e.videoGop,"config.videoGop"),Cw(e.videoCodecProfile)||Tw(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Cw(e.userCount)||Sw(e.userCount,"config.userCount",0,17),Cw(e.backgroundColor)||Sw(e.backgroundColor,"config.backgroundColor",0,16777215),Cw(e.userConfigExtraInfo)||Rw(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Cw(e.transcodingUsers)&&(vw(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{TU(e.uid),Cw(e.x)||Sw(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Cw(e.y)||Sw(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Cw(e.width)||Sw(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Cw(e.height)||Sw(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Cw(e.zOrder)||Sw(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Cw(e.alpha)||Sw(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),Cw(e.watermark)||vU(e.watermark,"watermark"),Cw(e.backgroundImage)||vU(e.backgroundImage,"backgroundImage"),e.images&&!Cw(e.images)&&(vw(e.images,"config.images"),e.images.forEach(((e,t)=>{vU(e,"images[".concat(t,"]"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>kY(kY(kY({},RU),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(kY(kY(kY({},RU),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(kY(kY(kY({},RU),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>kY({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Wh.resolve(e.uid):sF(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Wh.all(n)).forEach(((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(Zh(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});YN.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{YN.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{YN.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{YN.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,i){if(!this.transcodingConfig&&t===SU.TRANSCODE)throw new tD(Ew.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const n={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};YN.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&i)return void r();if(this.streamingTasks.get(e)&&!i)return r(),new tD(Ew.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case SU.TRANSCODE:n.transcodingConfig=kY({},this.transcodingConfig);case SU.RAW:}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new Wh(((t,n)=>{uO(this.retryTimeout).then((()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),a=await Wh.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===SU.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,YN.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:n,mode:t,url:e,taskId:o}),r()}catch(n){if(r(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Wh(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new tD(Ew.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{YN.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===SU.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{YN.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(i)}))}resetAllTask(){var e;const t=Array.from(Zh(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=Ab.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new tD(Ew.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await Yw(this,yU.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new PY(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(IU.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(IU.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(IU.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new tD(Ew.UNEXPECTED_ERROR,"can not get new live streaming address list"));Yw(this,yU.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(i)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case AU.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case AU.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new tD(Ew.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return YN.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case AU.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new tD(Ew.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case AU.LIVE_STREAM_RESPONSE_WORKER_LOST:case AU.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(Zh(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(YN.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new tD(Ew.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{YN.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)})).catch((e=>{YN.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const UY={name:"LiveStreaming",create:function(e){return new MY(e.joinInfo,e.websocketRetryConfig||AO,e.httpRetryConfig||AO)}};function xY(e){let t=zY();return function(e,t){let i=e.appId;void 0!==i&&(cq(t,10),tq(t,i));let n=e.cid;void 0!==n&&(cq(t,16),cq(t,n));let r=e.cname;void 0!==r&&(cq(t,26),tq(t,r));let o=e.deviceId;void 0!==o&&(cq(t,34),tq(t,o));let s=e.elapse;void 0!==s&&(cq(t,40),dq(t,s));let a=e.fileSize;void 0!==a&&(cq(t,48),dq(t,YY(a)));let c=e.height;void 0!==c&&(cq(t,56),dq(t,YY(c)));let d=e.jpg;void 0!==d&&(cq(t,66),cq(t,d.length),function(e,t){let i=ZY(e,t.length);e.bytes.set(t,i)}(t,d));let l=e.networkType;void 0!==l&&(cq(t,72),dq(t,YY(l)));let u=e.osType;void 0!==u&&(cq(t,80),dq(t,YY(u)));let h=e.requestId;void 0!==h&&(cq(t,90),tq(t,h));let p=e.sdkVersion;void 0!==p&&(cq(t,98),tq(t,p));let _=e.sequence;void 0!==_&&(cq(t,104),dq(t,YY(_)));let E=e.sid;void 0!==E&&(cq(t,114),tq(t,E));let m=e.timestamp;void 0!==m&&(cq(t,120),dq(t,m));let f=e.uid;void 0!==f&&(cq(t,128),cq(t,f));let T=e.vid;void 0!==T&&(cq(t,136),cq(t,T));let S=e.width;void 0!==S&&(cq(t,144),dq(t,YY(S)));let g=e.service;void 0!==g&&(cq(t,152),cq(t,g));let R=e.callbackData;void 0!==R&&(cq(t,162),tq(t,R));let v=e.jpgEncryption;void 0!==v&&(cq(t,168),cq(t,v));let C=e.requestType;void 0!==C&&(cq(t,176),cq(t,C));let I=e.scorePorn;void 0!==I&&(cq(t,185),sq(t,I));let y=e.scoreSexy;void 0!==y&&(cq(t,193),sq(t,y));let A=e.scoreNeutral;void 0!==A&&(cq(t,201),sq(t,A));let b=e.scene;void 0!==b&&(cq(t,208),cq(t,b));let w=e.ossFilePrefix;void 0!==w&&(cq(t,218),tq(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){cq(t,226);let i=zY();BY(e,i),cq(t,i.limit),iq(t,i),XY(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function VY(e){return function(e){let t={};e:for(;!QY(e);){let i=aq(e);switch(i>>>3){case 0:break e;case 1:t.code=aq(e);break;case 2:t.msg=eq(e,aq(e));break;case 3:{let i=jY(e);t.data=FY(e),e.limit=i;break}default:GY(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function FY(e){let t={};e:for(;!QY(e);){let i=aq(e);switch(i>>>3){case 0:break e;case 1:t.requestId=eq(e,aq(e));break;case 2:t.requestType=aq(e)>>>0;break;case 3:t.scorePorn=oq(e);break;case 4:t.scoreSexy=oq(e);break;case 5:t.scoreNeutral=oq(e);break;case 6:t.requestScene=aq(e)>>>0;break;case 7:t.scene=aq(e)>>>0;break;default:GY(e,7&i)}}return t}function BY(e,t){let i=e.service;void 0!==i&&(cq(t,8),cq(t,i));let n=e.vendor;void 0!==n&&(cq(t,16),cq(t,n));let r=e.token;void 0!==r&&(cq(t,26),tq(t,r));let o=e.callbackUrl;void 0!==o&&(cq(t,34),tq(t,o))}function jY(e){let t=aq(e),i=e.limit;return e.limit=e.offset+t,i}function GY(e,t){switch(t){case 0:for(;128&nq(e););break;case 2:JY(e,aq(e));break;case 5:JY(e,4);break;case 1:JY(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let WY=new Float32Array(1);new Uint8Array(WY.buffer);let HY=new Float64Array(1),KY=new Uint8Array(HY.buffer);function YY(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let qY=[];function zY(){const e=qY.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function XY(e){qY.push(e)}function JY(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function QY(e){return e.offset>=e.limit}function ZY(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function $Y(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function eq(e,t){let i=$Y(e,t),n=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function tq(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function iq(e,t){let i=ZY(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e>>=0;t>=128;)rq(e,127&t|128),t>>>=7;rq(e,t)}function dq(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=ZY(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}function lq(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const uq=new Map([["moderation",1],["supervise",2]]);class hq extends Dw{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit($U.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=Xn(t=e.map((e=>uq.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),QI(this,"name","AgoraRTCVideoContentInspect"),QI(this,"_connectionState",QU.CONNECTING),QI(this,"_innerConnectionState",void 0),QI(this,"sequence",0),QI(this,"inspectStartTime",void 0),QI(this,"workerManagerConnection",void 0),QI(this,"workerConnection",void 0),QI(this,"workerMessageLengthLimit",void 0),QI(this,"inspectIntervalMinimum",void 0),QI(this,"qualityRatio",void 0),QI(this,"_connectInfo",void 0),QI(this,"_cancelTokenSource",Ab.CancelToken.source()),QI(this,"_retryConfig",void 0),QI(this,"wmSequence",0),QI(this,"inspectInterval",void 0),QI(this,"inspectTimer",null),QI(this,"ossFilePrefix",void 0),QI(this,"extraInfo",void 0),QI(this,"_inspectType",void 0),QI(this,"_inspectMode",void 0),QI(this,"_quality",1),QI(this,"qualityTimer",null),QI(this,"_inspectId",void 0),QI(this,"_needWorkUrlOnly",!1),QI(this,"inspectImage",(()=>{if(this.connectionState!==QU.CONNECTED)throw new tD(Ew.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===QU.CONNECTED?this.requestToInspectImage():YN.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval{this._innerConnectionState=e,YN.debug("[".concat(this._inspectId,"] Inspect operation :").concat(ZU[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new yx("worker-"+this._inspectId,AO),this.handleWorkerEvents()}async init(e,t){this.emit($U.STATE_CHANGE,ZU.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Wh(((n,r)=>{this.on($U.CONNECTION_STATE_CHANGE,((e,t)=>{t===QU.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=_N("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;eF++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:eF,seq:eF,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return wO((async()=>{h=Date.now();const e=await PV(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new tD(Ew.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw YN.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new tD(Ew.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw YN.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new tD(Ew.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw YN.error(e.toString()),e}const n=_N("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=_N("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(eD.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(eD.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Ew.OPERATION_ABORTED&&t.code!==Ew.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit($U.STATE_CHANGE,ZU.AP_CONNECTED);const{addressList:o}=r;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit($U.STATE_CHANGE,ZU.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(mU.CONNECTED,(async()=>{this.emit($U.STATE_CHANGE,ZU.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.23.2",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(mU.CLOSED,(()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit($U.STATE_CHANGE,ZU.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw YN.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new tD(Ew.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw YN.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new tD(Ew.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=_N("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit($U.STATE_CHANGE,ZU.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit($U.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(mU.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(mU.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(mU.CONNECTED,(async()=>{this.emit($U.STATE_CHANGE,ZU.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=QU.CONNECTED})),this.workerConnection.on(mU.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=VY(new Uint8Array(e.data));if(_N("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&YN.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit($U.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=Xn(t=Object.keys(e)).call(t,((t,i)=>e[t]>e[i]?t:i),"porn"),r=Object.keys(e).find((e=>e===n));this.emit($U.INSPECT_RESULT,r)}else this.emit($U.INSPECT_RESULT,void 0,new tD(Ew.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit($U.INSPECT_RESULT,void 0,new tD(Ew.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else YN.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit($U.INSPECT_RESULT,void 0,new tD(Ew.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(mU.CLOSED,(()=>{this.connectionState=QU.CLOSED})),this.workerConnection.on(mU.FAILED,(()=>{this.connectionState=QU.CLOSED})),this.workerConnection.on(mU.RECONNECTING,(()=>{this.connectionState=this.connectionState===QU.CONNECTED?QU.RECONNECTING:QU.CONNECTING})),this.workerConnection.on(mU.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this.workerConnection.on(mU.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once($U.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=zw(this,$U.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit($U.INSPECT_RESULT,void 0,new tD(Ew.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit($U.INSPECT_RESULT,void 0,new tD(Ew.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await MP(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+hO(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:(p=Number(c-this.inspectStartTime),{low:p|=0,high:p>>31,unsigned:p>=0}),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.23.2",sequence:this.sequence,sid:s,timestamp:Gj(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var p;void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const _=xY(h);if(_.byteLength{var t;if(!Dn(t=["supervise","moderation"]).call(t,e))throw new tD(Ew.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new tD(Ew.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new hq(t)}};var _q=i(ie.Object.getOwnPropertySymbols),Eq=wi,mq=qi.indexOf,fq=Bn,Tq=I([].indexOf),Sq=!!Tq&&1/Tq([1],1,-0)<0;Eq({target:"Array",proto:!0,forced:Sq||!fq("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return Sq?Tq(this,e,t)||0:mq(this,e,t)}});var gq=Ji("Array").indexOf,Rq=l,vq=gq,Cq=Array.prototype,Iq=function(e){var t=e.indexOf;return e===Cq||Rq(Cq,e)&&t===Cq.indexOf?vq:t},yq=i(Iq);function Aq(e,t){if(null==e)return{};var i,n,r=function(e,t){if(null==e)return{};var i,n,r={},o=MM(e);for(n=0;n=0||(r[i]=e[i]);return r}(e,t);if(_q){var o=_q(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}let bq=class{get localCapabilities(){return eO(this._localCapabilities)}get rtpCapabilities(){return eO(this._rtpCapabilities)}get candidates(){return eO(this._candidates)}get iceParameters(){return eO(this._iceParameters)}get dtlsParameters(){return eO(this._dtlsParameters)}constructor(e){QI(this,"sessionDesc",void 0),QI(this,"_localCapabilities",void 0),QI(this,"_rtpCapabilities",void 0),QI(this,"_candidates",void 0),QI(this,"_iceParameters",void 0),QI(this,"_dtlsParameters",void 0),QI(this,"setup",void 0),QI(this,"currentMidIndex",void 0),QI(this,"cname","o/i14u9pJrxRKAsu"),QI(this,"firefoxSsrcMidMap",new Map),e=eO(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=s===EU.RECEIVE_ONLY?yN("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):yN("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o;const u=s===EU.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=s===EU.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===EU.RECEIVE_ONLY?r.send.videoCodecs:uV(HU.VIDEO,u,h,c),_=s===EU.RECEIVE_ONLY?r.send.audioCodecs:uV(HU.AUDIO,u,h,d);for(const e of l.mediaDescriptions)e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=p.map((e=>e.payloadType.toString(10))),e.attributes.payloads=p,e.attributes.extmaps=u.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,lV(e));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return AN(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=$x(t,this.cname,_N("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(Kb()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o,n);let i;return-1===t?(i=this.createOrRecycleSendMedia(e,o,s,"sendonly",n,r),this.updateBundleMids()):(i=eO(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),Kb()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,i){const n=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(r);let s,a=!1;-1===o?(a=!0,s=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(s=eO(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction="recvonly"),n.push({mid:s.attributes.mid,needCreateTransceiver:a})})),n}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=i?i:"",priority:c?c+"":"",connectionAddress:null!=n?n:"",port:r?r+"":"",type:o?o+"":"",relAddr:null!=s?s:"",relPort:a?a+"":"",extension:{}};this.candidates.some((e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port))||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,n,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=uV(o,s,this.localCapabilities.send,o===HU.AUDIO?r:n),c=o===HU.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(o);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const r=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(Kb()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i}))}predictReceivingMids(e){const t=[];for(let i=0;i{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,r,o){const s=this.rtpCapabilities.send,a=e===HU.VIDEO?s.videoCodecs:s.audioCodecs,c=e===HU.VIDEO?s.videoExtensions:s.audioExtensions;Kb()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){const n=eO(e);return tV(n),eV(n,t),iV(n,t),nV(n),rV(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=eO(e);return rV(i,t,this.localCapabilities.recv),lV(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Kb()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const wq=["sdp"];var Oq;function Nq(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Dq(e){for(var t=1;t2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(cV(t,e,"videoExtensions",i,n,r),cV(t,e,"videoCodecs",i,n,r),cV(t,e,"audioExtensions",i,n,r),cV(t,e,"audioCodecs",i,n,r),_N("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:r}}({},{},t);this.remoteSDP=new bq({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const o=Xx(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await aV({},{},r.sdp);this.localCapabilities=dV(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Dq(Dq({},o),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Xx(e.sdp);return this.initialOffer=e,Dq(Dq({},t),{},{sdp:e.sdp})}}catch(e){throw new mw(Ew.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await aV({},{},t);this.remoteSDP=new bq({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new mw(Ew.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return FA((function*(){const r=yield BA(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=n.remoteSDP.receive(e,t,i);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const i=n.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(s[t].mid));o.push(i),e._updateRtpTransceiver(i)}})),Kb()&&!0===_N("SIMULCAST")&&(yield BA(n.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield BA(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=yN(d),u=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Jx(t,_N("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}));yield BA(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=n.remoteSDP.toString();throw yield BA(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield BA(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield BA(n.stopSending(a,!0)),e}yield BA(n.applySimulcastEncodings(o,e)),yield BA(n.applySendEncodings(o,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield BA(n.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i}}))}catch(e){throw e instanceof mw?e:new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),YN.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else YN.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s||null===s.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,mid:s.mid,transceiver:s}}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),YN.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else YN.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===sN.Auto&&(this.store.p2pTransport=sN.SdRtn,nD().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,nD().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:t}=Xx(e.sdp);return this.store.descriptionStart(),this.direction===EU.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===EU.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:t}=Xx(e.sdp);return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new mw(Ew.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)?Kb()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:Dq(Dq({},FO),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Dq(Dq({},FO),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Dn(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else YN.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var o;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Fw(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),_N("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),Dn(o=[sN.Relay,sN.SdRtn]).call(o,i)&&(r.iceTransportPolicy="relay"),_N("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return _N("ENABLE_ENCODED_TRANSFORM")&&nD().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),YN.debug("P2PConnection p2pTransport is ".concat(i)),r}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter((e=>e.tcpport));YN.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const o=r.length>i?r[i]:r[0];switch(t){case sN.SdRtn:const t=e.filter((e=>{var t;return Dn(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL})),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(Dx(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(Dx(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case sN.Relay:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Dx(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Dx(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return n}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();YN.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})," )"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return YN.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return YN.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!nD().supportSetRtpSenderParameters)return YN.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(e._encoderConfig){var o;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Dn(o=e._hints).call(o,vD.LOW_STREAM)&&(i&&(r.maxFramerate=Lx(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(_N("DSCP_TYPE")&&dw()){var s;const e=_N("DSCP_TYPE");Dn(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];Kb()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),YN.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!nD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(eV(o,e),oV(o,e,this.store.codec))})),AN(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Kb()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(_N("SDP_LOGGING"))return YN.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async e=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=yN(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Dn(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){const n=yN(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===HU.AUDIO&&"audio"===r.media.mediaType&&lV(r),AN(n)}},rU(Oq.prototype,"establish",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"establish"),Oq.prototype),rU(Oq.prototype,"connect",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"connect"),Oq.prototype),rU(Oq.prototype,"receive",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"receive"),Oq.prototype),rU(Oq.prototype,"mockReceive",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"mockReceive"),Oq.prototype),rU(Oq.prototype,"stopReceiving",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"stopReceiving"),Oq.prototype),rU(Oq.prototype,"restartICE",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"restartICE"),Oq.prototype),rU(Oq.prototype,"close",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"close"),Oq.prototype),rU(Oq.prototype,"updateEncoderConfig",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"updateEncoderConfig"),Oq.prototype),rU(Oq.prototype,"updateSendParameters",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"updateSendParameters"),Oq.prototype),rU(Oq.prototype,"replaceTrack",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"replaceTrack"),Oq.prototype),rU(Oq.prototype,"muteLocal",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"muteLocal"),Oq.prototype),rU(Oq.prototype,"unmuteLocal",[Lq],Object.getOwnPropertyDescriptor(Oq.prototype,"unmuteLocal"),Oq.prototype),Oq);function Lq(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==XU.Connected)return void i(new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const s=this.filterTobeMutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>"videoLowTrack"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(s.map((e=>{let[,{id:t}]=e;return t})));let c=!1;var r,o;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(zU.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(zU.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await qw(this,JU.RequestMuteLocal,d);const l="video"===e.trackMediaType?ax.MUTE_LOCAL_VIDEO:ax.MUTE_LOCAL_AUDIO;await qw(this,JU.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}})),QI(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==XU.Connected)return void i(new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnmuteMessage(r),s="video"===e.trackMediaType?ax.UNMUTE_LOCAL_VIDEO:ax.UNMUTE_LOCAL_AUDIO;await qw(this,JU.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){i(e)}finally{n()}})),QI(this,"handleUpdateVideoEncoder",(async(e,t,i,n)=>{let r;"boolean"==typeof n&&n||(r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(zU.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==XU.Connected)return void t();const{id:n,track:s}=i;n&&(await this.sendConnection.updateSendParameters(n,s),await this.sendConnection.updateEncoderConfig(n,s),this.emit(JU.UpdateVideoEncoder,s)),t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),QI(this,"handleUpdateVideoSendParameters",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(zU.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==XU.Connected)return void t();const{id:r,track:o}=i;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),QI(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;YN.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==XU.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),i[0]===zU.LocalVideoTrack&&nD().supportDualStreamEncoding){const t=this.localTrackMap.get(zU.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Wh(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),QI(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),QI(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),QI(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),QI(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new SB(e),this.bindStatsUploaderEvents(),this.sendMutex=new IO("P2PChannel2-send-mutex",e.clientId),this.recvMutex=new IO("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),_N("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(YN.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Pq(e,this.store,EU.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=XU.New,this.sendConnection&&(YN.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Pq(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new mw(Ew.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=XU.Connected}async addRemoteCandidate(e,t){if(t===EU.RECEIVE_ONLY){if(!this.sendConnection)throw new mw(Ew.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new mw(Ew.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return FA((function*(){const r=yield BA(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==XU.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,TF.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield BA(n.tryToUnmuteAudio(e)));o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===zU.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(o);const s=yield BA(n.sendConnection.send(o.map((e=>{let{track:t}=e;return t})),n.store.codec,n.store.audioCodec)),a=(yield BA(s.next())).value,c=n.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===Ew.WS_ABORT&&o.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(o),e}yield BA(s.next()),o.forEach((e=>{let{type:t}=e;n.statsCollector.addLocalStats(t)})),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(o,a),o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===zU.LocalAudioTrack?"audio":"video",void 0,r)})),n.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==XU.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Dn(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===XU.Connected){if(i){i[1].track.close()}return n}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((i=>{let[n,{track:r,ssrcs:o}]=i;const s={stream_type:GF(r,n),ssrcs:o};r._muted||!r._enabled?e.push(s):t.push(s)})),e.length>0&&e.forEach((e=>{qw(this,JU.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{qw(this,JU.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return FA((function*(){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(YN.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Yw(this,JU.RequestRePublish,this.pendingLocalTracks),this.emit(JU.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new mw(Ew.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:o,mid:s,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===HU.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Nk(o,e.uid,e._uintid,this.store),YN.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new Ok(o,e.uid,e._uintid,this.store),YN.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,s):this.remoteUserMap.set(e,new Map([[t,s]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(JU.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new mw(Ew.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n)}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===HU.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===HU.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===HU.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===HU.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===HU.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),r.forEach((e=>{let[,{kind:t}]=e;qw(this,JU.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[HU.VIDEO,HU.AUDIO].forEach((e=>{t.has(e)?qw(this,JU.RequestP2PUnmuteRemote,e):qw(this,JU.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new mw(Ew.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void YN.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void YN.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===HU.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void YN.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||YN.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(zU.LocalAudioTrack);if((null==t?void 0:t.track)instanceof bL){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==zU.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===zU.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===zU.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(zU.LocalAudioTrack),o=n?this.localTrackMap.get(zU.LocalVideoLowTrack):this.localTrackMap.get(zU.LocalVideoTrack);eD.publish(this.store.sessionId,{eventElapse:TF.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(vD.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 IL)),a=n?null===(o=this.localTrackMap.get(zU.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof pk));eD.publish(this.store.sessionId,{eventElapse:TF.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(vD.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===HU.VIDEO?i._videoSSRC:i._audioSSRC;r&&eD.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===HU.VIDEO,audio:n===HU.AUDIO,peerid:i.uid,subscribeRequestid:n===HU.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:TF.measureFromSubscribeStart(this.store.clientId,r)})}reset(){YN.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new IO("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new IO("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(zU.LocalAudioTrack);if((null==e?void 0:e.track)instanceof bL){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=XU.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(zU.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(zU.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 pk||t&&t.track instanceof IL?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(MN(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(zU.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=vS(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(YN.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=XU.Reconnecting,_N("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case zU.LocalVideoTrack:Dn(t=n._hints).call(t,vD.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case zU.LocalAudioTrack:n instanceof bL?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case zU.LocalVideoLowTrack:}})),this.emit(JU.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(MN(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(JU.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),YN.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof IF?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,n;if(e===EU.SEND_ONLY){if(!this.sendConnection)throw new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection}else{if(!this.recvConnection)throw new mw(Ew.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e}{const e=await n.restartICE();if(e){const t=await Yw(this,JU.RequestP2PRestartICE,{direction:EU.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(zU.LocalVideoTrack),i=this.localTrackMap.get(zU.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!r)return 1;const o=zw(this,JU.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(vD.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return fM[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=zw(this,JU.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Wh(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=nD(),o=this.getAllTracks();e=Zw(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof pk&&(this.localTrackMap.has(zU.LocalVideoTrack)||s?new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:zU.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:zU.LocalVideoLowTrack})}if(o instanceof IL){const e=this.localTrackMap.get(zU.LocalAudioTrack);if(e){if(!(e.track instanceof bL))throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===zU.LocalAudioTrack}));if(!(e.track instanceof bL))throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof bL||o._bypassWebAudio)n.push({track:o,type:zU.LocalAudioTrack});else{const e=new bL;e.addAudioTrack(o),n.push({track:e,type:zU.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=Zw(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof IL){const e=this.localTrackMap.get(zU.LocalAudioTrack);if(!e)continue;e.track instanceof bL?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([zU.LocalAudioTrack,e]),e.track.close())):t.push([zU.LocalAudioTrack,e])}if(i instanceof pk){const e=this.localTrackMap.get(zU.LocalVideoTrack);if(!e)continue;t.push([zU.LocalVideoTrack,e]);const i=this.localTrackMap.get(zU.LocalVideoLowTrack);i&&t.push([zU.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case zU.LocalVideoTrack:t.addListener(RD.GET_STATS,this.handleGetLocalVideoStats),t.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(RD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(RD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case zU.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case zU.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof bL?e.trackList.forEach((e=>{e.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(RD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(RD.GET_STATS,this.handleGetLocalAudioStats),e.addListener(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case zU.LocalVideoTrack:t.off(RD.GET_STATS,this.handleGetLocalVideoStats),t.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(RD.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(RD.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case zU.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case zU.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof bL?e.trackList.forEach((e=>{e.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(RD.GET_STATS,this.handleGetLocalAudioStats),e.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(RD.GET_STATS,this.handleGetLocalAudioStats),e.off(RD.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(RD.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(RD.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(RD.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Ok&&t.addListener(RD.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Nk&&t.addListener(RD.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(RD.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(HU.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(HU.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,{track:o,type:s}=e;switch(s){case zU.LocalAudioTrack:r=PU.Audio;break;case zU.LocalVideoTrack:r=Dn(n=o._hints).call(n,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:r=PU.Low}return{kind:s===zU.LocalAudioTrack?HU.AUDIO:HU.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(JU.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),Dn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&await uO(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eD.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Mw.TRACER}).onSuccess(),this.emit(JU.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(MN(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(wD.FIRST_FRAME_DECODED),eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_AUDIO_DECODE,QN.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(MN(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_AUDIO_RECEIVED,QN.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(MN(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&eD.firstRemoteFrame(this.store.sessionId,JN.FIRST_VIDEO_RECEIVED,QN.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(JU.ConnectionTypeChange,i),YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Fx(t))," -> ").concat(JSON.stringify(Fx(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{YN.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Fx(t))," -> ").concat(JSON.stringify(Fx(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(JU.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===EU.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,YN.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===EU.SEND_ONLY?this.restartICE(e):Yw(this,JU.RequestP2PRestartICE,{direction:EU.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(zU.LocalAudioTrack);if(e instanceof IL&&(null==i?void 0:i.track)instanceof bL)return i.track.isActive||t.push([zU.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===zU.LocalVideoTrack)){const e=this.localTrackMap.get(zU.LocalVideoLowTrack);e&&t.push([zU.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(zU.LocalAudioTrack);if(e instanceof IL&&(null==i?void 0:i.track)instanceof bL)return i.track.isActive&&t.push([zU.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===zU.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(zU.LocalVideoLowTrack);e&&t.push([zU.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case zU.LocalAudioTrack:i=PU.Audio;break;case zU.LocalVideoTrack:i=Dn(t=r._hints).call(t,vD.SCREEN_TRACK)?PU.Screen:PU.High;break;case zU.LocalVideoLowTrack:i=PU.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case HU.VIDEO:return void(i._videoSSRC&&t.push({stream_type:HU.VIDEO,ssrcId:i._videoSSRC}));case HU.AUDIO:return void(i._audioSSRC&&t.push({stream_type:HU.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(zU.LocalVideoTrack),i=this.localTrackMap.get(zU.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Wh(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Wh(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;tthis.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>{let[,{ssrcs:t}]=e;return!!t})),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(JU.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(JU.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await uO(bO(this.dtlsFailedCount,AO)),this.emit(JU.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(zU.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof pk))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof pk)).length>1)throw new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof IL)).length>1&&(e.some((e=>e instanceof IL&&e._bypassWebAudio))||!nD().webAudioMediaStreamDest))throw new mw(Ew.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 pk&&this.pendingLocalTracks.some((e=>e instanceof pk)))throw new mw(Ew.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof IL&&this.pendingLocalTracks.some((e=>e instanceof IL))&&(!nD().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof IL&&e._bypassWebAudio))))throw new mw(Ew.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!_N("DISABLE_DUAL_STREAM_USE_ENCODING")&&nD().supportDualStreamEncoding,n=zq(zq({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():eB(e,n);const o=hO(8,"track-low-"),s=new pk(r,zq(zq({},i&&{scaleResolutionDownBy:Vx(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(AD.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,CD.LOW_STREAM)})),s._hints.push(vD.LOW_STREAM),e.addListener(RD.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(MN(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));eD.firstRemoteVideoDecode(this.store.sessionId,JN.FIRST_VIDEO_DECODE,QN.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:TF.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==i}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new mw(Ew.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new mw(Ew.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new mw(Ew.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new mw(Ew.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new mw(Ew.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new mw(Ew.NOT_SUPPORTED)}async preConnect(e){throw new mw(Ew.NOT_SUPPORTED)}getEstablishParams(){throw new mw(Ew.NOT_SUPPORTED)}async reSubscribe(e){throw new mw(Ew.NOT_SUPPORTED)}async updateVideoStreamParameter(e,t){throw new mw(Ew.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===zU.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,CD.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},rU(Yq.prototype,"p2pConnect",[Mq],Object.getOwnPropertyDescriptor(Yq.prototype,"p2pConnect"),Yq.prototype),rU(Yq.prototype,"unpublish",[Uq],Object.getOwnPropertyDescriptor(Yq.prototype,"unpublish"),Yq.prototype),rU(Yq.prototype,"unpublishLowStream",[xq],Object.getOwnPropertyDescriptor(Yq.prototype,"unpublishLowStream"),Yq.prototype),rU(Yq.prototype,"subscribe",[Vq],Object.getOwnPropertyDescriptor(Yq.prototype,"subscribe"),Yq.prototype),rU(Yq.prototype,"mockSubscribe",[Fq],Object.getOwnPropertyDescriptor(Yq.prototype,"mockSubscribe"),Yq.prototype),rU(Yq.prototype,"unsubscribe",[Bq],Object.getOwnPropertyDescriptor(Yq.prototype,"unsubscribe"),Yq.prototype),rU(Yq.prototype,"muteRemote",[jq],Object.getOwnPropertyDescriptor(Yq.prototype,"muteRemote"),Yq.prototype),rU(Yq.prototype,"unmuteRemote",[Gq],Object.getOwnPropertyDescriptor(Yq.prototype,"unmuteRemote"),Yq.prototype),rU(Yq.prototype,"hasRemoteMediaWithLock",[Wq],Object.getOwnPropertyDescriptor(Yq.prototype,"hasRemoteMediaWithLock"),Yq.prototype),rU(Yq.prototype,"disconnectForReconnect",[Hq],Object.getOwnPropertyDescriptor(Yq.prototype,"disconnectForReconnect"),Yq.prototype),rU(Yq.prototype,"remoteMediaSsrcChanged",[Kq],Object.getOwnPropertyDescriptor(Yq.prototype,"remoteMediaSsrcChanged"),Yq.prototype),Yq);function Jq(e){return function(t,i,n){const r=t[i];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),o=0;o{this.signal.connectionState===lU.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*_N("P2P_TOKEN_INTERVAL"))};i()}async send(e,t,i,n,r){var o,s,a;if(0===this.userMap.size)return;const c=Array.from(Zh(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(s=n)&&void 0!==s?s:hO(6,""),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:n,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(c)};_N("SHOW_P2P_LOG")&&YN.debug("send message",d,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(d)).forEach((e=>{this.signal.request(hU.DATA_STREAM,{payload:oO(this.encoder.encode(e))})}));const l=new Wh(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),this.off(sx.ABORT,a),YN.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?r(new mw(Ew.INVALID_REMOTE_USER)):r(new mw(Ew.TIMEOUT))}),_N("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off(sx.ABORT,a),i&&t()},a=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),s),this.off("res-@".concat(n),c),r(new mw(Ew.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)))};this.once(sx.ABORT,a),this.once("res-@".concat(n,"_ack"),s);const c=(i,c)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),s),this.off(sx.ABORT,a),"success"===i?t(c):r(new mw(Ew.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)))};let l=!1;i||(this.once("res-@".concat(n),c),uO(_N("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||YN.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(d))})))}));try{return await l}catch(o){if(o.code===Ew.TIMEOUT)return await this.send(e,t,i,n,r);throw o}}onMessage(e){var t;const{_uid:i}=e;let n,r=this.userMap.get(i);if(r)n=r.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==ox.CHECK)return;const{token:t}=e;n=new Map,r={uid:i,isStart:!0,token:t,splitMessageMap:n,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(i,r),this.signal.emit(_U.ON_USER_ONLINE,{uid:i}),this.handleUserOnline()}if("id"in e&&"total"in e){var o;const{id:t,total:r}=e,s=null!==(o=n.get(t))&&void 0!==o?o:[];if(s.push(e),n.has(t)||n.set(t,s),s.length!==r)return;{const r=vS(s).call(s,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");n.delete(t),(e=JSON.parse(r))._uid=i}}const{_type:s,token:a}=e;if(Dn(t=[ox.ACK,ox.CHECK]).call(t,s))return s===ox.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):YN.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:hO(6,""),token:this.token,_type:ox.CHECK};_N("SHOW_P2P_LOG")&&YN.debug("send message",e),this.signal.request(hU.DATA_STREAM,{payload:oO(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:ox.ACK,token:this.token};_N("SHOW_P2P_LOG")&&YN.debug("send message",t),this.signal.request(hU.DATA_STREAM,{payload:oO(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(ox.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this.userMap.get(i),{receivedMessagesMap:o,isStart:s,nextExpectedSequenceNumber:a}=r;if(n{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case ox.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case ox.RESPONSE:{const{success:e,message:i}=o;this.emit("res-@".concat(t),e?"success":"failed",i);break}}}}splitMessage(e){if(e.length0;){r++;const a={id:n,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(i)};JSON.stringify(a).length>Qq.MAX_MESSAGE_SIZE?o-=50:(t.push(a),e=e.slice(o))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(YN.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{YN.debug("token timeout, ".concat(t)),this.reset(e.uid)}),_N("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await Yw(this.signal,ox.CALL,void 0),t=await this.send(ox.CALL,e);this.signal.emit(uU.P2P_CONNECTION,t,!0)}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(sx.ABORT),this.signal.emit(_U.ON_USER_OFFLINE,{uid:i.uid,reason:cx.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(YN.debug("change local token from ".concat(t," to ").concat(t)),this.token=hO(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(sx.ABORT)}}QI(Qq,"MAX_SIZE",1),QI(Qq,"MAX_MESSAGE_SIZE",1024);class Zq extends Dw{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===lU.CONNECTED?this.emit(uU.WS_CONNECTED):e===lU.RECONNECTING?this.emit(uU.WS_RECONNECTING,this._websocketReconnectReason):e===lU.CLOSED&&this.emit(uU.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),QI(this,"_disconnectedReason",void 0),QI(this,"_websocketReconnectReason",void 0),QI(this,"_connectionState",lU.CLOSED),QI(this,"reconnectToken",void 0),QI(this,"p2pToken",void 0),QI(this,"websocket",void 0),QI(this,"openConnectionTime",void 0),QI(this,"clientId",void 0),QI(this,"lastMsgTime",Date.now()),QI(this,"uploadCache",[]),QI(this,"uploadCacheInterval",void 0),QI(this,"rttRolling",new NO(5)),QI(this,"pingpongTimer",void 0),QI(this,"pingpongTimeoutCount",0),QI(this,"joinResponse",void 0),QI(this,"multiIpOption",void 0),QI(this,"initError",void 0),QI(this,"spec",void 0),QI(this,"store",void 0),QI(this,"_external_signal",void 0),QI(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(uU.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case _U.ON_DATA_STREAM:return void this.handleDataStream(t._message);case _U.MUTE_AUDIO:case _U.MUTE_VIDEO:case _U.ON_P2P_LOST:case _U.ON_USER_ONLINE:return;case _U.ON_USER_OFFLINE:const{uid:e}=t._message;return YN.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===_U.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===_U.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(Vw.UID_BANNED);break;case 15:this.close(Vw.IP_BANNED);break;case 16:this.close(Vw.CHANNEL_BANNED)}if(t._type===_U.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case dU.ERR_LICENSE_MISSING:this.close(Vw.LICENSE_MISSING);break;case dU.ERR_LICENSE_EXPIRED:this.close(Vw.LICENSE_EXPIRED);break;case dU.ERR_LICENSE_MINUTES_EXCEEDED:this.close(Vw.LICENSE_MINUTES_EXCEEDED);break;case dU.ERR_LICENSE_PERIOD_INVALID:this.close(Vw.LICENSE_PERIOD_INVALID);break;case dU.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(Vw.LICENSE_MULTIPLE_SDK_SERVICE);break;case dU.ERR_LICENSE_ILLEGAL:this.close(Vw.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Ix("gateway-".concat(this.clientId),this.spec.retryConfig,!0,_N("JOIN_GATEWAY_USE_DUAL_DOMAIN"),_N("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===lU.CONNECTED&&this.reconnect("retry",Ww.OFFLINE)})),this.p2pToken=hO(6,""),this._external_signal=new Qq(this,this.p2pToken)}async request(e,t,i,n){const r=hO(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Wh(((e,t)=>{if(this.connectionState===lU.CONNECTED)return e();const i=()=>{this.off(uU.WS_CLOSED,n),e()},n=()=>{this.off(uU.WS_CONNECTED,i),t(new mw(Ew.WS_ABORT))};this.once(uU.WS_CONNECTED,i),this.once(uU.WS_CLOSED,n)}));if(this.connectionState!==lU.CONNECTING&&this.connectionState!==lU.RECONNECTING||e===hU.JOIN||e===hU.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Wh(((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(uU.WS_CLOSED,c),this.off(uU.WS_RECONNECTING,c),this.emit(uU.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new mw(Ew.WS_ABORT,"type: ".concat(e))),this.off(uU.WS_CLOSED,c),this.off(uU.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(uU.WS_CLOSED,c),this.once(uU.WS_RECONNECTING,c),uO(_N("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(YN.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(uU.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===lU.CLOSED||e===hU.LEAVE)throw new mw(Ew.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===hU.JOIN||e===hU.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=hx(l),h=new mw(Ew.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(YN.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===dU.ERR_TOO_MANY_BROADCASTERS?e===hU.JOIN||e===hU.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===dU.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,YN.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ww.MULTI_IP)):this.reconnect(u.action,Ww.SERVER_ERROR),e===hU.JOIN||e===hU.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Wh((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void YN.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(pU.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=_N("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!==lU.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)}),_N("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Wh(((t,i)=>{this.once(uU.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(uU.WS_CLOSED,(()=>i(this.initError||new mw(Ew.WS_ABORT)))),this.connectionState=lU.CONNECTING,this.websocket.init(e).catch(i)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||Vw.LEAVE,this.connectionState=lU.CLOSED,YN.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=hO(6,""),this._external_signal.clear(),this._external_signal=new Qq(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(uU.ABORT_P2P_EXECUTION);const e=await Yw(this,uU.REQUEST_JOIN_INFO),t=await this.request(hU.JOIN,e);if(!t)return this.emit(uU.REPORT_JOIN_GATEWAY,Ew.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(uU.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=lU.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleDataStream(e){try{var t;const i=rO(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);"total"in r&&"id"in r||Dn(t=Object.values(ox)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(_U.ON_DATA_STREAM,e)}catch(t){this.emit(_U.ON_DATA_STREAM,e)}}handleNotification(e){YN.debug("[".concat(this.clientId,"] receive notification: "),e);const t=hx(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(Vw.UID_BANNED),void this.close()):void this.reconnect(t.action,Ww.SERVER_ERROR);YN.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=_N("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(YN.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>_N("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ww.TIMEOUT):this.request(hU.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),_N("REPORT_STATS")&&this.send(hU.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(mU.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(uU.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(mU.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(mU.CLOSED,(()=>{this.connectionState=lU.CLOSED})),this.websocket.on(mU.FAILED,(()=>{this._disconnectedReason=Vw.NETWORK_ERROR,this.connectionState=lU.CLOSED})),this.websocket.on(mU.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===lU.CONNECTED?this.connectionState=lU.RECONNECTING:this.connectionState=lU.CONNECTING})),this.websocket.on(mU.WILL_RECONNECT,((e,t,i)=>{"retry"!==e?(YN.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):YN.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e)})),this.websocket.on(mU.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(uU.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof mw&&e.code===Ew.UNEXPECTED_RESPONSE&&e.data.code===dU.ERR_NO_AUTHORIZED)return YN.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Ww.SERVER_ERROR);YN.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ww.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(mU.REQUEST_NEW_URLS,((e,t)=>{Yw(this,uU.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(mU.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(_U.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const $q={name:"P2PChannel",create:function(e){let{store:t,statsCollector:i}=e;return new Xq(t,i)},createSubmodule:function(e){let{store:t,spec:i}=e;return new Zq(i,t)}};function ez(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 tz(e){for(var t=1;te.payloadType.toString(10)));let e=r.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,a)}));0===e.length&&(e=r.videoCodecs),s.attributes.payloads=e,s.attributes.extmaps=r.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),s.attributes.payloads=r.audioCodecs,s.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return AN(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=$x(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===HU.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(r),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{Dn(e).call(e,t.attributes.label||"")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Dn(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(tz(tz({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case KU.TCP_RELAY:this.candidates=i;break;case KU.UDP_TCP_RELAY:case KU.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=eO(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;it.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===HU.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=eO(e);return tV(t),function(e){const t=e.attributes.extmaps.find((e=>Kx(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 nz;function rz(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 oz(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Dn(t=Object.keys(TN)).call(t,e)})))]}constructor(t,i){super(t,i),QI(this,"store",void 0),QI(this,"peerConnection",void 0),QI(this,"remoteSDP",void 0),QI(this,"initialOffer",void 0),QI(this,"statsFilter",void 0),QI(this,"useRTX",!1),QI(this,"localCapabilities",void 0),QI(this,"localCandidateCount",0),QI(this,"allCandidatesReceived",!1),QI(this,"establishPromise",void 0),QI(this,"mutex",void 0),this.store=i,this.mutex=new IO("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=tN(this.peerConnection,_N("STATS_UPDATE_INTERVAL"),void 0,Kb()?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=Xx(e.sdp),i=zx(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:_N("FILTER_VIDEO_FEC"),filterAudioFec:_N("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,oz(oz({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new mw(Ew.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 iz(oz(oz({},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 mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new mw(Ew.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var i=this;return FA((function*(){const n=yield BA(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 BA(i.peerConnection.createOffer()),s=yN(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=>{Wb()&&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 BA(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield BA(i.applySendEncodings(r,e)),yield BA(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 mw(Ew.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=>{Wb()&&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 mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),o=new Wh(((t,n)=>{const o=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=n=>{const a=xb();if(("Safari"===a.name&&11===Number(a.version)||Yb())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener("track",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:i}}catch(e){throw new mw(Ew.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 mw(Ew.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(Wb()&&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 mw(Ew.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(Wb()&&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 mw(Ew.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return FA((function*(){const i=yield BA(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=nD().supportPCSetConfiguration;if(e===KU.RELAY&&!n)return;if(n){const i=t.peerConnection.getConfiguration(),n=e===KU.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(YN.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}e!==KU.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield BA(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=Xx(r.sdp),{remoteIceParameters:s}=yield o.iceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield BA(t.peerConnection.setLocalDescription(r)),yield BA(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){YN.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 mw(Ew.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 mw(Ew.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new mw(Ew.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,YN.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,YN.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),_N("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&&(Fw(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),_N("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 YN.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!nD().supportSetRtpSenderParameters)return YN.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof pk)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(_N("DSCP_TYPE")&&dw()){var o;const e=_N("DSCP_TYPE");Dn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(s,n),YN.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!nD().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&eV(r,e)})),AN(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let{id:n,mslabel:r}=t;const{kind:o}=e[i];return new Wh(((e,t)=>{const i=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=xb();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Wh.all(t)}catch(e){throw new mw(Ew.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(nD().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},rU(nz.prototype,"connect",[az],Object.getOwnPropertyDescriptor(nz.prototype,"connect"),nz.prototype),rU(nz.prototype,"stopSending",[az],Object.getOwnPropertyDescriptor(nz.prototype,"stopSending"),nz.prototype),rU(nz.prototype,"receive",[az],Object.getOwnPropertyDescriptor(nz.prototype,"receive"),nz.prototype),rU(nz.prototype,"stopReceiving",[az],Object.getOwnPropertyDescriptor(nz.prototype,"stopReceiving"),nz.prototype),rU(nz.prototype,"muteRemote",[az],Object.getOwnPropertyDescriptor(nz.prototype,"muteRemote"),nz.prototype),rU(nz.prototype,"unmuteRemote",[az],Object.getOwnPropertyDescriptor(nz.prototype,"unmuteRemote"),nz.prototype),rU(nz.prototype,"muteLocal",[az],Object.getOwnPropertyDescriptor(nz.prototype,"muteLocal"),nz.prototype),rU(nz.prototype,"unmuteLocal",[az],Object.getOwnPropertyDescriptor(nz.prototype,"unmuteLocal"),nz.prototype),rU(nz.prototype,"close",[az],Object.getOwnPropertyDescriptor(nz.prototype,"close"),nz.prototype),rU(nz.prototype,"updateEncoderConfig",[az],Object.getOwnPropertyDescriptor(nz.prototype,"updateEncoderConfig"),nz.prototype),rU(nz.prototype,"updateSendParameters",[az],Object.getOwnPropertyDescriptor(nz.prototype,"updateSendParameters"),nz.prototype),rU(nz.prototype,"replaceTrack",[az],Object.getOwnPropertyDescriptor(nz.prototype,"replaceTrack"),nz.prototype),rU(nz.prototype,"getRemoteSSRC",[az],Object.getOwnPropertyDescriptor(nz.prototype,"getRemoteSSRC"),nz.prototype),nz);function az(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;s1&&void 0!==arguments[1]?arguments[1]:{};if(!nD().supportWebRTCEncodedTransform)return void YN.warning("browser not support audio encoded transform");if(Wk.has(e))return;if(!e.track)return;const i={track:e.track};if(Gb()){if(!e.createEncodedStreams)return void YN.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void YN.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(YN.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const s=t.metadata&&t.metadata();s?function(e,t){const{chunk:i,controller:n}=t,r=_N("ENABLE_AUDIO_PTS_METADATA")?jk.AUDIO_64_BIT_PTS:jk.METADATA;i.data=function(e,t,i){const n=i.byteLength,r=n+Fk+Bk,o=xk+Vk+r,s=new ArrayBuffer(e.byteLength+o),a=new DataView(s);a.setUint8(0,Uk),a.setUint16(1,r),a.setUint8(3,t),a.setUint16(4,n);for(let e=0;er.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=s,await new Wh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var s;if(r.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id)YN.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n);else if(r.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},i.worker=r}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}const t=Wk.get(e);if(t){Wk.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){YN.warning(e&&e.message)}}}Wk.set(e,i),e.track.addEventListener("ended",n)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!nD().supportWebRTCEncodedTransform)return void YN.warning("browser not support audio encoded transform");if(uM.has(e))return;const i={track:e.track,onMetadata:t.onMetadata};if(Gb()){if(!e.createEncodedStreams)return void YN.warning("browser not support createEncodedStreams() API");Xb(Lb.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(e){return void YN.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(YN.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)),t.enableTopn?function(e,t,i){var n;const r=Gk(new DataView(t.data));if(!r)return i.enqueue(t);const o=e.track.id;hM.set(o,e.track);const s=null===(n=r.tlv.find((e=>e.tag===jk.AUDIO_LEVEL)))||void 0===n?void 0:n.value;let a=0;"number"==typeof s&&(a=127-s);const c=Math.round(Math.pow(10,a/60)-1),{selected:d,speaker:l}=function(e,t){let i=tM.get(e);if(i||(i=function(e){const t=new Qk;return tM.set(e,t),iM||(iM=new eM(_N("TOPN_SILENCE_THRESHOLD")||500),iM.on("ActiveSpeakerChanged",(e=>{null!=e&&(nM=e)}))),iM.addSpeakers([t]),t}(e)),tM.size<=rM)return{selected:!0,speaker:i};if(!iM)throw new Error("no active speaker detector");return iM.levelChanged(i.id,t),oM=iM.loudest.map((e=>e.id)),nM&&!Dn(oM).call(oM,nM)&&oM.length>=rM&&oM.pop(),{selected:Dn(oM).call(oM,i.id)||i.id===nM,speaker:i}}(e,c),u=function(e,t,i){const n=sM.get(e)||new cM(e,t);return n.score=i,sM.set(e,n),function(e){if(aM.set(e,!0),!dM)return void(dM=Date.now());const t=Date.now();t-dM>1e3&&(aM.get(e)?aM.set(e,!1):(lM(e),aM.delete(e)),dM=t)}(e),n}(o,e.track,l.energyScore);u.addSample(d),u.active&&(t.data=r.frame.buffer,i.enqueue(t))}(e,r,o):t.enableMetadata?function(e,t,i){const n=Gk(new DataView(e.data));if(!n)return t.enqueue(e);const r=n.tlv.find((e=>e.tag===jk.METADATA||e.tag===jk.AUDIO_64_BIT_PTS));r&&i&&r.value instanceof Uint8Array&&i(r.value),e.data=n.frame.buffer,t.enqueue(e)}(r,o,t.onMetadata):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(Wb()){if("undefined"==typeof RTCRtpScriptTransform)return void YN.warning("browser not support RTCRtpScriptTransform");const t=Mk(),r=new MessageChannel;await new Wh((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:r.port2},[r.port2]);e.transform=o,await new Wh((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(YN.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)):t.data.metadata&&i.onMetadata&&i.onMetadata(t.data.metadata)},i.worker=t}function n(){e.track.removeEventListener("ended",n),function(e){const t=uM.get(e);if(t){!function(e){const t=tM.get(e);t&&(tM.delete(e),iM&&(iM.removeSpeakers([t]),0===tM.size&&(iM.destroy(),iM=null)))}(e),lM(e.track.id),uM.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){YN.warning(e&&e.message)}}}(e)}uM.set(e,i),e.track.addEventListener("ended",n)},interceptLocalVideoFrame:async function(e,t){if(!nD().supportWebRTCEncodedTransform)return void YN.warning("browser not support video encoded transform");if(_M.has(e))return;if(!e.track)return;const i={track:e.track};if(Gb()){if(!e.createEncodedStreams)return void YN.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void YN.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const s=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(YN.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const s=o.shift();s&&(t.data=function(e,t){const i=function(e){const t=e.length;let i=[],n=0;for(;nr.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=s,await new Wh((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(YN.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n))},i.worker=r}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}const t=_M.get(e);if(t){_M.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){YN.warning(e&&e.message)}}}_M.set(e,i),e.track.addEventListener("ended",n)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!nD().supportWebRTCEncodedTransform)return void YN.warning("browser not support video encoded transform");if(!e.track)return;if(EM.has(e)){const i=EM.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(Gb()){if(!e.createEncodedStreams)return void YN.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams()}catch(e){return void YN.error("create video-encoded-streams error",e&&e.message)}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(YN.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const o=function(e){const t=new DataView(e.data);let i=0;for(;i+4t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"sei-rx",port:r.port2},[r.port2]);e.transform=o,await new Wh((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(YN.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n)}!function(e){const t=EM.get(e);if(t){EM.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){YN.warning(e&&e.message)}}}(e)}EM.set(e,i),e.track.addEventListener("ended",n)}},lz={name:"InterceptFrame",create:()=>dz};nN(),pN("PROCESS_ID","process-".concat(hO(8,""),"-").concat(hO(4,""),"-").concat(hO(4,""),"-").concat(hO(4,""),"-").concat(hO(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void YN.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();YN.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(hN,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;mN[e]=n,hN[e]=n}}))}catch(t){YN.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(mN.AREAS)&&mN.AREAS.length>0&&jV(mN.AREAS,!0);const uz=(e,t,i)=>{YN.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),pN(e,t,i)};vV(OY,!1),vV(UY,!1),vV(Yj,!1),vV(pq,!1),vV(AY,!1),vV($q,!1),vV(cz,!1),vV(lz,!1);const hz=function(e){const t=new Dw,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===tx.SECURITY_POLICY_VIOLATION&&YG(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 HG(HG({},i),n)}({__TRACK_LIST__:SD,VERSION:rN,BUILD:lN,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:uz,getParameter:_N,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return nD().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 tD(Ew.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=eD.reportApiInvoke(null,{name:kw.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:Mw.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n),t&&cw()&&zb(75)&&(new e).close()}catch(e){return YN.error("check system requirement failed: ",e),!1}let i=!1;const n=xb();n.name===Lb.CHROME&&Number(n.version)>=58&&("WebKit"!==Mb.engine.name||function(){const e=xb();if(jb()){if(e.os===Pb.MAC_OS)return!0;if(e.os===Pb.IOS){const e=Mb.os.version&&Mb.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}())&&(i=!0),(n.name===Lb.FIREFOX&&Number(n.version)>=56||n.name===Lb.OPERA&&Number(n.version)>=45||n.name===Lb.SAFARI&&Number(n.version)>=11||"WebKit"===n.name&&(Yb()||ow())&&n.osVersion&&Number(n.osVersion.split(".")[0])>=11||sw()||xb().name===Lb.QQ)&&(i=!0),YN.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return mP.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return mP.getRecordingDevices(e)},getCameras:function(e){return mP.getCamerasDevices(e)},getElectronScreenSources:cP,getPlaybackDevices:function(e){return mP.getSpeakers(e)},createClient:function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=hO(5,"client-"),n=eD.reportApiInvoke(null,{id:i,name:kw.CREATE_CLIENT,options:[t],tag:Mw.TRACER});try{!function(e){Tw(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),Tw(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&Tw(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Rw(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&Bw(e.turnServer),void 0!==e.httpRetryConfig&&Uw(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&Uw(e.websocketRetryConfig)}(t)}catch(e){throw n.onError(e),e}return(Zb(16,0,!0)||$b(16,0,!0))&&("vp9"===t.codec&&(t.codec="vp8",YN.debug("browser not support vp9, force use vp8")),pN("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),n.onSuccess(),new xG(UG(UG({forceWaitGatewayResponse:!0},t),{},{role:Dn(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}),i)},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=_N("CAMERA_CAPTURE_CONFIG"),i=hO(8,"track-cam-"),n=eD.reportApiInvoke(null,{id:i,tag:Mw.TRACER,name:kw.CREATE_CAM_VIDEO_TRACK,options:[KD({},e),t]});t&&(e.encoderConfig=t);const r=DP(e);let o=null;YN.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await hP({video:r},i)).getVideoTracks()[0]||null}catch(e){throw n.onError(e),e}if(!o){const e=new mw(Ew.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(YN)}e.optimizationMode&&Ek(i,o,e,_D(e.encoderConfig));const s=new _k(o,e,r,e.scalabiltyMode?mD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return n.onSuccess(s.getTrackId()),YN.info("create camera video success, trackId:",i),s},createCustomVideoTrack:function(e){const t=hO(8,"track-cus-"),i=eD.reportApiInvoke(null,{id:t,tag:Mw.TRACER,name:kw.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),n=new pk(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?mD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[vD.CUSTOM_TRACK]);return i.onSuccess(n.getTrackId()),YN.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){return PP(e)}(t):void 0;i&&(t="auto");const n=hO(8,"track-scr-v-"),r=eD.reportApiInvoke(null,{id:n,tag:Mw.TRACER,name:kw.CREATE_SCREEN_VIDEO_TRACK,options:[KD({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Gb()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:o,preferCurrentTab:s}=e;(qb(107)||Jb(107)||ew(93))&&(i&&(Tw(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(Tw(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(Tw(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(qb(105)||Jb(105)||ew(91))&&o&&(Tw(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(qb(94)||Jb(94)||ew(80))&&s&&(t.preferCurrentTab=!0),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const a=e.encoderConfig?ED(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:a?a.width:void 0,maxHeight:a?a.height:void 0},a&&(a.frameRate&&("number"==typeof a.frameRate?(t.mandatory.maxFrameRate=a.frameRate,t.mandatory.minFrameRate=a.frameRate):(t.mandatory.maxFrameRate=a.frameRate.max||a.frameRate.ideal||a.frameRate.exact||void 0,t.mandatory.minFrameRate=a.frameRate.min||a.frameRate.ideal||a.frameRate.exact||void 0),t.frameRate=a.frameRate),a.width&&(t.width=a.width),a.height&&(t.height=a.height)),t}(e);let s=null,a=null;const c=nD();if(!c.supportShareAudio&&"enable"===t){const e=new mw(Ew.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(YN)}YN.info("start create screen video track with config",e,"withAudio",t,"trackId",n);const d=c.supportShareAudio&&"disable"!==t;try{const e=await hP({screen:o,screenAudio:d?i||!0:void 0},n);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!s){const e=new mw(Ew.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(YN)}if(!a&&"enable"===t){s&&s.stop();const e=new mw(Ew.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(YN)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(Ek(n,s,e,e.encoderConfig&&ED(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new pk(s,e.encoderConfig?ED(e.encoderConfig):{},e.scalabiltyMode?mD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n,[vD.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),YN.info("create screen video track success","video:",l.getTrackId()),l;const u=new IL(a,void 0,hO(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),YN.info("create screen video track success","video:",l.getTrackId(),"audio:",u.getTrackId()),[l,u]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=_N("CAMERA_CAPTURE_CONFIG"),n=hO(8,"track-mic-"),r=hO(8,"track-cam-"),o=eD.reportApiInvoke(null,{id:"".concat(n,"-").concat(r),tag:Mw.TRACER,name:kw.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const s=DP(t),a=LP(e);let c=null,d=null;YN.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 hP({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 mw(Ew.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(YN)}t.optimizationMode&&Ek(r,d,t,_D(t.encoderConfig));const l=new yL(c,e,a,n),u=new _k(d,t,s,t.scalabiltyMode?mD(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),YN.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=hO(8,"track-mic-"),i=eD.reportApiInvoke(null,{id:t,tag:Mw.TRACER,name:kw.CREATE_MIC_AUDIO_TRACK,options:[e]}),n=LP(e);let r=null;YN.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await hP({audio:n},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!r){const e=new mw(Ew.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(YN)}const o=new yL(r,e,n,t);return i.onSuccess(o.getTrackId()),YN.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:function(e){const t=hO(8,"track-cus-"),i=eD.reportApiInvoke(null,{id:t,tag:Mw.TRACER,name:kw.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),n=new IL(e.mediaStreamTrack,e.encoderConfig?TD(e.encoderConfig):{},t,!1);return YN.info("create custom audio track success with config",e,"trackId",n.getTrackId()),i.onSuccess(n.getTrackId()),n},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},s=hO(8,"track-buf-"),a=eD.reportApiInvoke(null,{id:s,tag:Mw.TRACER,name:kw.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(_N("DISABLE_WEBAUDIO"))throw new mw(Ew.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");YN.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=OL.get(e);if(t)return YN.debug("use cached audio resource: ",e),t;try{i=(await wO((()=>Ab.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new mw(Ew.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Wh(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new mw(Ew.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new mw(Ew.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=$D();return new Wh(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new mw(Ew.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&OL.set(e,n),n}(r,i)}catch(e){return a.onError(e),e.throw(YN)}const d=new wL(r),l=new AL(c,d,n?TD(n):{},s);return YN.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(YN.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw YN.debug("Invalid appType"),new tD(Ew.INVALID_PARAMS,"invalid app type",e);pN("APP_TYPE",Math.floor(e))},setLogLevel:function(e){YN.setLogLevel(e)},enableLogUpload:function(){_N("USE_NEW_LOG")?pN("UPLOAD_LOG",!0):YN.enableLogUpload()},disableLogUpload:function(){_N("USE_NEW_LOG")?pN("UPLOAD_LOG",!1):YN.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new vF},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eD.reportApiInvoke(null,{tag:Mw.TRACER,name:kw.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof IL||e instanceof Nk)){const e=new tD(Ew.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof IL?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new Wh((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:n,maxVolumeLevel:o,result:t};YN.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=eD.reportApiInvoke(null,{tag:Mw.TRACER,name:kw.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof pk||e instanceof Ok)){const e=new tD(Ew.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof pk?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,(Wb()||jb())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([r]),o.play();const s=document.createElement("canvas");s.width=160,s.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,o=0,s=null;return new Wh(((a,c)=>{function d(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new tD(Ew.UNEXPECTED_ERROR,"can not get canvas 2d context.");return YN.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e{r&&(r(),a(o))}),t),r=iP((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw i.onError(e),e}WB===Lb.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return YN.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:jV,audioElementPlayCenter:vP,resumeAudioContext:function(){vP.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){GG.processExternalMediaAEC(e)},registerExtensions:function(e){const t=_N("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Dn(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=YN.extLog,i.reporter.hookApiInvoke=eD.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach((e=>{i.parameters[e]=_N(e)}))})),uz("PLUGIN_INFO",t)},ChannelMediaRelayError:DU,ChannelMediaRelayEvent:OU,ChannelMediaRelayState:NU,RemoteStreamFallbackType:yD,RemoteStreamType:ID,ConnectionDisconnectedReason:Vw,AudienceLatencyLevelType:xw,AREAS:UU,preload:async function(e,t,i,n){return nj(e,t,i,n)}});return Object.defineProperties(hz,{onAudioAutoplayFailed:{get:()=>TP.onAudioAutoplayFailed,set:e=>{TP.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>TP.onAutoplayFailed,set:e=>{TP.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>hz._onSecurityPolicyViolation,set(e){hz._onSecurityPolicyViolation=e,YG(e)}},__CLIENT_LIST__:{get:()=>_N("SHOW_GLOBAL_CLIENT_LIST")?TM:[]}}),mP.on(FD.CAMERA_DEVICE_CHANGED,(e=>{YN.info("camera device changed",JSON.stringify(e)),hz.onCameraChanged&&hz.onCameraChanged(e),hz.safeEmit(tx.CAMERA_CHANGED,e)})),mP.on(FD.RECORDING_DEVICE_CHANGED,(e=>{YN.info("microphone device changed",JSON.stringify(e)),hz.onMicrophoneChanged&&hz.onMicrophoneChanged(e),hz.safeEmit(tx.MICROPHONE_CHANGED,e)})),mP.on(FD.PLAYOUT_DEVICE_CHANGED,(e=>{YN.debug("playout device changed",JSON.stringify(e)),hz.onPlaybackDeviceChanged&&hz.onPlaybackDeviceChanged(e),hz.safeEmit(tx.PLAYBACK_DEVICE_CHANGED,e)})),vP.onAutoplayFailed=()=>{YN.info("detect audio element autoplay failed"),TP.onAudioAutoplayFailed&&TP.onAudioAutoplayFailed()},ZD.on("autoplay-failed",(()=>{YN.info("detect webaudio autoplay failed"),TP.onAudioAutoplayFailed&&TP.onAudioAutoplayFailed(),hz.safeEmit(tx.AUTOPLAY_FAILED)})),ZD.on(sD.STATE_CHANGE,((e,t)=>{YN.info("audio context state changed: ".concat(t," => ").concat(e)),hz.onAudioContextStateChanged&&hz.onAudioContextStateChanged(e,t),hz.safeEmit(tx.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),Jw.on(Kw.NETWORK_STATE_CHANGE,((e,t)=>{YN.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=hz),hz}));